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": "ttps://registry.npmjs.org/-/user/org.couchdb.user:bobzoller')\n .yields(makeError('not found', 'E404'",
"end": 601,
"score": 0.874629020690918,
"start": 592,
"tag": "USERNAME",
"value": "bobzoller"
},
{
"context": "fined', ->\n expect(auth.sync.authentic... | test/sinopia_npm.test.coffee | goodeggs/sinopia-npm | 4 | fibrous = require 'fibrous'
require 'mocha-sinon'
{expect} = chai = require 'chai'
chai.use require 'sinon-chai'
RegClient = require 'npm-registry-client'
ms = require 'to-ms'
sinopiaNpm = require '..'
makeError = (message, code) ->
e = new Error(message)
e.code = code
e
describe 'sinopia-npm', ->
{npm, auth} = {}
beforeEach ->
npm = new RegClient
auth = sinopiaNpm client: npm
describe '::authenticate', ->
describe 'unknown user', ->
beforeEach ->
@sinon.stub(npm, 'get')
.withArgs('https://registry.npmjs.org/-/user/org.couchdb.user:bobzoller')
.yields(makeError('not found', 'E404'))
it 'returns undefined', ->
expect(auth.sync.authenticate('bobzoller', 'foobar')).to.be.undefined
describe 'incorrect password', ->
beforeEach ->
@sinon.stub(npm, 'get')
.withArgs('https://registry.npmjs.org/-/user/org.couchdb.user:bobzoller')
.yields(null, {email: 'bob@example.com', name: 'bobzoller'})
@sinon.stub(npm, 'adduser')
.withArgs('https://registry.npmjs.org', auth: {username: 'bobzoller', email: 'bob@example.com', password: 'foobar'}, timeout: 1000)
.yields(makeError('bad auth', 'E400'))
it 'returns false', ->
expect(auth.sync.authenticate('bobzoller', 'foobar')).to.equal false
describe 'correct password', ->
beforeEach ->
@sinon.stub(npm, 'get')
.withArgs('https://registry.npmjs.org/-/user/org.couchdb.user:bobzoller')
.yields(null, {email: 'bob@example.com', name: 'bobzoller'})
@sinon.stub(npm, 'adduser')
.withArgs('https://registry.npmjs.org', auth: {username: 'bobzoller', email: 'bob@example.com', password: 'foobar'}, timeout: 1000)
.yields(null, {"ok": true})
describe 'a single call', ->
it 'returns array of perms', ->
expect(auth.sync.authenticate('bobzoller', 'foobar')).to.eql ['bobzoller']
describe 'multiple calls', ->
{clock} = {}
beforeEach ->
clock = @sinon.useFakeTimers()
it 'caches the authentication for 15 minutes', ->
expect(auth.sync.authenticate('bobzoller', 'foobar')).to.eql ['bobzoller']
expect(auth.sync.authenticate('bobzoller', 'foobar')).to.eql ['bobzoller']
expect(npm.get).to.have.been.calledOnce
expect(npm.adduser).to.have.been.calledOnce
clock.tick ms.minutes(16).valueOf()
expect(auth.sync.authenticate('bobzoller', 'foobar')).to.eql ['bobzoller']
expect(auth.sync.authenticate('bobzoller', 'foobar')).to.eql ['bobzoller']
expect(npm.get).to.have.been.calledTwice
expect(npm.adduser).to.have.been.calledTwice
| 135605 | fibrous = require 'fibrous'
require 'mocha-sinon'
{expect} = chai = require 'chai'
chai.use require 'sinon-chai'
RegClient = require 'npm-registry-client'
ms = require 'to-ms'
sinopiaNpm = require '..'
makeError = (message, code) ->
e = new Error(message)
e.code = code
e
describe 'sinopia-npm', ->
{npm, auth} = {}
beforeEach ->
npm = new RegClient
auth = sinopiaNpm client: npm
describe '::authenticate', ->
describe 'unknown user', ->
beforeEach ->
@sinon.stub(npm, 'get')
.withArgs('https://registry.npmjs.org/-/user/org.couchdb.user:bobzoller')
.yields(makeError('not found', 'E404'))
it 'returns undefined', ->
expect(auth.sync.authenticate('bobzoller', 'foobar')).to.be.undefined
describe 'incorrect password', ->
beforeEach ->
@sinon.stub(npm, 'get')
.withArgs('https://registry.npmjs.org/-/user/org.couchdb.user:bobzoller')
.yields(null, {email: '<EMAIL>', name: 'bobzoller'})
@sinon.stub(npm, 'adduser')
.withArgs('https://registry.npmjs.org', auth: {username: 'bobzoller', email: '<EMAIL>', password: '<PASSWORD>'}, timeout: 1000)
.yields(makeError('bad auth', 'E400'))
it 'returns false', ->
expect(auth.sync.authenticate('bobzoller', 'foobar')).to.equal false
describe 'correct password', ->
beforeEach ->
@sinon.stub(npm, 'get')
.withArgs('https://registry.npmjs.org/-/user/org.couchdb.user:bobzoller')
.yields(null, {email: '<EMAIL>', name: 'bobz<NAME>ler'})
@sinon.stub(npm, 'adduser')
.withArgs('https://registry.npmjs.org', auth: {username: 'bobzoller', email: '<EMAIL>', password: '<PASSWORD>'}, timeout: 1000)
.yields(null, {"ok": true})
describe 'a single call', ->
it 'returns array of perms', ->
expect(auth.sync.authenticate('bobzoller', 'foobar')).to.eql ['bobzoller']
describe 'multiple calls', ->
{clock} = {}
beforeEach ->
clock = @sinon.useFakeTimers()
it 'caches the authentication for 15 minutes', ->
expect(auth.sync.authenticate('bobzoller', 'foobar')).to.eql ['bobzoller']
expect(auth.sync.authenticate('bobzoller', 'foobar')).to.eql ['bobzoller']
expect(npm.get).to.have.been.calledOnce
expect(npm.adduser).to.have.been.calledOnce
clock.tick ms.minutes(16).valueOf()
expect(auth.sync.authenticate('bobzoller', 'foobar')).to.eql ['bobzoller']
expect(auth.sync.authenticate('bobzoller', 'foobar')).to.eql ['bobzoller']
expect(npm.get).to.have.been.calledTwice
expect(npm.adduser).to.have.been.calledTwice
| true | fibrous = require 'fibrous'
require 'mocha-sinon'
{expect} = chai = require 'chai'
chai.use require 'sinon-chai'
RegClient = require 'npm-registry-client'
ms = require 'to-ms'
sinopiaNpm = require '..'
makeError = (message, code) ->
e = new Error(message)
e.code = code
e
describe 'sinopia-npm', ->
{npm, auth} = {}
beforeEach ->
npm = new RegClient
auth = sinopiaNpm client: npm
describe '::authenticate', ->
describe 'unknown user', ->
beforeEach ->
@sinon.stub(npm, 'get')
.withArgs('https://registry.npmjs.org/-/user/org.couchdb.user:bobzoller')
.yields(makeError('not found', 'E404'))
it 'returns undefined', ->
expect(auth.sync.authenticate('bobzoller', 'foobar')).to.be.undefined
describe 'incorrect password', ->
beforeEach ->
@sinon.stub(npm, 'get')
.withArgs('https://registry.npmjs.org/-/user/org.couchdb.user:bobzoller')
.yields(null, {email: 'PI:EMAIL:<EMAIL>END_PI', name: 'bobzoller'})
@sinon.stub(npm, 'adduser')
.withArgs('https://registry.npmjs.org', auth: {username: 'bobzoller', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI'}, timeout: 1000)
.yields(makeError('bad auth', 'E400'))
it 'returns false', ->
expect(auth.sync.authenticate('bobzoller', 'foobar')).to.equal false
describe 'correct password', ->
beforeEach ->
@sinon.stub(npm, 'get')
.withArgs('https://registry.npmjs.org/-/user/org.couchdb.user:bobzoller')
.yields(null, {email: 'PI:EMAIL:<EMAIL>END_PI', name: 'bobzPI:NAME:<NAME>END_PIler'})
@sinon.stub(npm, 'adduser')
.withArgs('https://registry.npmjs.org', auth: {username: 'bobzoller', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI'}, timeout: 1000)
.yields(null, {"ok": true})
describe 'a single call', ->
it 'returns array of perms', ->
expect(auth.sync.authenticate('bobzoller', 'foobar')).to.eql ['bobzoller']
describe 'multiple calls', ->
{clock} = {}
beforeEach ->
clock = @sinon.useFakeTimers()
it 'caches the authentication for 15 minutes', ->
expect(auth.sync.authenticate('bobzoller', 'foobar')).to.eql ['bobzoller']
expect(auth.sync.authenticate('bobzoller', 'foobar')).to.eql ['bobzoller']
expect(npm.get).to.have.been.calledOnce
expect(npm.adduser).to.have.been.calledOnce
clock.tick ms.minutes(16).valueOf()
expect(auth.sync.authenticate('bobzoller', 'foobar')).to.eql ['bobzoller']
expect(auth.sync.authenticate('bobzoller', 'foobar')).to.eql ['bobzoller']
expect(npm.get).to.have.been.calledTwice
expect(npm.adduser).to.have.been.calledTwice
|
[
{
"context": " = $('#password', @$el).val()\n password2 = $('#password2', @$el).val()\n bothThere = Boolean(password1)",
"end": 6647,
"score": 0.5357905030250549,
"start": 6639,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " return\n if bothThere\n me.set('pa... | app/views/account/settings_view.coffee | Melondonut/codecombat | 0 | RootView = require 'views/kinds/RootView'
template = require 'templates/account/settings'
{me} = require 'lib/auth'
forms = require 'lib/forms'
User = require 'models/User'
AuthModalView = require 'views/modal/auth_modal'
WizardSettingsView = require './wizard_settings_view'
JobProfileView = require './job_profile_view'
module.exports = class SettingsView extends RootView
id: 'account-settings-view'
template: template
changedFields: [] # DOM input fields
events:
'click #save-button': 'save'
'change #settings-panes input:checkbox': (e) -> @trigger 'checkboxToggled', e
'keyup #settings-panes input:text, #settings-panes input:password': (e) -> @trigger 'inputChanged', e
'keyup #name': 'onNameChange'
'click #toggle-all-button': 'toggleEmailSubscriptions'
'keypress #settings-panes': 'onKeyPress'
constructor: (options) ->
@save = _.debounce(@save, 200)
@onNameChange = _.debounce @checkNameExists, 500
super options
return unless me
@listenTo(me, 'invalid', (errors) -> forms.applyErrorsToForm(@$el, me.validationError))
@on 'checkboxToggled', @onToggle
@on 'checkboxToggled', @onInputChanged
@on 'inputChanged', @onInputChanged
@on 'enterPressed', @onEnter
onInputChanged: (e) ->
return @enableSaveButton() unless e?.currentTarget
that = e.currentTarget
$that = $(that)
savedValue = $that.data 'saved-value'
currentValue = $that.val()
if savedValue isnt currentValue
@changedFields.push that unless that in @changedFields
@enableSaveButton()
else
_.pull @changedFields, that
@disableSaveButton() if _.isEmpty @changedFields
onToggle: (e) ->
$that = $(e.currentTarget)
$that.val $that[0].checked
onEnter: ->
@save()
onKeyPress: (e) ->
@trigger 'enterPressed', e if e.which is 13
enableSaveButton: ->
$('#save-button', @$el).removeClass 'disabled'
$('#save-button', @$el).removeClass 'btn-danger'
$('#save-button', @$el).removeAttr 'disabled'
$('#save-button', @$el).text 'Save'
disableSaveButton: ->
$('#save-button', @$el).addClass 'disabled'
$('#save-button', @$el).removeClass 'btn-danger'
$('#save-button', @$el).attr 'disabled', "true"
$('#save-button', @$el).text 'No Changes'
checkNameExists: =>
name = $('#name', @$el).val()
return if name is me.get 'name'
User.getUnconflictedName name, (newName) =>
forms.clearFormAlerts(@$el)
if name is newName
@suggestedName = undefined
else
@suggestedName = newName
forms.setErrorToProperty @$el, 'name', "That name is taken! How about #{newName}?", true
afterRender: ->
super()
$('#settings-tabs a', @$el).click((e) =>
e.preventDefault()
$(e.target).tab('show')
# make sure errors show up in the general pane, but keep the password pane clean
$('#password-pane input').val('')
#@save() unless $(e.target).attr('href') is '#password-pane'
forms.clearFormAlerts($('#password-pane', @$el))
)
@chooseTab(location.hash.replace('#', ''))
wizardSettingsView = new WizardSettingsView()
@listenTo wizardSettingsView, 'change', @enableSaveButton
@insertSubView wizardSettingsView
@jobProfileView = new JobProfileView()
@listenTo @jobProfileView, 'change', @enableSaveButton
@insertSubView @jobProfileView
_.defer => @buildPictureTreema() # Not sure why, but the Treemas don't fully build without this if you reload the page.
afterInsert: ->
super()
$('#email-pane input[type="checkbox"]').on 'change', ->
$(@).addClass 'changed'
if me.get('anonymous')
@openModalView new AuthModalView()
@updateSavedValues()
chooseTab: (category) ->
id = "##{category}-pane"
pane = $(id, @$el)
return @chooseTab('general') unless pane.length or category is 'general'
loc = "a[href=#{id}]"
$(loc, @$el).tab('show')
$('.tab-pane').removeClass('active')
pane.addClass('active')
@currentTab = category
getRenderData: ->
c = super()
return c unless me
c.subs = {}
c.subs[sub] = 1 for sub in c.me.getEnabledEmails()
c.showsJobProfileTab = me.isAdmin() or me.get('jobProfile') or location.hash.search('job-profile-') isnt -1
c
getSubscriptions: ->
inputs = ($(i) for i in $('#email-pane input[type="checkbox"].changed', @$el))
emailNames = (i.attr('name').replace('email_', '') for i in inputs)
enableds = (i.prop('checked') for i in inputs)
_.zipObject emailNames, enableds
toggleEmailSubscriptions: =>
subs = @getSubscriptions()
$('#email-pane input[type="checkbox"]', @$el).prop('checked', not _.any(_.values(subs))).addClass('changed')
@save()
buildPictureTreema: ->
data = photoURL: me.get('photoURL')
data.photoURL = null if data.photoURL?.search('gravatar') isnt -1 # Old style
schema = $.extend true, {}, me.schema()
schema.properties = _.pick me.schema().properties, 'photoURL'
schema.required = ['photoURL']
treemaOptions =
filePath: "db/user/#{me.id}"
schema: schema
data: data
callbacks: {change: @onPictureChanged}
@pictureTreema = @$el.find('#picture-treema').treema treemaOptions
@pictureTreema?.build()
@pictureTreema?.open()
@$el.find('.gravatar-fallback').toggle not me.get 'photoURL'
onPictureChanged: (e) =>
@trigger 'inputChanged', e
@$el.find('.gravatar-fallback').toggle not me.get 'photoURL'
save: (e) ->
$('#settings-tabs input').removeClass 'changed'
forms.clearFormAlerts(@$el)
@grabData()
res = me.validate()
if res?
console.error 'Couldn\'t save because of validation errors:', res
forms.applyErrorsToForm(@$el, res)
return
return unless me.hasLocalChanges()
res = me.patch()
return unless res
save = $('#save-button', @$el).text($.i18n.t('common.saving', defaultValue: 'Saving...'))
.removeClass('btn-danger').addClass('btn-success').show()
res.error ->
errors = JSON.parse(res.responseText)
forms.applyErrorsToForm(@$el, errors)
save.text($.i18n.t('account_settings.error_saving', defaultValue: 'Error Saving')).removeClass('btn-success').addClass('btn-danger', 500)
res.success (model, response, options) =>
@changedFields = []
@updateSavedValues()
save.text($.i18n.t('account_settings.saved', defaultValue: 'Changes Saved')).removeClass('btn-success', 500).attr('disabled', 'true')
grabData: ->
@grabPasswordData()
@grabOtherData()
grabPasswordData: ->
password1 = $('#password', @$el).val()
password2 = $('#password2', @$el).val()
bothThere = Boolean(password1) and Boolean(password2)
if bothThere and password1 isnt password2
message = $.i18n.t('account_settings.password_mismatch', defaultValue: 'Password does not match.')
err = [message: message, property: 'password2', formatted: true]
forms.applyErrorsToForm(@$el, err)
return
if bothThere
me.set('password', password1)
else if password1
message = $.i18n.t('account_settings.password_repeat', defaultValue: 'Please repeat your password.')
err = [message: message, property: 'password2', formatted: true]
forms.applyErrorsToForm(@$el, err)
grabOtherData: ->
$('#name', @$el).val @suggestedName if @suggestedName
me.set 'name', $('#name', @$el).val()
me.set 'email', $('#email', @$el).val()
for emailName, enabled of @getSubscriptions()
me.setEmailSubscription emailName, enabled
me.set 'photoURL', @pictureTreema.get('/photoURL')
adminCheckbox = @$el.find('#admin')
if adminCheckbox.length
permissions = []
permissions.push 'admin' if adminCheckbox.prop('checked')
me.set('permissions', permissions)
jobProfile = me.get('jobProfile') ? {}
updated = false
for key, val of @jobProfileView.getData()
updated = updated or not _.isEqual jobProfile[key], val
jobProfile[key] = val
if updated
jobProfile.updated = (new Date()).toISOString()
me.set 'jobProfile', jobProfile
updateSavedValues: ->
$('#settings-panes input:text').each ->
$(@).data 'saved-value', $(@).val()
$('#settings-panes input:checkbox').each ->
$(@).data 'saved-value', JSON.stringify $(@)[0].checked
| 172239 | RootView = require 'views/kinds/RootView'
template = require 'templates/account/settings'
{me} = require 'lib/auth'
forms = require 'lib/forms'
User = require 'models/User'
AuthModalView = require 'views/modal/auth_modal'
WizardSettingsView = require './wizard_settings_view'
JobProfileView = require './job_profile_view'
module.exports = class SettingsView extends RootView
id: 'account-settings-view'
template: template
changedFields: [] # DOM input fields
events:
'click #save-button': 'save'
'change #settings-panes input:checkbox': (e) -> @trigger 'checkboxToggled', e
'keyup #settings-panes input:text, #settings-panes input:password': (e) -> @trigger 'inputChanged', e
'keyup #name': 'onNameChange'
'click #toggle-all-button': 'toggleEmailSubscriptions'
'keypress #settings-panes': 'onKeyPress'
constructor: (options) ->
@save = _.debounce(@save, 200)
@onNameChange = _.debounce @checkNameExists, 500
super options
return unless me
@listenTo(me, 'invalid', (errors) -> forms.applyErrorsToForm(@$el, me.validationError))
@on 'checkboxToggled', @onToggle
@on 'checkboxToggled', @onInputChanged
@on 'inputChanged', @onInputChanged
@on 'enterPressed', @onEnter
onInputChanged: (e) ->
return @enableSaveButton() unless e?.currentTarget
that = e.currentTarget
$that = $(that)
savedValue = $that.data 'saved-value'
currentValue = $that.val()
if savedValue isnt currentValue
@changedFields.push that unless that in @changedFields
@enableSaveButton()
else
_.pull @changedFields, that
@disableSaveButton() if _.isEmpty @changedFields
onToggle: (e) ->
$that = $(e.currentTarget)
$that.val $that[0].checked
onEnter: ->
@save()
onKeyPress: (e) ->
@trigger 'enterPressed', e if e.which is 13
enableSaveButton: ->
$('#save-button', @$el).removeClass 'disabled'
$('#save-button', @$el).removeClass 'btn-danger'
$('#save-button', @$el).removeAttr 'disabled'
$('#save-button', @$el).text 'Save'
disableSaveButton: ->
$('#save-button', @$el).addClass 'disabled'
$('#save-button', @$el).removeClass 'btn-danger'
$('#save-button', @$el).attr 'disabled', "true"
$('#save-button', @$el).text 'No Changes'
checkNameExists: =>
name = $('#name', @$el).val()
return if name is me.get 'name'
User.getUnconflictedName name, (newName) =>
forms.clearFormAlerts(@$el)
if name is newName
@suggestedName = undefined
else
@suggestedName = newName
forms.setErrorToProperty @$el, 'name', "That name is taken! How about #{newName}?", true
afterRender: ->
super()
$('#settings-tabs a', @$el).click((e) =>
e.preventDefault()
$(e.target).tab('show')
# make sure errors show up in the general pane, but keep the password pane clean
$('#password-pane input').val('')
#@save() unless $(e.target).attr('href') is '#password-pane'
forms.clearFormAlerts($('#password-pane', @$el))
)
@chooseTab(location.hash.replace('#', ''))
wizardSettingsView = new WizardSettingsView()
@listenTo wizardSettingsView, 'change', @enableSaveButton
@insertSubView wizardSettingsView
@jobProfileView = new JobProfileView()
@listenTo @jobProfileView, 'change', @enableSaveButton
@insertSubView @jobProfileView
_.defer => @buildPictureTreema() # Not sure why, but the Treemas don't fully build without this if you reload the page.
afterInsert: ->
super()
$('#email-pane input[type="checkbox"]').on 'change', ->
$(@).addClass 'changed'
if me.get('anonymous')
@openModalView new AuthModalView()
@updateSavedValues()
chooseTab: (category) ->
id = "##{category}-pane"
pane = $(id, @$el)
return @chooseTab('general') unless pane.length or category is 'general'
loc = "a[href=#{id}]"
$(loc, @$el).tab('show')
$('.tab-pane').removeClass('active')
pane.addClass('active')
@currentTab = category
getRenderData: ->
c = super()
return c unless me
c.subs = {}
c.subs[sub] = 1 for sub in c.me.getEnabledEmails()
c.showsJobProfileTab = me.isAdmin() or me.get('jobProfile') or location.hash.search('job-profile-') isnt -1
c
getSubscriptions: ->
inputs = ($(i) for i in $('#email-pane input[type="checkbox"].changed', @$el))
emailNames = (i.attr('name').replace('email_', '') for i in inputs)
enableds = (i.prop('checked') for i in inputs)
_.zipObject emailNames, enableds
toggleEmailSubscriptions: =>
subs = @getSubscriptions()
$('#email-pane input[type="checkbox"]', @$el).prop('checked', not _.any(_.values(subs))).addClass('changed')
@save()
buildPictureTreema: ->
data = photoURL: me.get('photoURL')
data.photoURL = null if data.photoURL?.search('gravatar') isnt -1 # Old style
schema = $.extend true, {}, me.schema()
schema.properties = _.pick me.schema().properties, 'photoURL'
schema.required = ['photoURL']
treemaOptions =
filePath: "db/user/#{me.id}"
schema: schema
data: data
callbacks: {change: @onPictureChanged}
@pictureTreema = @$el.find('#picture-treema').treema treemaOptions
@pictureTreema?.build()
@pictureTreema?.open()
@$el.find('.gravatar-fallback').toggle not me.get 'photoURL'
onPictureChanged: (e) =>
@trigger 'inputChanged', e
@$el.find('.gravatar-fallback').toggle not me.get 'photoURL'
save: (e) ->
$('#settings-tabs input').removeClass 'changed'
forms.clearFormAlerts(@$el)
@grabData()
res = me.validate()
if res?
console.error 'Couldn\'t save because of validation errors:', res
forms.applyErrorsToForm(@$el, res)
return
return unless me.hasLocalChanges()
res = me.patch()
return unless res
save = $('#save-button', @$el).text($.i18n.t('common.saving', defaultValue: 'Saving...'))
.removeClass('btn-danger').addClass('btn-success').show()
res.error ->
errors = JSON.parse(res.responseText)
forms.applyErrorsToForm(@$el, errors)
save.text($.i18n.t('account_settings.error_saving', defaultValue: 'Error Saving')).removeClass('btn-success').addClass('btn-danger', 500)
res.success (model, response, options) =>
@changedFields = []
@updateSavedValues()
save.text($.i18n.t('account_settings.saved', defaultValue: 'Changes Saved')).removeClass('btn-success', 500).attr('disabled', 'true')
grabData: ->
@grabPasswordData()
@grabOtherData()
grabPasswordData: ->
password1 = $('#password', @$el).val()
password2 = $('#<PASSWORD>2', @$el).val()
bothThere = Boolean(password1) and Boolean(password2)
if bothThere and password1 isnt password2
message = $.i18n.t('account_settings.password_mismatch', defaultValue: 'Password does not match.')
err = [message: message, property: 'password2', formatted: true]
forms.applyErrorsToForm(@$el, err)
return
if bothThere
me.set('password', <PASSWORD>1)
else if password1
message = $.i18n.t('account_settings.password_repeat', defaultValue: 'Please repeat your password.')
err = [message: message, property: 'password2', formatted: true]
forms.applyErrorsToForm(@$el, err)
grabOtherData: ->
$('#name', @$el).val @suggestedName if @suggestedName
me.set 'name', $('#name', @$el).val()
me.set 'email', $('#email', @$el).val()
for emailName, enabled of @getSubscriptions()
me.setEmailSubscription emailName, enabled
me.set 'photoURL', @pictureTreema.get('/photoURL')
adminCheckbox = @$el.find('#admin')
if adminCheckbox.length
permissions = []
permissions.push 'admin' if adminCheckbox.prop('checked')
me.set('permissions', permissions)
jobProfile = me.get('jobProfile') ? {}
updated = false
for key, val of @jobProfileView.getData()
updated = updated or not _.isEqual jobProfile[key], val
jobProfile[key] = val
if updated
jobProfile.updated = (new Date()).toISOString()
me.set 'jobProfile', jobProfile
updateSavedValues: ->
$('#settings-panes input:text').each ->
$(@).data 'saved-value', $(@).val()
$('#settings-panes input:checkbox').each ->
$(@).data 'saved-value', JSON.stringify $(@)[0].checked
| true | RootView = require 'views/kinds/RootView'
template = require 'templates/account/settings'
{me} = require 'lib/auth'
forms = require 'lib/forms'
User = require 'models/User'
AuthModalView = require 'views/modal/auth_modal'
WizardSettingsView = require './wizard_settings_view'
JobProfileView = require './job_profile_view'
module.exports = class SettingsView extends RootView
id: 'account-settings-view'
template: template
changedFields: [] # DOM input fields
events:
'click #save-button': 'save'
'change #settings-panes input:checkbox': (e) -> @trigger 'checkboxToggled', e
'keyup #settings-panes input:text, #settings-panes input:password': (e) -> @trigger 'inputChanged', e
'keyup #name': 'onNameChange'
'click #toggle-all-button': 'toggleEmailSubscriptions'
'keypress #settings-panes': 'onKeyPress'
constructor: (options) ->
@save = _.debounce(@save, 200)
@onNameChange = _.debounce @checkNameExists, 500
super options
return unless me
@listenTo(me, 'invalid', (errors) -> forms.applyErrorsToForm(@$el, me.validationError))
@on 'checkboxToggled', @onToggle
@on 'checkboxToggled', @onInputChanged
@on 'inputChanged', @onInputChanged
@on 'enterPressed', @onEnter
onInputChanged: (e) ->
return @enableSaveButton() unless e?.currentTarget
that = e.currentTarget
$that = $(that)
savedValue = $that.data 'saved-value'
currentValue = $that.val()
if savedValue isnt currentValue
@changedFields.push that unless that in @changedFields
@enableSaveButton()
else
_.pull @changedFields, that
@disableSaveButton() if _.isEmpty @changedFields
onToggle: (e) ->
$that = $(e.currentTarget)
$that.val $that[0].checked
onEnter: ->
@save()
onKeyPress: (e) ->
@trigger 'enterPressed', e if e.which is 13
enableSaveButton: ->
$('#save-button', @$el).removeClass 'disabled'
$('#save-button', @$el).removeClass 'btn-danger'
$('#save-button', @$el).removeAttr 'disabled'
$('#save-button', @$el).text 'Save'
disableSaveButton: ->
$('#save-button', @$el).addClass 'disabled'
$('#save-button', @$el).removeClass 'btn-danger'
$('#save-button', @$el).attr 'disabled', "true"
$('#save-button', @$el).text 'No Changes'
checkNameExists: =>
name = $('#name', @$el).val()
return if name is me.get 'name'
User.getUnconflictedName name, (newName) =>
forms.clearFormAlerts(@$el)
if name is newName
@suggestedName = undefined
else
@suggestedName = newName
forms.setErrorToProperty @$el, 'name', "That name is taken! How about #{newName}?", true
afterRender: ->
super()
$('#settings-tabs a', @$el).click((e) =>
e.preventDefault()
$(e.target).tab('show')
# make sure errors show up in the general pane, but keep the password pane clean
$('#password-pane input').val('')
#@save() unless $(e.target).attr('href') is '#password-pane'
forms.clearFormAlerts($('#password-pane', @$el))
)
@chooseTab(location.hash.replace('#', ''))
wizardSettingsView = new WizardSettingsView()
@listenTo wizardSettingsView, 'change', @enableSaveButton
@insertSubView wizardSettingsView
@jobProfileView = new JobProfileView()
@listenTo @jobProfileView, 'change', @enableSaveButton
@insertSubView @jobProfileView
_.defer => @buildPictureTreema() # Not sure why, but the Treemas don't fully build without this if you reload the page.
afterInsert: ->
super()
$('#email-pane input[type="checkbox"]').on 'change', ->
$(@).addClass 'changed'
if me.get('anonymous')
@openModalView new AuthModalView()
@updateSavedValues()
chooseTab: (category) ->
id = "##{category}-pane"
pane = $(id, @$el)
return @chooseTab('general') unless pane.length or category is 'general'
loc = "a[href=#{id}]"
$(loc, @$el).tab('show')
$('.tab-pane').removeClass('active')
pane.addClass('active')
@currentTab = category
getRenderData: ->
c = super()
return c unless me
c.subs = {}
c.subs[sub] = 1 for sub in c.me.getEnabledEmails()
c.showsJobProfileTab = me.isAdmin() or me.get('jobProfile') or location.hash.search('job-profile-') isnt -1
c
getSubscriptions: ->
inputs = ($(i) for i in $('#email-pane input[type="checkbox"].changed', @$el))
emailNames = (i.attr('name').replace('email_', '') for i in inputs)
enableds = (i.prop('checked') for i in inputs)
_.zipObject emailNames, enableds
toggleEmailSubscriptions: =>
subs = @getSubscriptions()
$('#email-pane input[type="checkbox"]', @$el).prop('checked', not _.any(_.values(subs))).addClass('changed')
@save()
buildPictureTreema: ->
data = photoURL: me.get('photoURL')
data.photoURL = null if data.photoURL?.search('gravatar') isnt -1 # Old style
schema = $.extend true, {}, me.schema()
schema.properties = _.pick me.schema().properties, 'photoURL'
schema.required = ['photoURL']
treemaOptions =
filePath: "db/user/#{me.id}"
schema: schema
data: data
callbacks: {change: @onPictureChanged}
@pictureTreema = @$el.find('#picture-treema').treema treemaOptions
@pictureTreema?.build()
@pictureTreema?.open()
@$el.find('.gravatar-fallback').toggle not me.get 'photoURL'
onPictureChanged: (e) =>
@trigger 'inputChanged', e
@$el.find('.gravatar-fallback').toggle not me.get 'photoURL'
save: (e) ->
$('#settings-tabs input').removeClass 'changed'
forms.clearFormAlerts(@$el)
@grabData()
res = me.validate()
if res?
console.error 'Couldn\'t save because of validation errors:', res
forms.applyErrorsToForm(@$el, res)
return
return unless me.hasLocalChanges()
res = me.patch()
return unless res
save = $('#save-button', @$el).text($.i18n.t('common.saving', defaultValue: 'Saving...'))
.removeClass('btn-danger').addClass('btn-success').show()
res.error ->
errors = JSON.parse(res.responseText)
forms.applyErrorsToForm(@$el, errors)
save.text($.i18n.t('account_settings.error_saving', defaultValue: 'Error Saving')).removeClass('btn-success').addClass('btn-danger', 500)
res.success (model, response, options) =>
@changedFields = []
@updateSavedValues()
save.text($.i18n.t('account_settings.saved', defaultValue: 'Changes Saved')).removeClass('btn-success', 500).attr('disabled', 'true')
grabData: ->
@grabPasswordData()
@grabOtherData()
grabPasswordData: ->
password1 = $('#password', @$el).val()
password2 = $('#PI:PASSWORD:<PASSWORD>END_PI2', @$el).val()
bothThere = Boolean(password1) and Boolean(password2)
if bothThere and password1 isnt password2
message = $.i18n.t('account_settings.password_mismatch', defaultValue: 'Password does not match.')
err = [message: message, property: 'password2', formatted: true]
forms.applyErrorsToForm(@$el, err)
return
if bothThere
me.set('password', PI:PASSWORD:<PASSWORD>END_PI1)
else if password1
message = $.i18n.t('account_settings.password_repeat', defaultValue: 'Please repeat your password.')
err = [message: message, property: 'password2', formatted: true]
forms.applyErrorsToForm(@$el, err)
grabOtherData: ->
$('#name', @$el).val @suggestedName if @suggestedName
me.set 'name', $('#name', @$el).val()
me.set 'email', $('#email', @$el).val()
for emailName, enabled of @getSubscriptions()
me.setEmailSubscription emailName, enabled
me.set 'photoURL', @pictureTreema.get('/photoURL')
adminCheckbox = @$el.find('#admin')
if adminCheckbox.length
permissions = []
permissions.push 'admin' if adminCheckbox.prop('checked')
me.set('permissions', permissions)
jobProfile = me.get('jobProfile') ? {}
updated = false
for key, val of @jobProfileView.getData()
updated = updated or not _.isEqual jobProfile[key], val
jobProfile[key] = val
if updated
jobProfile.updated = (new Date()).toISOString()
me.set 'jobProfile', jobProfile
updateSavedValues: ->
$('#settings-panes input:text').each ->
$(@).data 'saved-value', $(@).val()
$('#settings-panes input:checkbox').each ->
$(@).data 'saved-value', JSON.stringify $(@)[0].checked
|
[
{
"context": "###!\nCopyright (c) 2002-2017 \"Neo Technology,\"\nNetwork Engine for Objects in Lund AB [http://n",
"end": 44,
"score": 0.7367420196533203,
"start": 34,
"tag": "NAME",
"value": "Technology"
}
] | src/components/D3Visualization/lib/visualization/components/collision.coffee | yezonggang/zcfx-admin-master | 24 | ###!
Copyright (c) 2002-2017 "Neo Technology,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
'use strict'
neo.collision = do ->
collision = {}
collide = (node) ->
r = node.radius + 10
nx1 = node.x - r
nx2 = node.x + r
ny1 = node.y - r
ny2 = node.y + r
return (quad, x1, y1, x2, y2) ->
if (quad.point && (quad.point != node))
x = node.x - quad.point.x
y = node.y - quad.point.y
l = Math.sqrt(x * x + y * y)
r = node.radius + 10 + quad.point.radius
if (l < r)
l = (l - r) / l * .5
node.x -= x *= l
node.y -= y *= l
quad.point.x += x
quad.point.y += y
x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1
collision.avoidOverlap = (nodes) ->
q = d3.geom.quadtree(nodes)
for n in nodes
q.visit collide(n)
collision | 32205 | ###!
Copyright (c) 2002-2017 "Neo <NAME>,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
'use strict'
neo.collision = do ->
collision = {}
collide = (node) ->
r = node.radius + 10
nx1 = node.x - r
nx2 = node.x + r
ny1 = node.y - r
ny2 = node.y + r
return (quad, x1, y1, x2, y2) ->
if (quad.point && (quad.point != node))
x = node.x - quad.point.x
y = node.y - quad.point.y
l = Math.sqrt(x * x + y * y)
r = node.radius + 10 + quad.point.radius
if (l < r)
l = (l - r) / l * .5
node.x -= x *= l
node.y -= y *= l
quad.point.x += x
quad.point.y += y
x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1
collision.avoidOverlap = (nodes) ->
q = d3.geom.quadtree(nodes)
for n in nodes
q.visit collide(n)
collision | true | ###!
Copyright (c) 2002-2017 "Neo PI:NAME:<NAME>END_PI,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
'use strict'
neo.collision = do ->
collision = {}
collide = (node) ->
r = node.radius + 10
nx1 = node.x - r
nx2 = node.x + r
ny1 = node.y - r
ny2 = node.y + r
return (quad, x1, y1, x2, y2) ->
if (quad.point && (quad.point != node))
x = node.x - quad.point.x
y = node.y - quad.point.y
l = Math.sqrt(x * x + y * y)
r = node.radius + 10 + quad.point.radius
if (l < r)
l = (l - r) / l * .5
node.x -= x *= l
node.y -= y *= l
quad.point.x += x
quad.point.y += y
x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1
collision.avoidOverlap = (nodes) ->
q = d3.geom.quadtree(nodes)
for n in nodes
q.visit collide(n)
collision |
[
{
"context": "gramming for microcontrollers\n# Copyright (c) 2018 Jon Nordby <jononor@gmail.com>\n# MicroFlo may be freely dist",
"end": 90,
"score": 0.9998371601104736,
"start": 80,
"tag": "NAME",
"value": "Jon Nordby"
},
{
"context": "microcontrollers\n# Copyright (c) 2018 Jon Nord... | test/protocol.coffee | microflo/microflo | 136 | ### MicroFlo - Flow-Based Programming for microcontrollers
# Copyright (c) 2018 Jon Nordby <jononor@gmail.com>
# MicroFlo may be freely distributed under the MIT license
###
chai = require('chai')
fbpClient = require 'fbp-client'
address = 'ws://localhost:3334'
describe 'FBP runtime protocol', ->
client = null
# FIXME: setup own runtime, instead of relying on fbp-spec
before ->
fbpClient({address:address}).then (c) ->
client = c
return client.connect()
after ->
return
describe 'network:getstatus', ->
it 'should give started', ->
client.protocol.network.start({graph: 'main'})
.then (response) ->
chai.expect(response.started).to.equal true
describe 'network:edges', ->
describe 'with empty edges', ->
it 'should succeed', ->
edges = []
client.protocol.graph.clear({id: 'main'})
.then () ->
client.protocol.network.edges({graph: 'main', edges: edges})
.then (response) ->
chai.expect(response.edges).to.have.length edges.length
describe 'with non-exitsting node', ->
it 'should error', ->
edges = [
{ src: { node: 'fofo', port: 'out' }, tgt: { node: 'barb', port: 'in'} }
]
client.protocol.network.edges({graph: 'main', edges: edges})
.then (r) ->
chai.expect(r).to.not.exist
.catch (err) ->
chai.expect(err.message).to.contain 'No node'
chai.expect(err.message).to.contain 'fofo'
describe 'runtime:packet', ->
describe 'with data to non-existent port', ->
it 'should error', ->
client.protocol.graph.clear({id: 'main'})
.then () ->
client.protocol.runtime.packet({graph: 'main', port: 'noexist22', event: 'data', payload: 666})
.then (r) ->
chai.expect(r).to.not.exist
.catch (response) ->
chai.expect(response.message).to.contain 'No runtime inport named'
chai.expect(response.message).to.contain 'noexist22'
describe 'component:list', ->
it 'should return components', ->
client.protocol.component.list()
.then (response) ->
chai.expect(response).to.be.a 'array'
chai.expect(response[0]).to.include.keys ['name', 'description', 'subgraph']
names = response.map (c) -> c.name
chai.expect(names).to.include 'ToggleBoolean'
describe 'component:getsource', ->
describe 'with main graph', ->
it 'is not implemented', ->
client.protocol.component.getsource({name: 'default/main'})
.then (response) ->
chai.expect(response).to.include.keys ['name', 'code', 'language', 'library']
describe 'with a component', ->
it 'is not implemented', ->
client.protocol.component.getsource({name: 'ToggleBoolean'})
.then (response) ->
chai.expect(response).to.not.exist
.catch (err) ->
chai.expect(err.message).to.contain 'not implemented'
| 23663 | ### MicroFlo - Flow-Based Programming for microcontrollers
# Copyright (c) 2018 <NAME> <<EMAIL>>
# MicroFlo may be freely distributed under the MIT license
###
chai = require('chai')
fbpClient = require 'fbp-client'
address = 'ws://localhost:3334'
describe 'FBP runtime protocol', ->
client = null
# FIXME: setup own runtime, instead of relying on fbp-spec
before ->
fbpClient({address:address}).then (c) ->
client = c
return client.connect()
after ->
return
describe 'network:getstatus', ->
it 'should give started', ->
client.protocol.network.start({graph: 'main'})
.then (response) ->
chai.expect(response.started).to.equal true
describe 'network:edges', ->
describe 'with empty edges', ->
it 'should succeed', ->
edges = []
client.protocol.graph.clear({id: 'main'})
.then () ->
client.protocol.network.edges({graph: 'main', edges: edges})
.then (response) ->
chai.expect(response.edges).to.have.length edges.length
describe 'with non-exitsting node', ->
it 'should error', ->
edges = [
{ src: { node: 'fofo', port: 'out' }, tgt: { node: 'barb', port: 'in'} }
]
client.protocol.network.edges({graph: 'main', edges: edges})
.then (r) ->
chai.expect(r).to.not.exist
.catch (err) ->
chai.expect(err.message).to.contain 'No node'
chai.expect(err.message).to.contain 'fofo'
describe 'runtime:packet', ->
describe 'with data to non-existent port', ->
it 'should error', ->
client.protocol.graph.clear({id: 'main'})
.then () ->
client.protocol.runtime.packet({graph: 'main', port: 'noexist22', event: 'data', payload: 666})
.then (r) ->
chai.expect(r).to.not.exist
.catch (response) ->
chai.expect(response.message).to.contain 'No runtime inport named'
chai.expect(response.message).to.contain 'noexist22'
describe 'component:list', ->
it 'should return components', ->
client.protocol.component.list()
.then (response) ->
chai.expect(response).to.be.a 'array'
chai.expect(response[0]).to.include.keys ['name', 'description', 'subgraph']
names = response.map (c) -> c.name
chai.expect(names).to.include 'ToggleBoolean'
describe 'component:getsource', ->
describe 'with main graph', ->
it 'is not implemented', ->
client.protocol.component.getsource({name: 'default/main'})
.then (response) ->
chai.expect(response).to.include.keys ['name', 'code', 'language', 'library']
describe 'with a component', ->
it 'is not implemented', ->
client.protocol.component.getsource({name: 'ToggleBoolean'})
.then (response) ->
chai.expect(response).to.not.exist
.catch (err) ->
chai.expect(err.message).to.contain 'not implemented'
| true | ### MicroFlo - Flow-Based Programming for microcontrollers
# Copyright (c) 2018 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# MicroFlo may be freely distributed under the MIT license
###
chai = require('chai')
fbpClient = require 'fbp-client'
address = 'ws://localhost:3334'
describe 'FBP runtime protocol', ->
client = null
# FIXME: setup own runtime, instead of relying on fbp-spec
before ->
fbpClient({address:address}).then (c) ->
client = c
return client.connect()
after ->
return
describe 'network:getstatus', ->
it 'should give started', ->
client.protocol.network.start({graph: 'main'})
.then (response) ->
chai.expect(response.started).to.equal true
describe 'network:edges', ->
describe 'with empty edges', ->
it 'should succeed', ->
edges = []
client.protocol.graph.clear({id: 'main'})
.then () ->
client.protocol.network.edges({graph: 'main', edges: edges})
.then (response) ->
chai.expect(response.edges).to.have.length edges.length
describe 'with non-exitsting node', ->
it 'should error', ->
edges = [
{ src: { node: 'fofo', port: 'out' }, tgt: { node: 'barb', port: 'in'} }
]
client.protocol.network.edges({graph: 'main', edges: edges})
.then (r) ->
chai.expect(r).to.not.exist
.catch (err) ->
chai.expect(err.message).to.contain 'No node'
chai.expect(err.message).to.contain 'fofo'
describe 'runtime:packet', ->
describe 'with data to non-existent port', ->
it 'should error', ->
client.protocol.graph.clear({id: 'main'})
.then () ->
client.protocol.runtime.packet({graph: 'main', port: 'noexist22', event: 'data', payload: 666})
.then (r) ->
chai.expect(r).to.not.exist
.catch (response) ->
chai.expect(response.message).to.contain 'No runtime inport named'
chai.expect(response.message).to.contain 'noexist22'
describe 'component:list', ->
it 'should return components', ->
client.protocol.component.list()
.then (response) ->
chai.expect(response).to.be.a 'array'
chai.expect(response[0]).to.include.keys ['name', 'description', 'subgraph']
names = response.map (c) -> c.name
chai.expect(names).to.include 'ToggleBoolean'
describe 'component:getsource', ->
describe 'with main graph', ->
it 'is not implemented', ->
client.protocol.component.getsource({name: 'default/main'})
.then (response) ->
chai.expect(response).to.include.keys ['name', 'code', 'language', 'library']
describe 'with a component', ->
it 'is not implemented', ->
client.protocol.component.getsource({name: 'ToggleBoolean'})
.then (response) ->
chai.expect(response).to.not.exist
.catch (err) ->
chai.expect(err.message).to.contain 'not implemented'
|
[
{
"context": " # UserName+Password\n # Hull.login({login:'abcd@ef.com', password:'passwd', strategy:'redirect|popup', r",
"end": 6544,
"score": 0.9999178647994995,
"start": 6533,
"tag": "EMAIL",
"value": "abcd@ef.com"
},
{
"context": " # Hull.login({login:'abcd@ef.com', pa... | src/client/auth.coffee | fossabot/hull-js | 25 | assign = require '../polyfills/assign'
Promise = require '../utils/promises'
_ = require '../utils/lodash'
logger = require '../utils/logger'
EventBus = require '../utils/eventbus'
isMobile = require '../utils/is-mobile'
getNoUserPromise = ()->
Promise.reject({
reason: 'no_current_user',
message: 'User must be logged in to perform this action'
})
getUser = ()->
user = Hull.currentUser()
return (!!user && user.id?)
parseParams = (argsArray)->
opts = {}
while (next = argsArray.shift())
if _.isString next
if !login
login = next
else
password = next
else if _.isFunction next
if !callback
callback = next
else
errback = next
else if _.isObject(next) and !_.isEmpty(next)
if !login and !password
opts = next
else
opts.params = assign(next, opts.params||{})
if login
opts = if password then assign(opts, {login, password}) else assign(opts, {provider:login})
opts.params = opts.params || {}
callback = callback || ->
errback = errback || ->
opts.params.display ||= 'touch' if isMobile()
# Setup defaults for Popup login for Facebook on Desktop
# # Redirect login by default. if on Mobile.
# # Setup 'display' to be 'touch' for Facebook Login if on Mobile
if opts.provider == 'facebook'
opts.params.display ||= if opts.strategy == 'redirect' then 'page' else 'popup'
# TODO : OK to ignore `params` in this email login scenario ?
delete opts.params if opts.password?
{
options: opts
callback : callback
errback : errback
}
postForm = (path, method='post', params={}) ->
form = document.createElement("form")
form.setAttribute("method", method)
form.setAttribute("action", path)
for key of params
if params.hasOwnProperty key
hiddenField = document.createElement("input")
hiddenField.setAttribute("type", "hidden")
hiddenField.setAttribute("name", key)
hiddenField.setAttribute("value", params[key])
form.appendChild(hiddenField)
document.body.appendChild(form)
form.submit()
class Auth
constructor: (api, currentUser, currentConfig)->
@api = api
@currentUser = currentUser
@currentConfig = currentConfig
@_popupInterval = null
@_authenticating = null
@authServices = _.keys(@currentConfig.get('services.auth'))
isAuthenticating : -> @_authenticating?
# Generates the complete URL to be reached to validate login
generateAuthUrl : (opts={})->
@createAuthCallback()
params = opts.params || {}
params.app_id = @currentConfig.get('appId')
# The following is here for backward compatibility. Must be removed at first sight next time
params.callback_url = opts.redirect_url || params.callback_url || @currentConfig.get('callback_url') || @currentConfig.get('callbackUrl') || document.location.toString()
params.auth_referer = document.location.toString()
params.version = @currentConfig.get('version')
params._bid = @currentConfig.identifyBrowser().id
params._sid = @currentConfig.identifySession().id
querystring = _.map params,(v,k) ->
encodeURIComponent(k)+'='+encodeURIComponent(v)
.join('&')
"#{@currentConfig.get('orgUrl')}/auth/#{opts.provider}?#{querystring}"
createAuthCallback: =>
window.__hull_login_status__ = (hash) =>
window.__hull_login_status__ = null
@onAuthComplete(hash)
popupAuthWindow: (path, opts={})->
# Handle smaller Facebook popup windows
[width, height] = if opts.provider == 'facebook' and opts.params.display == 'popup' then [500, 400] else [1030, 550]
openerString = "location=0,status=0,width=#{width},height=#{height}"
w = window.open(path, "_auth",openerString)
# Support for cordova events
if window.device?.cordova
w?.addEventListener 'loadstart', (event)->
hash = try JSON.parse(Base64.decode(event.url.split('#')[1]))
if hash
window.__hull_login_status__(hash)
w.close()
# 30 seconds after creating popup, reject promise if still active.
setTimeout ()=>
@onAuthComplete({ success: false, error: { reason: 'timeout', message: 'Timeout for login (after 30 seconds), User never finished the auth' } })
, 90000
# Reject Promise if window has been closed
@_popupInterval = w? && setInterval =>
@onAuthComplete({ success: false, error: { reason: 'window_closed', message: 'User closed the window before finishing. He might have canceled' } }) if w?.closed
, 200
onAuthComplete : (hash)=>
return unless @_authenticating
if hash.success
@_authenticating.resolve({})
else
error = new Error("Login failed : #{hash?.error?.reason}")
error[k] = v for k, v of hash.error
@_authenticating.reject(error)
@_authenticating = null
clearInterval(@_popupInterval)
@_popupInterval = null
undefined
loginWithProvider : (opts)=>
isAuthenticating = @isAuthenticating()
return isAuthenticating if isAuthenticating
@_authenticating = {}
promise = new Promise (resolve, reject)=>
@_authenticating.resolve = resolve
@_authenticating.reject = reject
unless ~(_.indexOf(@authServices, opts.provider))
@_authenticating.reject
message: "No authentication service #{opts.provider} configured for the app"
reason: 'no_such_service'
return promise
@_authenticating.provider = opts.provider.toLowerCase()
authUrl = @generateAuthUrl(opts)
if opts.strategy == 'redirect'
# Don't do an early return to not break promise chain
window.location.href = authUrl
else
# Classic Popup Strategy
@popupAuthWindow(authUrl, opts)
promise
login : () =>
if @isAuthenticating()
# Return promise even if login is in progress.
msg = "Login in progress. Use `Hull.on('hull.user.login', callback)` to call `callback` when done."
logger.info msg
return Promise.reject {error: {reason:'in_progress', message: 'Login already in progress'}}
# Handle Legacy Format,
# Ensure New Format: Hash signature
# Preprocess Options
# Opts format is now : {login:"", password:"", params:{}} or {provider:"", params:{}}
{options, callback, errback} = parseParams(Array.prototype.slice.call(arguments))
if !(options?.provider? || options.login? || options.access_token?)
# UserName+Password
# Hull.login({login:'abcd@ef.com', password:'passwd', strategy:'redirect|popup', redirect:'...'})
unless options.login? and options.password?
msg = 'Seems like something is wrong in your Hull.login() call, We need a login and password fields to login. Read up here: http://www.hull.io/docs/references/hull_js/#user-signup-and-login'
logger.warn msg
return Promise.reject({error:{ reason:'missing_parameters', message:'Empty login or password' }})
if options.provider?
# Social Login
if options.access_token?
# Hull.login({provider:'facebook', access_token:'xxxx'})
provider = assign({}, options)
delete provider.provider
op = {}
op[options.provider] = provider
promise = @api.message('users', 'post', op)
else
# Hull.login({provider:'facebook', strategy:'redirect|popup', redirect:'...'})
promise = @loginWithProvider(options)
else
# Email Login
# Hull.login({login:'user@host.com', password:'xxxx'})
# Hull.login({access_token:'xxxxx'})
promise = @api.message('users/login', 'post', _.pick(options, 'login', 'password', 'access_token'))
if options.strategy == 'redirect' || !@currentConfig.getRemote('cookiesEnabled')
postUrl = @currentConfig.get('orgUrl')+'/api/v1/users/login'
options.redirect_url ||= window.location.href
promise = promise.then -> postForm(postUrl, 'post', options)
@completeLoginPromiseChain(promise, callback, errback)
logout: (options={}, callback, errback) =>
@currentConfig.resetIdentify()
@api.channel.rpc.resetIdentify()
promise = @api.message('logout')
if options.strategy == 'redirect' || !@currentConfig.getRemote('cookiesEnabled')
redirect_url = options.redirect_url || document.location.href
# Add this param to make sure safari actually redirects to the logoutUrl
b = new Date().getTime()
logoutUrl = @currentConfig.get('orgUrl') + '/api/v1/logout?b=' + b + '&redirect_url=' + encodeURIComponent(redirect_url)
promise.then -> document.location = logoutUrl
@completeLoginPromiseChain(promise,callback,errback)
resetPassword : (email=@currentUser.get('email'), callback, errback) =>
promise = @api.message('/users/request_password_reset', 'post', {email})
@completeLoginPromiseChain(promise,callback,errback)
confirmEmail : (email=@currentUser.get('email'), callback, errback) =>
promise = @api.message('/users/request_confirmation_email', 'post', {email})
@completeLoginPromiseChain(promise,callback,errback)
signup : (attrs, callback, errback) =>
promise = @api.message('users', 'POST', attrs)
if !@currentConfig.getRemote('cookiesEnabled')
postUrl = @currentConfig.get('orgUrl')+'/api/v1/users/login'
promise = promise.then (user)->
params = {
redirect_url: window.location.href,
access_token: user.access_token
}
postForm(postUrl, 'post', params)
@completeLoginPromiseChain(promise, callback, errback)
###*
* link an Identity to a Hull User
* @param {options} An options Hash
* @param {callback} Success callback
* @param {errback} error callback
* @return {Promise} A promise
###
linkIdentity : ()=>
return getNoUserPromise() unless getUser()
{options, callback, errback} = parseParams(Array.prototype.slice.call(arguments))
options.params.mode = 'connect'
@login(options, callback, errback)
###*
* unlink an Identity from a Hull User
* @param {options} An options Hash
* @param {callback} Success callback
* @param {errback} error callback
* @return {Promise} A promise
*
###
unlinkIdentity : ()=>
return getNoUserPromise() unless getUser()
{options, callback, errback} = parseParams(Array.prototype.slice.call(arguments))
promise = @api.message("me/identities/#{options.provider}", 'delete')
@completeLoginPromiseChain(promise,callback,errback)
completeLoginPromiseChain: (promise, callback,errback)=>
if promise && promise.then
callback = callback || ->
errback = errback || ->
p = promise.then @api.refreshUser, @emitLoginFailure
p.then callback, errback
p
emitLoginFailure : (err)->
EventBus.emit("hull.user.fail", err)
err
throw err
module.exports = Auth
| 200004 | assign = require '../polyfills/assign'
Promise = require '../utils/promises'
_ = require '../utils/lodash'
logger = require '../utils/logger'
EventBus = require '../utils/eventbus'
isMobile = require '../utils/is-mobile'
getNoUserPromise = ()->
Promise.reject({
reason: 'no_current_user',
message: 'User must be logged in to perform this action'
})
getUser = ()->
user = Hull.currentUser()
return (!!user && user.id?)
parseParams = (argsArray)->
opts = {}
while (next = argsArray.shift())
if _.isString next
if !login
login = next
else
password = next
else if _.isFunction next
if !callback
callback = next
else
errback = next
else if _.isObject(next) and !_.isEmpty(next)
if !login and !password
opts = next
else
opts.params = assign(next, opts.params||{})
if login
opts = if password then assign(opts, {login, password}) else assign(opts, {provider:login})
opts.params = opts.params || {}
callback = callback || ->
errback = errback || ->
opts.params.display ||= 'touch' if isMobile()
# Setup defaults for Popup login for Facebook on Desktop
# # Redirect login by default. if on Mobile.
# # Setup 'display' to be 'touch' for Facebook Login if on Mobile
if opts.provider == 'facebook'
opts.params.display ||= if opts.strategy == 'redirect' then 'page' else 'popup'
# TODO : OK to ignore `params` in this email login scenario ?
delete opts.params if opts.password?
{
options: opts
callback : callback
errback : errback
}
postForm = (path, method='post', params={}) ->
form = document.createElement("form")
form.setAttribute("method", method)
form.setAttribute("action", path)
for key of params
if params.hasOwnProperty key
hiddenField = document.createElement("input")
hiddenField.setAttribute("type", "hidden")
hiddenField.setAttribute("name", key)
hiddenField.setAttribute("value", params[key])
form.appendChild(hiddenField)
document.body.appendChild(form)
form.submit()
class Auth
constructor: (api, currentUser, currentConfig)->
@api = api
@currentUser = currentUser
@currentConfig = currentConfig
@_popupInterval = null
@_authenticating = null
@authServices = _.keys(@currentConfig.get('services.auth'))
isAuthenticating : -> @_authenticating?
# Generates the complete URL to be reached to validate login
generateAuthUrl : (opts={})->
@createAuthCallback()
params = opts.params || {}
params.app_id = @currentConfig.get('appId')
# The following is here for backward compatibility. Must be removed at first sight next time
params.callback_url = opts.redirect_url || params.callback_url || @currentConfig.get('callback_url') || @currentConfig.get('callbackUrl') || document.location.toString()
params.auth_referer = document.location.toString()
params.version = @currentConfig.get('version')
params._bid = @currentConfig.identifyBrowser().id
params._sid = @currentConfig.identifySession().id
querystring = _.map params,(v,k) ->
encodeURIComponent(k)+'='+encodeURIComponent(v)
.join('&')
"#{@currentConfig.get('orgUrl')}/auth/#{opts.provider}?#{querystring}"
createAuthCallback: =>
window.__hull_login_status__ = (hash) =>
window.__hull_login_status__ = null
@onAuthComplete(hash)
popupAuthWindow: (path, opts={})->
# Handle smaller Facebook popup windows
[width, height] = if opts.provider == 'facebook' and opts.params.display == 'popup' then [500, 400] else [1030, 550]
openerString = "location=0,status=0,width=#{width},height=#{height}"
w = window.open(path, "_auth",openerString)
# Support for cordova events
if window.device?.cordova
w?.addEventListener 'loadstart', (event)->
hash = try JSON.parse(Base64.decode(event.url.split('#')[1]))
if hash
window.__hull_login_status__(hash)
w.close()
# 30 seconds after creating popup, reject promise if still active.
setTimeout ()=>
@onAuthComplete({ success: false, error: { reason: 'timeout', message: 'Timeout for login (after 30 seconds), User never finished the auth' } })
, 90000
# Reject Promise if window has been closed
@_popupInterval = w? && setInterval =>
@onAuthComplete({ success: false, error: { reason: 'window_closed', message: 'User closed the window before finishing. He might have canceled' } }) if w?.closed
, 200
onAuthComplete : (hash)=>
return unless @_authenticating
if hash.success
@_authenticating.resolve({})
else
error = new Error("Login failed : #{hash?.error?.reason}")
error[k] = v for k, v of hash.error
@_authenticating.reject(error)
@_authenticating = null
clearInterval(@_popupInterval)
@_popupInterval = null
undefined
loginWithProvider : (opts)=>
isAuthenticating = @isAuthenticating()
return isAuthenticating if isAuthenticating
@_authenticating = {}
promise = new Promise (resolve, reject)=>
@_authenticating.resolve = resolve
@_authenticating.reject = reject
unless ~(_.indexOf(@authServices, opts.provider))
@_authenticating.reject
message: "No authentication service #{opts.provider} configured for the app"
reason: 'no_such_service'
return promise
@_authenticating.provider = opts.provider.toLowerCase()
authUrl = @generateAuthUrl(opts)
if opts.strategy == 'redirect'
# Don't do an early return to not break promise chain
window.location.href = authUrl
else
# Classic Popup Strategy
@popupAuthWindow(authUrl, opts)
promise
login : () =>
if @isAuthenticating()
# Return promise even if login is in progress.
msg = "Login in progress. Use `Hull.on('hull.user.login', callback)` to call `callback` when done."
logger.info msg
return Promise.reject {error: {reason:'in_progress', message: 'Login already in progress'}}
# Handle Legacy Format,
# Ensure New Format: Hash signature
# Preprocess Options
# Opts format is now : {login:"", password:"", params:{}} or {provider:"", params:{}}
{options, callback, errback} = parseParams(Array.prototype.slice.call(arguments))
if !(options?.provider? || options.login? || options.access_token?)
# UserName+Password
# Hull.login({login:'<EMAIL>', password:'<PASSWORD>', strategy:'redirect|popup', redirect:'...'})
unless options.login? and options.password?
msg = 'Seems like something is wrong in your Hull.login() call, We need a login and password fields to login. Read up here: http://www.hull.io/docs/references/hull_js/#user-signup-and-login'
logger.warn msg
return Promise.reject({error:{ reason:'missing_parameters', message:'Empty login or password' }})
if options.provider?
# Social Login
if options.access_token?
# Hull.login({provider:'facebook', access_token:'xxxx'})
provider = assign({}, options)
delete provider.provider
op = {}
op[options.provider] = provider
promise = @api.message('users', 'post', op)
else
# Hull.login({provider:'facebook', strategy:'redirect|popup', redirect:'...'})
promise = @loginWithProvider(options)
else
# Email Login
# Hull.login({login:'<EMAIL>', password:'<PASSWORD>'})
# Hull.login({access_token:'xxxx<PASSWORD>'})
promise = @api.message('users/login', 'post', _.pick(options, 'login', 'password', 'access_token'))
if options.strategy == 'redirect' || !@currentConfig.getRemote('cookiesEnabled')
postUrl = @currentConfig.get('orgUrl')+'/api/v1/users/login'
options.redirect_url ||= window.location.href
promise = promise.then -> postForm(postUrl, 'post', options)
@completeLoginPromiseChain(promise, callback, errback)
logout: (options={}, callback, errback) =>
@currentConfig.resetIdentify()
@api.channel.rpc.resetIdentify()
promise = @api.message('logout')
if options.strategy == 'redirect' || !@currentConfig.getRemote('cookiesEnabled')
redirect_url = options.redirect_url || document.location.href
# Add this param to make sure safari actually redirects to the logoutUrl
b = new Date().getTime()
logoutUrl = @currentConfig.get('orgUrl') + '/api/v1/logout?b=' + b + '&redirect_url=' + encodeURIComponent(redirect_url)
promise.then -> document.location = logoutUrl
@completeLoginPromiseChain(promise,callback,errback)
resetPassword : (email=<EMAIL>('email'), callback, errback) =>
promise = @api.message('/users/request_password_reset', 'post', {email})
@completeLoginPromiseChain(promise,callback,errback)
confirmEmail : (email=<EMAIL>('email'), callback, errback) =>
promise = @api.message('/users/request_confirmation_email', 'post', {email})
@completeLoginPromiseChain(promise,callback,errback)
signup : (attrs, callback, errback) =>
promise = @api.message('users', 'POST', attrs)
if !@currentConfig.getRemote('cookiesEnabled')
postUrl = @currentConfig.get('orgUrl')+'/api/v1/users/login'
promise = promise.then (user)->
params = {
redirect_url: window.location.href,
access_token: user.access_token
}
postForm(postUrl, 'post', params)
@completeLoginPromiseChain(promise, callback, errback)
###*
* link an Identity to a Hull User
* @param {options} An options Hash
* @param {callback} Success callback
* @param {errback} error callback
* @return {Promise} A promise
###
linkIdentity : ()=>
return getNoUserPromise() unless getUser()
{options, callback, errback} = parseParams(Array.prototype.slice.call(arguments))
options.params.mode = 'connect'
@login(options, callback, errback)
###*
* unlink an Identity from a Hull User
* @param {options} An options Hash
* @param {callback} Success callback
* @param {errback} error callback
* @return {Promise} A promise
*
###
unlinkIdentity : ()=>
return getNoUserPromise() unless getUser()
{options, callback, errback} = parseParams(Array.prototype.slice.call(arguments))
promise = @api.message("me/identities/#{options.provider}", 'delete')
@completeLoginPromiseChain(promise,callback,errback)
completeLoginPromiseChain: (promise, callback,errback)=>
if promise && promise.then
callback = callback || ->
errback = errback || ->
p = promise.then @api.refreshUser, @emitLoginFailure
p.then callback, errback
p
emitLoginFailure : (err)->
EventBus.emit("hull.user.fail", err)
err
throw err
module.exports = Auth
| true | assign = require '../polyfills/assign'
Promise = require '../utils/promises'
_ = require '../utils/lodash'
logger = require '../utils/logger'
EventBus = require '../utils/eventbus'
isMobile = require '../utils/is-mobile'
getNoUserPromise = ()->
Promise.reject({
reason: 'no_current_user',
message: 'User must be logged in to perform this action'
})
getUser = ()->
user = Hull.currentUser()
return (!!user && user.id?)
parseParams = (argsArray)->
opts = {}
while (next = argsArray.shift())
if _.isString next
if !login
login = next
else
password = next
else if _.isFunction next
if !callback
callback = next
else
errback = next
else if _.isObject(next) and !_.isEmpty(next)
if !login and !password
opts = next
else
opts.params = assign(next, opts.params||{})
if login
opts = if password then assign(opts, {login, password}) else assign(opts, {provider:login})
opts.params = opts.params || {}
callback = callback || ->
errback = errback || ->
opts.params.display ||= 'touch' if isMobile()
# Setup defaults for Popup login for Facebook on Desktop
# # Redirect login by default. if on Mobile.
# # Setup 'display' to be 'touch' for Facebook Login if on Mobile
if opts.provider == 'facebook'
opts.params.display ||= if opts.strategy == 'redirect' then 'page' else 'popup'
# TODO : OK to ignore `params` in this email login scenario ?
delete opts.params if opts.password?
{
options: opts
callback : callback
errback : errback
}
postForm = (path, method='post', params={}) ->
form = document.createElement("form")
form.setAttribute("method", method)
form.setAttribute("action", path)
for key of params
if params.hasOwnProperty key
hiddenField = document.createElement("input")
hiddenField.setAttribute("type", "hidden")
hiddenField.setAttribute("name", key)
hiddenField.setAttribute("value", params[key])
form.appendChild(hiddenField)
document.body.appendChild(form)
form.submit()
class Auth
constructor: (api, currentUser, currentConfig)->
@api = api
@currentUser = currentUser
@currentConfig = currentConfig
@_popupInterval = null
@_authenticating = null
@authServices = _.keys(@currentConfig.get('services.auth'))
isAuthenticating : -> @_authenticating?
# Generates the complete URL to be reached to validate login
generateAuthUrl : (opts={})->
@createAuthCallback()
params = opts.params || {}
params.app_id = @currentConfig.get('appId')
# The following is here for backward compatibility. Must be removed at first sight next time
params.callback_url = opts.redirect_url || params.callback_url || @currentConfig.get('callback_url') || @currentConfig.get('callbackUrl') || document.location.toString()
params.auth_referer = document.location.toString()
params.version = @currentConfig.get('version')
params._bid = @currentConfig.identifyBrowser().id
params._sid = @currentConfig.identifySession().id
querystring = _.map params,(v,k) ->
encodeURIComponent(k)+'='+encodeURIComponent(v)
.join('&')
"#{@currentConfig.get('orgUrl')}/auth/#{opts.provider}?#{querystring}"
createAuthCallback: =>
window.__hull_login_status__ = (hash) =>
window.__hull_login_status__ = null
@onAuthComplete(hash)
popupAuthWindow: (path, opts={})->
# Handle smaller Facebook popup windows
[width, height] = if opts.provider == 'facebook' and opts.params.display == 'popup' then [500, 400] else [1030, 550]
openerString = "location=0,status=0,width=#{width},height=#{height}"
w = window.open(path, "_auth",openerString)
# Support for cordova events
if window.device?.cordova
w?.addEventListener 'loadstart', (event)->
hash = try JSON.parse(Base64.decode(event.url.split('#')[1]))
if hash
window.__hull_login_status__(hash)
w.close()
# 30 seconds after creating popup, reject promise if still active.
setTimeout ()=>
@onAuthComplete({ success: false, error: { reason: 'timeout', message: 'Timeout for login (after 30 seconds), User never finished the auth' } })
, 90000
# Reject Promise if window has been closed
@_popupInterval = w? && setInterval =>
@onAuthComplete({ success: false, error: { reason: 'window_closed', message: 'User closed the window before finishing. He might have canceled' } }) if w?.closed
, 200
onAuthComplete : (hash)=>
return unless @_authenticating
if hash.success
@_authenticating.resolve({})
else
error = new Error("Login failed : #{hash?.error?.reason}")
error[k] = v for k, v of hash.error
@_authenticating.reject(error)
@_authenticating = null
clearInterval(@_popupInterval)
@_popupInterval = null
undefined
loginWithProvider : (opts)=>
isAuthenticating = @isAuthenticating()
return isAuthenticating if isAuthenticating
@_authenticating = {}
promise = new Promise (resolve, reject)=>
@_authenticating.resolve = resolve
@_authenticating.reject = reject
unless ~(_.indexOf(@authServices, opts.provider))
@_authenticating.reject
message: "No authentication service #{opts.provider} configured for the app"
reason: 'no_such_service'
return promise
@_authenticating.provider = opts.provider.toLowerCase()
authUrl = @generateAuthUrl(opts)
if opts.strategy == 'redirect'
# Don't do an early return to not break promise chain
window.location.href = authUrl
else
# Classic Popup Strategy
@popupAuthWindow(authUrl, opts)
promise
login : () =>
if @isAuthenticating()
# Return promise even if login is in progress.
msg = "Login in progress. Use `Hull.on('hull.user.login', callback)` to call `callback` when done."
logger.info msg
return Promise.reject {error: {reason:'in_progress', message: 'Login already in progress'}}
# Handle Legacy Format,
# Ensure New Format: Hash signature
# Preprocess Options
# Opts format is now : {login:"", password:"", params:{}} or {provider:"", params:{}}
{options, callback, errback} = parseParams(Array.prototype.slice.call(arguments))
if !(options?.provider? || options.login? || options.access_token?)
# UserName+Password
# Hull.login({login:'PI:EMAIL:<EMAIL>END_PI', password:'PI:PASSWORD:<PASSWORD>END_PI', strategy:'redirect|popup', redirect:'...'})
unless options.login? and options.password?
msg = 'Seems like something is wrong in your Hull.login() call, We need a login and password fields to login. Read up here: http://www.hull.io/docs/references/hull_js/#user-signup-and-login'
logger.warn msg
return Promise.reject({error:{ reason:'missing_parameters', message:'Empty login or password' }})
if options.provider?
# Social Login
if options.access_token?
# Hull.login({provider:'facebook', access_token:'xxxx'})
provider = assign({}, options)
delete provider.provider
op = {}
op[options.provider] = provider
promise = @api.message('users', 'post', op)
else
# Hull.login({provider:'facebook', strategy:'redirect|popup', redirect:'...'})
promise = @loginWithProvider(options)
else
# Email Login
# Hull.login({login:'PI:EMAIL:<EMAIL>END_PI', password:'PI:PASSWORD:<PASSWORD>END_PI'})
# Hull.login({access_token:'xxxxPI:PASSWORD:<PASSWORD>END_PI'})
promise = @api.message('users/login', 'post', _.pick(options, 'login', 'password', 'access_token'))
if options.strategy == 'redirect' || !@currentConfig.getRemote('cookiesEnabled')
postUrl = @currentConfig.get('orgUrl')+'/api/v1/users/login'
options.redirect_url ||= window.location.href
promise = promise.then -> postForm(postUrl, 'post', options)
@completeLoginPromiseChain(promise, callback, errback)
logout: (options={}, callback, errback) =>
@currentConfig.resetIdentify()
@api.channel.rpc.resetIdentify()
promise = @api.message('logout')
if options.strategy == 'redirect' || !@currentConfig.getRemote('cookiesEnabled')
redirect_url = options.redirect_url || document.location.href
# Add this param to make sure safari actually redirects to the logoutUrl
b = new Date().getTime()
logoutUrl = @currentConfig.get('orgUrl') + '/api/v1/logout?b=' + b + '&redirect_url=' + encodeURIComponent(redirect_url)
promise.then -> document.location = logoutUrl
@completeLoginPromiseChain(promise,callback,errback)
resetPassword : (email=PI:EMAIL:<EMAIL>END_PI('email'), callback, errback) =>
promise = @api.message('/users/request_password_reset', 'post', {email})
@completeLoginPromiseChain(promise,callback,errback)
confirmEmail : (email=PI:EMAIL:<EMAIL>END_PI('email'), callback, errback) =>
promise = @api.message('/users/request_confirmation_email', 'post', {email})
@completeLoginPromiseChain(promise,callback,errback)
signup : (attrs, callback, errback) =>
promise = @api.message('users', 'POST', attrs)
if !@currentConfig.getRemote('cookiesEnabled')
postUrl = @currentConfig.get('orgUrl')+'/api/v1/users/login'
promise = promise.then (user)->
params = {
redirect_url: window.location.href,
access_token: user.access_token
}
postForm(postUrl, 'post', params)
@completeLoginPromiseChain(promise, callback, errback)
###*
* link an Identity to a Hull User
* @param {options} An options Hash
* @param {callback} Success callback
* @param {errback} error callback
* @return {Promise} A promise
###
linkIdentity : ()=>
return getNoUserPromise() unless getUser()
{options, callback, errback} = parseParams(Array.prototype.slice.call(arguments))
options.params.mode = 'connect'
@login(options, callback, errback)
###*
* unlink an Identity from a Hull User
* @param {options} An options Hash
* @param {callback} Success callback
* @param {errback} error callback
* @return {Promise} A promise
*
###
unlinkIdentity : ()=>
return getNoUserPromise() unless getUser()
{options, callback, errback} = parseParams(Array.prototype.slice.call(arguments))
promise = @api.message("me/identities/#{options.provider}", 'delete')
@completeLoginPromiseChain(promise,callback,errback)
completeLoginPromiseChain: (promise, callback,errback)=>
if promise && promise.then
callback = callback || ->
errback = errback || ->
p = promise.then @api.refreshUser, @emitLoginFailure
p.then callback, errback
p
emitLoginFailure : (err)->
EventBus.emit("hull.user.fail", err)
err
throw err
module.exports = Auth
|
[
{
"context": "rt by key\", ->\n items = [\n { 'name': 'barney', 'age': 36 }\n { 'name': 'fred', 'age'",
"end": 9703,
"score": 0.9996756911277771,
"start": 9697,
"tag": "NAME",
"value": "barney"
},
{
"context": "'name': 'barney', 'age': 36 }\n { 'name': ... | tests/collection_test.coffee | bahiamartins/stacktic | 1 | Collection = require("../lib/Collection")
collection = (items) ->
items ||= [{a: 1, b: 1},{a: 2, b: 2},{a: 3, b: 3}]
new Collection(items)
describe "Collection", ->
describe "#toArray", ->
it "should return an array with the right size", ->
collection().toArray().should.be.instanceof(Array).and.have.lengthOf(3)
it "should return an array of clones if clone is passed", ->
item = {a: 1}
ary1 = collection([item]).toArray()
ary2 = collection([item]).toArray(clone: true)
item.a = 2
ary1.should.eql([{a: 2}])
ary2.should.eql([{a: 1}])
describe "#first", ->
it "should return first item", ->
collection().first().should.eql({ a: 1, b: 1 })
describe "#last", ->
it "should return last item", ->
collection().last().should.eql({ a: 3, b: 3 })
describe "#paginate", ->
it "Should paginate right", ->
collection([1..10]).paginate(3).toArray().should.eql [
{ page: 1, items: [1..3] },
{ page: 2, items: [4..6] },
{ page: 3, items: [7..9] },
{ page: 4, items: [10] }
]
it "Should paginate empty to empty collection", ->
collection([]).paginate(3).size().should.equal(0)
describe "#offset", ->
it "should return offseted collection", ->
collection().offset(1).toArray().should.eql([{ a: 2, b: 2 }, { a: 3, b: 3 }])
it "should return full collection if false is passed", ->
collection().offset(false).toArray().should.eql([{a: 1, b: 1},{a: 2, b: 2},{a: 3, b: 3}])
describe "#limit", ->
it "should return limited collection", ->
collection().limit(1).toArray().should.eql([{ a: 1, b: 1 }])
it "should return full collection if false is passed", ->
collection().limit(false).toArray().should.eql([{a: 1, b: 1},{a: 2, b: 2},{a: 3, b: 3}])
describe "#merge", ->
it "should merge properties from object", ->
collection().merge({c: 0}).toArray().should.eql([{a: 1, b: 1, c: 0},{a: 2, b: 2, c: 0},{a: 3, b: 3, c: 0}])
it "should merge properties from collection", ->
collection().merge(collection([{c: 0}])).toArray().should.eql([{a: 1, b: 1, c: 0},{a: 2, b: 2, c: 0},{a: 3, b: 3, c: 0}])
it "should merge properties from array", ->
collection().merge([{c: 0}, {d: 1}]).toArray().should.eql([{a: 1, b: 1, c: 0, d: 1},{a: 2, b: 2, c: 0, d: 1},{a: 3, b: 3, c: 0, d: 1}])
it "should not complain if nothing is passed", ->
collection().merge().toArray().should.eql([{a: 1, b: 1},{a: 2, b: 2},{a: 3, b: 3}])
describe "#sort", ->
it "should sort elems and return the same collection", ->
orig = collection([1,3,2])
res = orig.sort()
orig.toArray().should.eql([1,2,3])
describe "#concat", ->
it "should concatenate collections and return a new collection", ->
orig = collection([1..3])
res = orig.concat(collection([4..6]))
res.toArray().should.eql([1..6])
orig.toArray().should.eql([1..3])
describe "#append", ->
it "should append a collection to another modifing the original", ->
orig = collection([1..3])
res = orig.append(collection([4..6]))
res.toArray().should.eql([1..6])
orig.toArray().should.eql([1..6])
describe "#prepend", ->
it "should prepend a collection to another modifing the original", ->
orig = collection([4..6])
res = orig.prepend(collection([1..3]))
res.toArray().should.eql([1..6])
orig.toArray().should.eql([1..6])
describe "#push", ->
it "Should push item", ->
collection([1..3]).push(4).toArray().should.eql([1..4])
describe "#unshift", ->
it "Should unshift item", ->
collection([2..4]).unshift(1).toArray().should.eql([1..4])
describe "#pop", ->
it "Should pop and return item", ->
coll = collection([1..3])
coll.pop().should.equal(3)
coll.toArray().should.eql([1..2])
describe "#shift", ->
it "Should shift and return item", ->
coll = collection([1..3])
coll.shift().should.equal(1)
coll.toArray().should.eql([2..3])
#
# Lodash delegated methods
#
describe "#at", ->
it "should return correspondig item at provided index", ->
(collection().at(-1) is undefined).should.be.true
collection().at(0).should.eql({ a: 1, b: 1 })
collection().at(1).should.eql({ a: 2, b: 2 })
collection().at(2).should.eql({ a: 3, b: 3 })
(collection().at(3) is undefined).should.be.true
describe "#contains", ->
it "Should return true if collection contains an item", ->
collection([1..3]).contains(3).should.be.true
it "Should return false if collection does not contain an item", ->
collection([1..3]).contains(4).should.be.false
describe "#countBy", ->
it "Should count values by key", ->
collection([{a:"A"}, {a: "A"}, {a: "B"}]).countBy('a').should.eql({"A": 2, "B": 1})
describe "#every", ->
it "Should return true if all values matches", ->
collection([{a: 1, b: 1}, {a: 1, b: 2}]).every({a: 1}).should.be.true
it "Should return false if some values not matches", ->
collection([{a: 1, b: 1}, {a: 1, b: 2}]).every({b: 1}).should.be.false
describe "#filter", ->
it "Should filter by keys", ->
collection([{a:"A"}, {a: "A"}, {a: "B"}]).filter({a: "A"}).toArray().should.eql([{a:"A"}, {a: "A"}])
it "Should filter by fn", ->
fn = (item) ->
item.a == "A"
collection([{a:"A"}, {a: "A"}, {a: "B"}]).filter(fn).toArray().should.eql([{a:"A"}, {a: "A"}])
describe "#find", ->
it "Should find by keys", ->
collection([{a:"A"}, {a: "A"}, {a: "B", b: 1}, {a: "B", b: 2}]).find({a: "B"}).should.eql({a:"B", b: 1})
it "Should find by fn", ->
fn = (item) ->
item.a == "B"
collection([{a:"A"}, {a: "A"}, {a: "B", b: 1}, {a: "B", b: 2}]).find(fn).should.eql({a:"B", b: 1})
describe "#findLast", ->
it "Should findLast by keys", ->
collection([{a:"A"}, {a: "A"}, {a: "B", b: 1}, {a: "B", b: 2}]).findLast({a: "B"}).should.eql({a:"B", b: 2})
it "Should findLast by fn", ->
fn = (item) ->
item.a == "B"
collection([{a:"A"}, {a: "A"}, {a: "B", b: 1}, {a: "B", b: 2}]).findLast(fn).should.eql({a:"B", b: 2})
describe "#forEach", ->
it "Should be chainable", ->
collection().forEach(->).should.be.instanceOf(Collection)
it "Should invoke callback for each item", ->
called = 0
coll = collection()
items = coll.toArray()
coll.forEach (item) ->
item.should.eql(items[called])
called++
called.should.equal(3)
it "It should break returning false", ->
called = 0
coll = collection()
items = coll.toArray()
coll.forEach (item) ->
item.should.eql(items[called])
called++
false
called.should.equal(1)
describe "#forEachRight", ->
it "Should be chainable", ->
collection().forEachRight(->).should.be.instanceOf(Collection)
it "Should invoke callback for each item", ->
called = 3
coll = collection()
items = coll.toArray()
coll.forEachRight (item) ->
called--
item.should.eql(items[called])
called.should.equal(0)
describe "#groupBy", ->
it "Should group by keys", ->
items = [{a:"A"}, {a: "A"}, {a: "B"}]
expected = {"A": {items: [{a: "A"}, {a: "A"}]}, "B": {items: [{a: "B"}]}}
collection(items).groupBy('a').should.eql(expected)
describe "#indexBy", ->
it "Should index keys", ->
items = [{a:"A"}, {a: "A"}, {a: "B"}]
expected = {"A": {items: [{a: "A"}]}, "B": {items: [{a: "B"}]}}
collection(items).indexBy('a').should.eql(expected)
describe "#invoke", ->
it "Should invoke methods on items", ->
items = [[5, 1, 7], [3, 2, 1]]
expected = [[1, 5, 7], [1, 2, 3]]
collection(items).invoke("sort").should.eql(expected)
describe "#map", ->
it "Should map items", ->
items = [1..3]
expected = [3, 6, 9]
fn = (n) -> n * 3
collection(items).map(fn).toArray().should.eql(expected)
describe "#max", ->
it "Should return the max item by key", ->
collection().max('a').should.eql({a: 3, b: 3})
describe "#min", ->
it "Should return the min item by key", ->
collection().min('a').should.eql({a: 1, b: 1})
describe "#pluck", ->
it "Should pluck a collection", ->
collection().pluck('a').should.eql([1,2,3])
describe "#reject", ->
it "should return filtered collection", ->
collection().reject(a: 2).toArray().should.eql([{a: 1, b: 1}, {a: 3, b: 3}])
describe "#sample", ->
it "Should return a new collection with an item from the original one", ->
coll = collection([1..10])
coll.contains(coll.sample().first())
describe "#shuffle", ->
it "Shoudl return a new collection (pretty much impossible to test further)", ->
collection().shuffle().should.be.instanceOf(Collection)
describe "#size", ->
it "should return the right size", ->
collection().size().should.equal(3)
describe "#slice", ->
it "should return right slices", ->
collection().slice(1,2).toArray().should.eql([{ a: 2, b: 2 }])
collection().slice(1).toArray().should.eql([{ a: 2, b: 2 }, { a: 3, b: 3 }])
describe "#some", ->
it "Should return true if any values matches", ->
collection([{a: 1, b: 1}, {a: 1, b: 2}]).some({b: 1}).should.be.true
it "Should return false if no values matches", ->
collection([{a: 1, b: 1}, {a: 1, b: 2}]).some({a: 2}).should.be.false
describe "#sortBy", ->
it "Should sort by key", ->
items = [
{ 'name': 'barney', 'age': 36 }
{ 'name': 'fred', 'age': 40 }
{ 'name': 'barney', 'age': 26 }
{ 'name': 'fred', 'age': 30 }
]
expected = [
{ 'name': 'barney', 'age': 26 }
{ 'name': 'fred', 'age': 30 }
{ 'name': 'barney', 'age': 36 }
{ 'name': 'fred', 'age': 40 }
]
collection(items).sortBy('age').toArray().should.eql(expected)
it "Should sort by in descending order", ->
items = [
{ 'name': 'barney', 'age': 36 }
{ 'name': 'fred', 'age': 40 }
{ 'name': 'barney', 'age': 26 }
{ 'name': 'fred', 'age': 30 }
]
expected = [
{ 'name': 'fred', 'age': 40 }
{ 'name': 'barney', 'age': 36 }
{ 'name': 'fred', 'age': 30 }
{ 'name': 'barney', 'age': 26 }
]
collection(items).sortBy('age', 'desc').toArray().should.eql(expected)
describe "#where", ->
it "should return filtered collection", ->
collection().where(a: 2).toArray().should.eql([{ a: 2, b: 2 }])
describe "#reduce", ->
it "should reduce left", ->
fn = (acc, item) -> acc + item.a
collection().reduce(fn, 0).should.eql(6)
describe "#reduceRight", ->
it "should reduce right", ->
fn = (acc, item) -> acc + item.a
collection().reduceRight(fn, 0).should.eql(6)
#
# Aliases
#
describe "#include", ->
it "Should be an alias", ->
Collection::include.should.be.a.Function
(Collection::include is Collection::contains).should.be.true
describe "#all", ->
it "Should be an alias", ->
Collection::all.should.be.a.Function
(Collection::all is Collection::every).should.be.true
describe "#select", ->
it "Should be an alias", ->
Collection::select.should.be.a.Function
(Collection::select is Collection::filter).should.be.true
describe "#detect", ->
it "Should be an alias", ->
Collection::detect.should.be.a.Function
(Collection::detect is Collection::find).should.be.true
describe "#findWhere", ->
it "Should be an alias", ->
Collection::findWhere.should.be.a.Function
(Collection::findWhere is Collection::find).should.be.true
describe "#each", ->
it "Should be an alias", ->
Collection::each.should.be.a.Function
(Collection::each is Collection::forEach).should.be.true
describe "#eachRight", ->
it "Should be an alias", ->
Collection::eachRight.should.be.a.Function
(Collection::eachRight is Collection::forEachRight).should.be.true
describe "#collect", ->
it "Should be an alias", ->
Collection::collect.should.be.a.Function
(Collection::collect is Collection::map).should.be.true
describe "#foldl", ->
it "Should be an alias", ->
Collection::foldl.should.be.a.Function
(Collection::foldl is Collection::reduce ).should.be.true
describe "#inject", ->
it "Should be an alias", ->
Collection::inject.should.be.a.Function
(Collection::inject is Collection::reduce).should.be.true
describe "#foldr", ->
it "Should be an alias", ->
Collection::foldr.should.be.a.Function
(Collection::foldr is Collection::reduceRight).should.be.true
describe "#any", ->
it "Should be an alias", ->
Collection::any.should.be.a.Function
(Collection::any is Collection::some).should.be.true
| 204818 | Collection = require("../lib/Collection")
collection = (items) ->
items ||= [{a: 1, b: 1},{a: 2, b: 2},{a: 3, b: 3}]
new Collection(items)
describe "Collection", ->
describe "#toArray", ->
it "should return an array with the right size", ->
collection().toArray().should.be.instanceof(Array).and.have.lengthOf(3)
it "should return an array of clones if clone is passed", ->
item = {a: 1}
ary1 = collection([item]).toArray()
ary2 = collection([item]).toArray(clone: true)
item.a = 2
ary1.should.eql([{a: 2}])
ary2.should.eql([{a: 1}])
describe "#first", ->
it "should return first item", ->
collection().first().should.eql({ a: 1, b: 1 })
describe "#last", ->
it "should return last item", ->
collection().last().should.eql({ a: 3, b: 3 })
describe "#paginate", ->
it "Should paginate right", ->
collection([1..10]).paginate(3).toArray().should.eql [
{ page: 1, items: [1..3] },
{ page: 2, items: [4..6] },
{ page: 3, items: [7..9] },
{ page: 4, items: [10] }
]
it "Should paginate empty to empty collection", ->
collection([]).paginate(3).size().should.equal(0)
describe "#offset", ->
it "should return offseted collection", ->
collection().offset(1).toArray().should.eql([{ a: 2, b: 2 }, { a: 3, b: 3 }])
it "should return full collection if false is passed", ->
collection().offset(false).toArray().should.eql([{a: 1, b: 1},{a: 2, b: 2},{a: 3, b: 3}])
describe "#limit", ->
it "should return limited collection", ->
collection().limit(1).toArray().should.eql([{ a: 1, b: 1 }])
it "should return full collection if false is passed", ->
collection().limit(false).toArray().should.eql([{a: 1, b: 1},{a: 2, b: 2},{a: 3, b: 3}])
describe "#merge", ->
it "should merge properties from object", ->
collection().merge({c: 0}).toArray().should.eql([{a: 1, b: 1, c: 0},{a: 2, b: 2, c: 0},{a: 3, b: 3, c: 0}])
it "should merge properties from collection", ->
collection().merge(collection([{c: 0}])).toArray().should.eql([{a: 1, b: 1, c: 0},{a: 2, b: 2, c: 0},{a: 3, b: 3, c: 0}])
it "should merge properties from array", ->
collection().merge([{c: 0}, {d: 1}]).toArray().should.eql([{a: 1, b: 1, c: 0, d: 1},{a: 2, b: 2, c: 0, d: 1},{a: 3, b: 3, c: 0, d: 1}])
it "should not complain if nothing is passed", ->
collection().merge().toArray().should.eql([{a: 1, b: 1},{a: 2, b: 2},{a: 3, b: 3}])
describe "#sort", ->
it "should sort elems and return the same collection", ->
orig = collection([1,3,2])
res = orig.sort()
orig.toArray().should.eql([1,2,3])
describe "#concat", ->
it "should concatenate collections and return a new collection", ->
orig = collection([1..3])
res = orig.concat(collection([4..6]))
res.toArray().should.eql([1..6])
orig.toArray().should.eql([1..3])
describe "#append", ->
it "should append a collection to another modifing the original", ->
orig = collection([1..3])
res = orig.append(collection([4..6]))
res.toArray().should.eql([1..6])
orig.toArray().should.eql([1..6])
describe "#prepend", ->
it "should prepend a collection to another modifing the original", ->
orig = collection([4..6])
res = orig.prepend(collection([1..3]))
res.toArray().should.eql([1..6])
orig.toArray().should.eql([1..6])
describe "#push", ->
it "Should push item", ->
collection([1..3]).push(4).toArray().should.eql([1..4])
describe "#unshift", ->
it "Should unshift item", ->
collection([2..4]).unshift(1).toArray().should.eql([1..4])
describe "#pop", ->
it "Should pop and return item", ->
coll = collection([1..3])
coll.pop().should.equal(3)
coll.toArray().should.eql([1..2])
describe "#shift", ->
it "Should shift and return item", ->
coll = collection([1..3])
coll.shift().should.equal(1)
coll.toArray().should.eql([2..3])
#
# Lodash delegated methods
#
describe "#at", ->
it "should return correspondig item at provided index", ->
(collection().at(-1) is undefined).should.be.true
collection().at(0).should.eql({ a: 1, b: 1 })
collection().at(1).should.eql({ a: 2, b: 2 })
collection().at(2).should.eql({ a: 3, b: 3 })
(collection().at(3) is undefined).should.be.true
describe "#contains", ->
it "Should return true if collection contains an item", ->
collection([1..3]).contains(3).should.be.true
it "Should return false if collection does not contain an item", ->
collection([1..3]).contains(4).should.be.false
describe "#countBy", ->
it "Should count values by key", ->
collection([{a:"A"}, {a: "A"}, {a: "B"}]).countBy('a').should.eql({"A": 2, "B": 1})
describe "#every", ->
it "Should return true if all values matches", ->
collection([{a: 1, b: 1}, {a: 1, b: 2}]).every({a: 1}).should.be.true
it "Should return false if some values not matches", ->
collection([{a: 1, b: 1}, {a: 1, b: 2}]).every({b: 1}).should.be.false
describe "#filter", ->
it "Should filter by keys", ->
collection([{a:"A"}, {a: "A"}, {a: "B"}]).filter({a: "A"}).toArray().should.eql([{a:"A"}, {a: "A"}])
it "Should filter by fn", ->
fn = (item) ->
item.a == "A"
collection([{a:"A"}, {a: "A"}, {a: "B"}]).filter(fn).toArray().should.eql([{a:"A"}, {a: "A"}])
describe "#find", ->
it "Should find by keys", ->
collection([{a:"A"}, {a: "A"}, {a: "B", b: 1}, {a: "B", b: 2}]).find({a: "B"}).should.eql({a:"B", b: 1})
it "Should find by fn", ->
fn = (item) ->
item.a == "B"
collection([{a:"A"}, {a: "A"}, {a: "B", b: 1}, {a: "B", b: 2}]).find(fn).should.eql({a:"B", b: 1})
describe "#findLast", ->
it "Should findLast by keys", ->
collection([{a:"A"}, {a: "A"}, {a: "B", b: 1}, {a: "B", b: 2}]).findLast({a: "B"}).should.eql({a:"B", b: 2})
it "Should findLast by fn", ->
fn = (item) ->
item.a == "B"
collection([{a:"A"}, {a: "A"}, {a: "B", b: 1}, {a: "B", b: 2}]).findLast(fn).should.eql({a:"B", b: 2})
describe "#forEach", ->
it "Should be chainable", ->
collection().forEach(->).should.be.instanceOf(Collection)
it "Should invoke callback for each item", ->
called = 0
coll = collection()
items = coll.toArray()
coll.forEach (item) ->
item.should.eql(items[called])
called++
called.should.equal(3)
it "It should break returning false", ->
called = 0
coll = collection()
items = coll.toArray()
coll.forEach (item) ->
item.should.eql(items[called])
called++
false
called.should.equal(1)
describe "#forEachRight", ->
it "Should be chainable", ->
collection().forEachRight(->).should.be.instanceOf(Collection)
it "Should invoke callback for each item", ->
called = 3
coll = collection()
items = coll.toArray()
coll.forEachRight (item) ->
called--
item.should.eql(items[called])
called.should.equal(0)
describe "#groupBy", ->
it "Should group by keys", ->
items = [{a:"A"}, {a: "A"}, {a: "B"}]
expected = {"A": {items: [{a: "A"}, {a: "A"}]}, "B": {items: [{a: "B"}]}}
collection(items).groupBy('a').should.eql(expected)
describe "#indexBy", ->
it "Should index keys", ->
items = [{a:"A"}, {a: "A"}, {a: "B"}]
expected = {"A": {items: [{a: "A"}]}, "B": {items: [{a: "B"}]}}
collection(items).indexBy('a').should.eql(expected)
describe "#invoke", ->
it "Should invoke methods on items", ->
items = [[5, 1, 7], [3, 2, 1]]
expected = [[1, 5, 7], [1, 2, 3]]
collection(items).invoke("sort").should.eql(expected)
describe "#map", ->
it "Should map items", ->
items = [1..3]
expected = [3, 6, 9]
fn = (n) -> n * 3
collection(items).map(fn).toArray().should.eql(expected)
describe "#max", ->
it "Should return the max item by key", ->
collection().max('a').should.eql({a: 3, b: 3})
describe "#min", ->
it "Should return the min item by key", ->
collection().min('a').should.eql({a: 1, b: 1})
describe "#pluck", ->
it "Should pluck a collection", ->
collection().pluck('a').should.eql([1,2,3])
describe "#reject", ->
it "should return filtered collection", ->
collection().reject(a: 2).toArray().should.eql([{a: 1, b: 1}, {a: 3, b: 3}])
describe "#sample", ->
it "Should return a new collection with an item from the original one", ->
coll = collection([1..10])
coll.contains(coll.sample().first())
describe "#shuffle", ->
it "Shoudl return a new collection (pretty much impossible to test further)", ->
collection().shuffle().should.be.instanceOf(Collection)
describe "#size", ->
it "should return the right size", ->
collection().size().should.equal(3)
describe "#slice", ->
it "should return right slices", ->
collection().slice(1,2).toArray().should.eql([{ a: 2, b: 2 }])
collection().slice(1).toArray().should.eql([{ a: 2, b: 2 }, { a: 3, b: 3 }])
describe "#some", ->
it "Should return true if any values matches", ->
collection([{a: 1, b: 1}, {a: 1, b: 2}]).some({b: 1}).should.be.true
it "Should return false if no values matches", ->
collection([{a: 1, b: 1}, {a: 1, b: 2}]).some({a: 2}).should.be.false
describe "#sortBy", ->
it "Should sort by key", ->
items = [
{ 'name': '<NAME>', 'age': 36 }
{ 'name': '<NAME>', 'age': 40 }
{ 'name': '<NAME>', 'age': 26 }
{ 'name': '<NAME>', 'age': 30 }
]
expected = [
{ 'name': '<NAME>', 'age': 26 }
{ 'name': '<NAME>', 'age': 30 }
{ 'name': '<NAME>', 'age': 36 }
{ 'name': '<NAME>', 'age': 40 }
]
collection(items).sortBy('age').toArray().should.eql(expected)
it "Should sort by in descending order", ->
items = [
{ 'name': '<NAME>', 'age': 36 }
{ 'name': '<NAME>', 'age': 40 }
{ 'name': '<NAME>', 'age': 26 }
{ 'name': '<NAME>', 'age': 30 }
]
expected = [
{ 'name': '<NAME>', 'age': 40 }
{ 'name': '<NAME>', 'age': 36 }
{ 'name': '<NAME>', 'age': 30 }
{ 'name': '<NAME>', 'age': 26 }
]
collection(items).sortBy('age', 'desc').toArray().should.eql(expected)
describe "#where", ->
it "should return filtered collection", ->
collection().where(a: 2).toArray().should.eql([{ a: 2, b: 2 }])
describe "#reduce", ->
it "should reduce left", ->
fn = (acc, item) -> acc + item.a
collection().reduce(fn, 0).should.eql(6)
describe "#reduceRight", ->
it "should reduce right", ->
fn = (acc, item) -> acc + item.a
collection().reduceRight(fn, 0).should.eql(6)
#
# Aliases
#
describe "#include", ->
it "Should be an alias", ->
Collection::include.should.be.a.Function
(Collection::include is Collection::contains).should.be.true
describe "#all", ->
it "Should be an alias", ->
Collection::all.should.be.a.Function
(Collection::all is Collection::every).should.be.true
describe "#select", ->
it "Should be an alias", ->
Collection::select.should.be.a.Function
(Collection::select is Collection::filter).should.be.true
describe "#detect", ->
it "Should be an alias", ->
Collection::detect.should.be.a.Function
(Collection::detect is Collection::find).should.be.true
describe "#findWhere", ->
it "Should be an alias", ->
Collection::findWhere.should.be.a.Function
(Collection::findWhere is Collection::find).should.be.true
describe "#each", ->
it "Should be an alias", ->
Collection::each.should.be.a.Function
(Collection::each is Collection::forEach).should.be.true
describe "#eachRight", ->
it "Should be an alias", ->
Collection::eachRight.should.be.a.Function
(Collection::eachRight is Collection::forEachRight).should.be.true
describe "#collect", ->
it "Should be an alias", ->
Collection::collect.should.be.a.Function
(Collection::collect is Collection::map).should.be.true
describe "#foldl", ->
it "Should be an alias", ->
Collection::foldl.should.be.a.Function
(Collection::foldl is Collection::reduce ).should.be.true
describe "#inject", ->
it "Should be an alias", ->
Collection::inject.should.be.a.Function
(Collection::inject is Collection::reduce).should.be.true
describe "#foldr", ->
it "Should be an alias", ->
Collection::foldr.should.be.a.Function
(Collection::foldr is Collection::reduceRight).should.be.true
describe "#any", ->
it "Should be an alias", ->
Collection::any.should.be.a.Function
(Collection::any is Collection::some).should.be.true
| true | Collection = require("../lib/Collection")
collection = (items) ->
items ||= [{a: 1, b: 1},{a: 2, b: 2},{a: 3, b: 3}]
new Collection(items)
describe "Collection", ->
describe "#toArray", ->
it "should return an array with the right size", ->
collection().toArray().should.be.instanceof(Array).and.have.lengthOf(3)
it "should return an array of clones if clone is passed", ->
item = {a: 1}
ary1 = collection([item]).toArray()
ary2 = collection([item]).toArray(clone: true)
item.a = 2
ary1.should.eql([{a: 2}])
ary2.should.eql([{a: 1}])
describe "#first", ->
it "should return first item", ->
collection().first().should.eql({ a: 1, b: 1 })
describe "#last", ->
it "should return last item", ->
collection().last().should.eql({ a: 3, b: 3 })
describe "#paginate", ->
it "Should paginate right", ->
collection([1..10]).paginate(3).toArray().should.eql [
{ page: 1, items: [1..3] },
{ page: 2, items: [4..6] },
{ page: 3, items: [7..9] },
{ page: 4, items: [10] }
]
it "Should paginate empty to empty collection", ->
collection([]).paginate(3).size().should.equal(0)
describe "#offset", ->
it "should return offseted collection", ->
collection().offset(1).toArray().should.eql([{ a: 2, b: 2 }, { a: 3, b: 3 }])
it "should return full collection if false is passed", ->
collection().offset(false).toArray().should.eql([{a: 1, b: 1},{a: 2, b: 2},{a: 3, b: 3}])
describe "#limit", ->
it "should return limited collection", ->
collection().limit(1).toArray().should.eql([{ a: 1, b: 1 }])
it "should return full collection if false is passed", ->
collection().limit(false).toArray().should.eql([{a: 1, b: 1},{a: 2, b: 2},{a: 3, b: 3}])
describe "#merge", ->
it "should merge properties from object", ->
collection().merge({c: 0}).toArray().should.eql([{a: 1, b: 1, c: 0},{a: 2, b: 2, c: 0},{a: 3, b: 3, c: 0}])
it "should merge properties from collection", ->
collection().merge(collection([{c: 0}])).toArray().should.eql([{a: 1, b: 1, c: 0},{a: 2, b: 2, c: 0},{a: 3, b: 3, c: 0}])
it "should merge properties from array", ->
collection().merge([{c: 0}, {d: 1}]).toArray().should.eql([{a: 1, b: 1, c: 0, d: 1},{a: 2, b: 2, c: 0, d: 1},{a: 3, b: 3, c: 0, d: 1}])
it "should not complain if nothing is passed", ->
collection().merge().toArray().should.eql([{a: 1, b: 1},{a: 2, b: 2},{a: 3, b: 3}])
describe "#sort", ->
it "should sort elems and return the same collection", ->
orig = collection([1,3,2])
res = orig.sort()
orig.toArray().should.eql([1,2,3])
describe "#concat", ->
it "should concatenate collections and return a new collection", ->
orig = collection([1..3])
res = orig.concat(collection([4..6]))
res.toArray().should.eql([1..6])
orig.toArray().should.eql([1..3])
describe "#append", ->
it "should append a collection to another modifing the original", ->
orig = collection([1..3])
res = orig.append(collection([4..6]))
res.toArray().should.eql([1..6])
orig.toArray().should.eql([1..6])
describe "#prepend", ->
it "should prepend a collection to another modifing the original", ->
orig = collection([4..6])
res = orig.prepend(collection([1..3]))
res.toArray().should.eql([1..6])
orig.toArray().should.eql([1..6])
describe "#push", ->
it "Should push item", ->
collection([1..3]).push(4).toArray().should.eql([1..4])
describe "#unshift", ->
it "Should unshift item", ->
collection([2..4]).unshift(1).toArray().should.eql([1..4])
describe "#pop", ->
it "Should pop and return item", ->
coll = collection([1..3])
coll.pop().should.equal(3)
coll.toArray().should.eql([1..2])
describe "#shift", ->
it "Should shift and return item", ->
coll = collection([1..3])
coll.shift().should.equal(1)
coll.toArray().should.eql([2..3])
#
# Lodash delegated methods
#
describe "#at", ->
it "should return correspondig item at provided index", ->
(collection().at(-1) is undefined).should.be.true
collection().at(0).should.eql({ a: 1, b: 1 })
collection().at(1).should.eql({ a: 2, b: 2 })
collection().at(2).should.eql({ a: 3, b: 3 })
(collection().at(3) is undefined).should.be.true
describe "#contains", ->
it "Should return true if collection contains an item", ->
collection([1..3]).contains(3).should.be.true
it "Should return false if collection does not contain an item", ->
collection([1..3]).contains(4).should.be.false
describe "#countBy", ->
it "Should count values by key", ->
collection([{a:"A"}, {a: "A"}, {a: "B"}]).countBy('a').should.eql({"A": 2, "B": 1})
describe "#every", ->
it "Should return true if all values matches", ->
collection([{a: 1, b: 1}, {a: 1, b: 2}]).every({a: 1}).should.be.true
it "Should return false if some values not matches", ->
collection([{a: 1, b: 1}, {a: 1, b: 2}]).every({b: 1}).should.be.false
describe "#filter", ->
it "Should filter by keys", ->
collection([{a:"A"}, {a: "A"}, {a: "B"}]).filter({a: "A"}).toArray().should.eql([{a:"A"}, {a: "A"}])
it "Should filter by fn", ->
fn = (item) ->
item.a == "A"
collection([{a:"A"}, {a: "A"}, {a: "B"}]).filter(fn).toArray().should.eql([{a:"A"}, {a: "A"}])
describe "#find", ->
it "Should find by keys", ->
collection([{a:"A"}, {a: "A"}, {a: "B", b: 1}, {a: "B", b: 2}]).find({a: "B"}).should.eql({a:"B", b: 1})
it "Should find by fn", ->
fn = (item) ->
item.a == "B"
collection([{a:"A"}, {a: "A"}, {a: "B", b: 1}, {a: "B", b: 2}]).find(fn).should.eql({a:"B", b: 1})
describe "#findLast", ->
it "Should findLast by keys", ->
collection([{a:"A"}, {a: "A"}, {a: "B", b: 1}, {a: "B", b: 2}]).findLast({a: "B"}).should.eql({a:"B", b: 2})
it "Should findLast by fn", ->
fn = (item) ->
item.a == "B"
collection([{a:"A"}, {a: "A"}, {a: "B", b: 1}, {a: "B", b: 2}]).findLast(fn).should.eql({a:"B", b: 2})
describe "#forEach", ->
it "Should be chainable", ->
collection().forEach(->).should.be.instanceOf(Collection)
it "Should invoke callback for each item", ->
called = 0
coll = collection()
items = coll.toArray()
coll.forEach (item) ->
item.should.eql(items[called])
called++
called.should.equal(3)
it "It should break returning false", ->
called = 0
coll = collection()
items = coll.toArray()
coll.forEach (item) ->
item.should.eql(items[called])
called++
false
called.should.equal(1)
describe "#forEachRight", ->
it "Should be chainable", ->
collection().forEachRight(->).should.be.instanceOf(Collection)
it "Should invoke callback for each item", ->
called = 3
coll = collection()
items = coll.toArray()
coll.forEachRight (item) ->
called--
item.should.eql(items[called])
called.should.equal(0)
describe "#groupBy", ->
it "Should group by keys", ->
items = [{a:"A"}, {a: "A"}, {a: "B"}]
expected = {"A": {items: [{a: "A"}, {a: "A"}]}, "B": {items: [{a: "B"}]}}
collection(items).groupBy('a').should.eql(expected)
describe "#indexBy", ->
it "Should index keys", ->
items = [{a:"A"}, {a: "A"}, {a: "B"}]
expected = {"A": {items: [{a: "A"}]}, "B": {items: [{a: "B"}]}}
collection(items).indexBy('a').should.eql(expected)
describe "#invoke", ->
it "Should invoke methods on items", ->
items = [[5, 1, 7], [3, 2, 1]]
expected = [[1, 5, 7], [1, 2, 3]]
collection(items).invoke("sort").should.eql(expected)
describe "#map", ->
it "Should map items", ->
items = [1..3]
expected = [3, 6, 9]
fn = (n) -> n * 3
collection(items).map(fn).toArray().should.eql(expected)
describe "#max", ->
it "Should return the max item by key", ->
collection().max('a').should.eql({a: 3, b: 3})
describe "#min", ->
it "Should return the min item by key", ->
collection().min('a').should.eql({a: 1, b: 1})
describe "#pluck", ->
it "Should pluck a collection", ->
collection().pluck('a').should.eql([1,2,3])
describe "#reject", ->
it "should return filtered collection", ->
collection().reject(a: 2).toArray().should.eql([{a: 1, b: 1}, {a: 3, b: 3}])
describe "#sample", ->
it "Should return a new collection with an item from the original one", ->
coll = collection([1..10])
coll.contains(coll.sample().first())
describe "#shuffle", ->
it "Shoudl return a new collection (pretty much impossible to test further)", ->
collection().shuffle().should.be.instanceOf(Collection)
describe "#size", ->
it "should return the right size", ->
collection().size().should.equal(3)
describe "#slice", ->
it "should return right slices", ->
collection().slice(1,2).toArray().should.eql([{ a: 2, b: 2 }])
collection().slice(1).toArray().should.eql([{ a: 2, b: 2 }, { a: 3, b: 3 }])
describe "#some", ->
it "Should return true if any values matches", ->
collection([{a: 1, b: 1}, {a: 1, b: 2}]).some({b: 1}).should.be.true
it "Should return false if no values matches", ->
collection([{a: 1, b: 1}, {a: 1, b: 2}]).some({a: 2}).should.be.false
describe "#sortBy", ->
it "Should sort by key", ->
items = [
{ 'name': 'PI:NAME:<NAME>END_PI', 'age': 36 }
{ 'name': 'PI:NAME:<NAME>END_PI', 'age': 40 }
{ 'name': 'PI:NAME:<NAME>END_PI', 'age': 26 }
{ 'name': 'PI:NAME:<NAME>END_PI', 'age': 30 }
]
expected = [
{ 'name': 'PI:NAME:<NAME>END_PI', 'age': 26 }
{ 'name': 'PI:NAME:<NAME>END_PI', 'age': 30 }
{ 'name': 'PI:NAME:<NAME>END_PI', 'age': 36 }
{ 'name': 'PI:NAME:<NAME>END_PI', 'age': 40 }
]
collection(items).sortBy('age').toArray().should.eql(expected)
it "Should sort by in descending order", ->
items = [
{ 'name': 'PI:NAME:<NAME>END_PI', 'age': 36 }
{ 'name': 'PI:NAME:<NAME>END_PI', 'age': 40 }
{ 'name': 'PI:NAME:<NAME>END_PI', 'age': 26 }
{ 'name': 'PI:NAME:<NAME>END_PI', 'age': 30 }
]
expected = [
{ 'name': 'PI:NAME:<NAME>END_PI', 'age': 40 }
{ 'name': 'PI:NAME:<NAME>END_PI', 'age': 36 }
{ 'name': 'PI:NAME:<NAME>END_PI', 'age': 30 }
{ 'name': 'PI:NAME:<NAME>END_PI', 'age': 26 }
]
collection(items).sortBy('age', 'desc').toArray().should.eql(expected)
describe "#where", ->
it "should return filtered collection", ->
collection().where(a: 2).toArray().should.eql([{ a: 2, b: 2 }])
describe "#reduce", ->
it "should reduce left", ->
fn = (acc, item) -> acc + item.a
collection().reduce(fn, 0).should.eql(6)
describe "#reduceRight", ->
it "should reduce right", ->
fn = (acc, item) -> acc + item.a
collection().reduceRight(fn, 0).should.eql(6)
#
# Aliases
#
describe "#include", ->
it "Should be an alias", ->
Collection::include.should.be.a.Function
(Collection::include is Collection::contains).should.be.true
describe "#all", ->
it "Should be an alias", ->
Collection::all.should.be.a.Function
(Collection::all is Collection::every).should.be.true
describe "#select", ->
it "Should be an alias", ->
Collection::select.should.be.a.Function
(Collection::select is Collection::filter).should.be.true
describe "#detect", ->
it "Should be an alias", ->
Collection::detect.should.be.a.Function
(Collection::detect is Collection::find).should.be.true
describe "#findWhere", ->
it "Should be an alias", ->
Collection::findWhere.should.be.a.Function
(Collection::findWhere is Collection::find).should.be.true
describe "#each", ->
it "Should be an alias", ->
Collection::each.should.be.a.Function
(Collection::each is Collection::forEach).should.be.true
describe "#eachRight", ->
it "Should be an alias", ->
Collection::eachRight.should.be.a.Function
(Collection::eachRight is Collection::forEachRight).should.be.true
describe "#collect", ->
it "Should be an alias", ->
Collection::collect.should.be.a.Function
(Collection::collect is Collection::map).should.be.true
describe "#foldl", ->
it "Should be an alias", ->
Collection::foldl.should.be.a.Function
(Collection::foldl is Collection::reduce ).should.be.true
describe "#inject", ->
it "Should be an alias", ->
Collection::inject.should.be.a.Function
(Collection::inject is Collection::reduce).should.be.true
describe "#foldr", ->
it "Should be an alias", ->
Collection::foldr.should.be.a.Function
(Collection::foldr is Collection::reduceRight).should.be.true
describe "#any", ->
it "Should be an alias", ->
Collection::any.should.be.a.Function
(Collection::any is Collection::some).should.be.true
|
[
{
"context": "e:\n#\n# @ARTICLE{Schulz02faststring,\n# author = {Klaus Schulz and Stoyan Mihov},\n# title = {Fast String Corre",
"end": 163,
"score": 0.9998989105224609,
"start": 151,
"tag": "NAME",
"value": "Klaus Schulz"
},
{
"context": "Schulz02faststring,\n# author = {Klaus... | src/levenshtein/transducer.coffee | DhrubajitPC/liblevenshtein-coffeescript | 13 | ###*
# The algorithm for imitating Levenshtein automata was taken from the
# following journal article:
#
# @ARTICLE{Schulz02faststring,
# author = {Klaus Schulz and Stoyan Mihov},
# title = {Fast String Correction with Levenshtein-Automata},
# journal = {INTERNATIONAL JOURNAL OF DOCUMENT ANALYSIS AND RECOGNITION},
# year = {2002},
# volume = {5},
# pages = {67--85}
# }
#
# As well, this Master Thesis helped me understand its concepts:
#
# www.fmi.uni-sofia.bg/fmi/logic/theses/mitankin-en.pdf
#
# The supervisor of the student who submitted the thesis was one of the
# authors of the journal article, above.
#
# The algorithm for constructing a DAWG (Direct Acyclic Word Graph) from the
# input dictionary of words (DAWGs are otherwise known as an MA-FSA, or
# Minimal Acyclic Finite-State Automata), was taken and modified from the
# following blog from Steve Hanov:
#
# http://stevehanov.ca/blog/index.php?id=115
#
# The algorithm therein was taken from the following paper:
#
# @MISC{Daciuk00incrementalconstruction,
# author = {Jan Daciuk and Bruce W. Watson and Richard E. Watson and Stoyan Mihov},
# title = {Incremental Construction of Minimal Acyclic Finite-State Automata},
# year = {2000}
# }
###
class Transducer
# Accepts a state corresponding to some dictionary term and the length of the
# query term, and identifies the minimum distance between the terms.
'minimum_distance': (state, w) ->
throw new Error('minimum_distance not specified on construction')
# Returns a collection for storing spelling candidates. The only requirement
# is that it has a push(candidate) method and can be passed to
# this.transform(matches)
'build_matches': () ->
throw new Error('build_matches not specified on construction')
# Returns the initial state of the Levenshtein automaton
'initial_state': () ->
throw new Error('initial_state not specified on construction')
# Returns the root of the dictionary
'root': () ->
throw new Error('root not specified on construction')
# Returns a mapping of labels to dictionary states, which correspond to the
# outgoing edges of a dictionary state.
'edges': (q_D) ->
throw new Error('edges not specified on construction')
# Determines whether a dictionary state is final
'is_final': (q_D) ->
throw new Error('is_final not specified on construction')
# Transforms a collection of spelling candidates as necessary
'transform': (matches) ->
throw new Error('transform not specified on construction')
# Accepts the maximum edit distance and returns a function that transitions
# among states.
'transition_for_state': (n) ->
throw new Error('transition_for_state not specified on construction')
# Returns the characteristic vector of a set of parameters (see the paper,
# "Fast String Correction with Levenshtein-Automata")
'characteristic_vector': (x, term, k, i) ->
throw new Error('characteristic_vector not specified on construction')
# Pushes a spelling candidate onto the matches
'push': (matches, candidate) ->
throw new Error('push not specified on construction')
# Specifies the default, maximum edit distance a spelling candidate may be
# from a query term.
'default_edit_distance': () ->
throw new Error('default_edit_distance not specified on construction')
constructor: (attributes) ->
for own attribute of attributes
this[attribute] = attributes[attribute]
# Returns every term in the dictionary that is within n units of error from
# the query term.
'transduce': (term, n) ->
n = @['default_edit_distance']() unless typeof n is 'number'
w = term.length
transition = @['transition_for_state'](n)
matches = @['build_matches']()
stack = [['', @['root'](), @['initial_state']()]]
while stack.length > 0
[V, q_D, M] = stack['pop'](); i = M[0][0]
a = 2 * n + 1; b = w - i
k = if a < b then a else b
for x, next_q_D of @['edges'](q_D)
vector = @['characteristic_vector'](x, term, k, i)
next_M = transition(M, vector)
if next_M
next_V = V + x
stack.push([next_V, next_q_D, next_M])
if @['is_final'](next_q_D)
distance = @['minimum_distance'](next_M, w)
if distance <= n
@['push'](matches, [next_V, distance])
@['transform'](matches)
global =
if typeof exports is 'object'
exports
else if typeof window is 'object'
window
else
this
global['levenshtein'] ||= {}
global['levenshtein']['Transducer'] = Transducer
| 147462 | ###*
# The algorithm for imitating Levenshtein automata was taken from the
# following journal article:
#
# @ARTICLE{Schulz02faststring,
# author = {<NAME> and <NAME>},
# title = {Fast String Correction with Levenshtein-Automata},
# journal = {INTERNATIONAL JOURNAL OF DOCUMENT ANALYSIS AND RECOGNITION},
# year = {2002},
# volume = {5},
# pages = {67--85}
# }
#
# As well, this Master Thesis helped me understand its concepts:
#
# www.fmi.uni-sofia.bg/fmi/logic/theses/mitankin-en.pdf
#
# The supervisor of the student who submitted the thesis was one of the
# authors of the journal article, above.
#
# The algorithm for constructing a DAWG (Direct Acyclic Word Graph) from the
# input dictionary of words (DAWGs are otherwise known as an MA-FSA, or
# Minimal Acyclic Finite-State Automata), was taken and modified from the
# following blog from Steve Hanov:
#
# http://stevehanov.ca/blog/index.php?id=115
#
# The algorithm therein was taken from the following paper:
#
# @MISC{Daciuk00incrementalconstruction,
# author = {<NAME> and <NAME> and <NAME> and <NAME>},
# title = {Incremental Construction of Minimal Acyclic Finite-State Automata},
# year = {2000}
# }
###
class Transducer
# Accepts a state corresponding to some dictionary term and the length of the
# query term, and identifies the minimum distance between the terms.
'minimum_distance': (state, w) ->
throw new Error('minimum_distance not specified on construction')
# Returns a collection for storing spelling candidates. The only requirement
# is that it has a push(candidate) method and can be passed to
# this.transform(matches)
'build_matches': () ->
throw new Error('build_matches not specified on construction')
# Returns the initial state of the Levenshtein automaton
'initial_state': () ->
throw new Error('initial_state not specified on construction')
# Returns the root of the dictionary
'root': () ->
throw new Error('root not specified on construction')
# Returns a mapping of labels to dictionary states, which correspond to the
# outgoing edges of a dictionary state.
'edges': (q_D) ->
throw new Error('edges not specified on construction')
# Determines whether a dictionary state is final
'is_final': (q_D) ->
throw new Error('is_final not specified on construction')
# Transforms a collection of spelling candidates as necessary
'transform': (matches) ->
throw new Error('transform not specified on construction')
# Accepts the maximum edit distance and returns a function that transitions
# among states.
'transition_for_state': (n) ->
throw new Error('transition_for_state not specified on construction')
# Returns the characteristic vector of a set of parameters (see the paper,
# "Fast String Correction with Levenshtein-Automata")
'characteristic_vector': (x, term, k, i) ->
throw new Error('characteristic_vector not specified on construction')
# Pushes a spelling candidate onto the matches
'push': (matches, candidate) ->
throw new Error('push not specified on construction')
# Specifies the default, maximum edit distance a spelling candidate may be
# from a query term.
'default_edit_distance': () ->
throw new Error('default_edit_distance not specified on construction')
constructor: (attributes) ->
for own attribute of attributes
this[attribute] = attributes[attribute]
# Returns every term in the dictionary that is within n units of error from
# the query term.
'transduce': (term, n) ->
n = @['default_edit_distance']() unless typeof n is 'number'
w = term.length
transition = @['transition_for_state'](n)
matches = @['build_matches']()
stack = [['', @['root'](), @['initial_state']()]]
while stack.length > 0
[V, q_D, M] = stack['pop'](); i = M[0][0]
a = 2 * n + 1; b = w - i
k = if a < b then a else b
for x, next_q_D of @['edges'](q_D)
vector = @['characteristic_vector'](x, term, k, i)
next_M = transition(M, vector)
if next_M
next_V = V + x
stack.push([next_V, next_q_D, next_M])
if @['is_final'](next_q_D)
distance = @['minimum_distance'](next_M, w)
if distance <= n
@['push'](matches, [next_V, distance])
@['transform'](matches)
global =
if typeof exports is 'object'
exports
else if typeof window is 'object'
window
else
this
global['levenshtein'] ||= {}
global['levenshtein']['Transducer'] = Transducer
| true | ###*
# The algorithm for imitating Levenshtein automata was taken from the
# following journal article:
#
# @ARTICLE{Schulz02faststring,
# author = {PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI},
# title = {Fast String Correction with Levenshtein-Automata},
# journal = {INTERNATIONAL JOURNAL OF DOCUMENT ANALYSIS AND RECOGNITION},
# year = {2002},
# volume = {5},
# pages = {67--85}
# }
#
# As well, this Master Thesis helped me understand its concepts:
#
# www.fmi.uni-sofia.bg/fmi/logic/theses/mitankin-en.pdf
#
# The supervisor of the student who submitted the thesis was one of the
# authors of the journal article, above.
#
# The algorithm for constructing a DAWG (Direct Acyclic Word Graph) from the
# input dictionary of words (DAWGs are otherwise known as an MA-FSA, or
# Minimal Acyclic Finite-State Automata), was taken and modified from the
# following blog from Steve Hanov:
#
# http://stevehanov.ca/blog/index.php?id=115
#
# The algorithm therein was taken from the following paper:
#
# @MISC{Daciuk00incrementalconstruction,
# author = {PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI},
# title = {Incremental Construction of Minimal Acyclic Finite-State Automata},
# year = {2000}
# }
###
class Transducer
# Accepts a state corresponding to some dictionary term and the length of the
# query term, and identifies the minimum distance between the terms.
'minimum_distance': (state, w) ->
throw new Error('minimum_distance not specified on construction')
# Returns a collection for storing spelling candidates. The only requirement
# is that it has a push(candidate) method and can be passed to
# this.transform(matches)
'build_matches': () ->
throw new Error('build_matches not specified on construction')
# Returns the initial state of the Levenshtein automaton
'initial_state': () ->
throw new Error('initial_state not specified on construction')
# Returns the root of the dictionary
'root': () ->
throw new Error('root not specified on construction')
# Returns a mapping of labels to dictionary states, which correspond to the
# outgoing edges of a dictionary state.
'edges': (q_D) ->
throw new Error('edges not specified on construction')
# Determines whether a dictionary state is final
'is_final': (q_D) ->
throw new Error('is_final not specified on construction')
# Transforms a collection of spelling candidates as necessary
'transform': (matches) ->
throw new Error('transform not specified on construction')
# Accepts the maximum edit distance and returns a function that transitions
# among states.
'transition_for_state': (n) ->
throw new Error('transition_for_state not specified on construction')
# Returns the characteristic vector of a set of parameters (see the paper,
# "Fast String Correction with Levenshtein-Automata")
'characteristic_vector': (x, term, k, i) ->
throw new Error('characteristic_vector not specified on construction')
# Pushes a spelling candidate onto the matches
'push': (matches, candidate) ->
throw new Error('push not specified on construction')
# Specifies the default, maximum edit distance a spelling candidate may be
# from a query term.
'default_edit_distance': () ->
throw new Error('default_edit_distance not specified on construction')
constructor: (attributes) ->
for own attribute of attributes
this[attribute] = attributes[attribute]
# Returns every term in the dictionary that is within n units of error from
# the query term.
'transduce': (term, n) ->
n = @['default_edit_distance']() unless typeof n is 'number'
w = term.length
transition = @['transition_for_state'](n)
matches = @['build_matches']()
stack = [['', @['root'](), @['initial_state']()]]
while stack.length > 0
[V, q_D, M] = stack['pop'](); i = M[0][0]
a = 2 * n + 1; b = w - i
k = if a < b then a else b
for x, next_q_D of @['edges'](q_D)
vector = @['characteristic_vector'](x, term, k, i)
next_M = transition(M, vector)
if next_M
next_V = V + x
stack.push([next_V, next_q_D, next_M])
if @['is_final'](next_q_D)
distance = @['minimum_distance'](next_M, w)
if distance <= n
@['push'](matches, [next_V, distance])
@['transform'](matches)
global =
if typeof exports is 'object'
exports
else if typeof window is 'object'
window
else
this
global['levenshtein'] ||= {}
global['levenshtein']['Transducer'] = Transducer
|
[
{
"context": " uuid: 'the-user-uuid'\n token: 'the-user-token'\n\n @UUID.v4.returns 'an-instance-uuid'\n ",
"end": 1540,
"score": 0.7811807990074158,
"start": 1526,
"tag": "PASSWORD",
"value": "the-user-token"
},
{
"context": "erateAndStoreTokenWithOptions.... | test/controllers/instances-controller-spec.coffee | octoblu/nanocyte-flow-deploy-service | 0 | InstancesController = require '../../src/controllers/instances-controller'
NanocyteDeployer = require 'nanocyte-deployer'
describe '/instances', ->
beforeEach ->
@response =
location: sinon.spy => @response
status: sinon.spy => @response
end: sinon.spy => @response
send: sinon.spy => @response
@UUID =
v4: sinon.stub()
@nanocyteDeployer =
deploy: sinon.stub()
destroy: sinon.stub()
startFlow: sinon.stub()
stopFlow: sinon.stub()
sendStopFlowMessage: sinon.stub()
@meshbluHttp =
generateAndStoreTokenWithOptions: sinon.stub()
options = {
UUID: @UUID
mongoDbUri: 'localhost'
redisUri: 'localhost'
octobluUrl: 'http://yahho.com'
flowLoggerUuid: 'flow-logger-uuid'
nanocyteEngineUrl: 'https://genisys.com'
intervalServiceUri: 'http://interval.octoblu.dev'
nodeRegistryUrl: 'http://registry.octoblu.dev'
}
@sut = new InstancesController options
@_createNanocyteDeployer = sinon.stub @sut, '_createNanocyteDeployer'
@_createNanocyteDeployer.returns @nanocyteDeployer
@_createMeshbluHttp = sinon.stub @sut, '_createMeshbluHttp'
@_createMeshbluHttp.returns @meshbluHttp
describe 'when /instances receives a post message', ->
beforeEach ->
request =
get: sinon.stub().withArgs('deploymentUuid').returns('the-deployment-uuid')
params:
flowId: 'some-flow-uuid'
meshbluAuth:
uuid: 'the-user-uuid'
token: 'the-user-token'
@UUID.v4.returns 'an-instance-uuid'
@sut.create request, @response
describe 'when deploy is successful', ->
beforeEach ->
@meshbluHttp.generateAndStoreTokenWithOptions.yield null, token: 'cool-token-bro'
@nanocyteDeployer.sendStopFlowMessage.yield null
@nanocyteDeployer.deploy.yield null
it 'should call _createMeshbluHttp', ->
expect(@_createMeshbluHttp).to.have.been.calledWith uuid: 'the-user-uuid', token: 'the-user-token'
it 'should call generateAndStoreTokenWithOptions', ->
expect(@meshbluHttp.generateAndStoreTokenWithOptions).to.have.been.calledWith 'some-flow-uuid'
it 'should call deploy on the nanocyte deployer', ->
expect(@nanocyteDeployer.deploy).to.have.been.called
it 'should call _createNanocyteDeployer', ->
expect(@_createNanocyteDeployer).to.have.been.calledWith
client: @sut.client
deploymentUuid: 'the-deployment-uuid'
flowUuid: 'some-flow-uuid'
instanceId: 'an-instance-uuid'
flowToken: 'cool-token-bro'
userUuid: 'the-user-uuid'
userToken: 'the-user-token'
octobluUrl: 'http://yahho.com'
forwardUrl: 'https://genisys.com/flows/some-flow-uuid/instances/an-instance-uuid/messages'
flowLoggerUuid: 'flow-logger-uuid'
intervalServiceUri: 'http://interval.octoblu.dev'
describe 'and startFlow fails', ->
beforeEach ->
@nanocyteDeployer.startFlow.yield new Error 'something wrong'
it 'should respond with a 422', ->
expect(@response.status).to.have.been.calledWith 422
expect(@response.send).to.have.been.calledWith 'something wrong'
it 'should call startFlow on the nanocyte deployer', ->
expect(@nanocyteDeployer.startFlow).to.have.been.called
describe 'and startFlow succeeds', ->
beforeEach ->
@nanocyteDeployer.startFlow.yield null
it 'should call startFlow on the nanocyte deployer', ->
expect(@nanocyteDeployer.startFlow).to.have.been.called
it 'should respond with a 201', ->
expect(@response.status).to.have.been.calledWith 201
expect(@response.location).to.have.been.calledWith '/flows/some-flow-uuid/instances/an-instance-uuid'
expect(@response.end).to.have.been.called
describe 'when deploy is failure', ->
beforeEach ->
@meshbluHttp.generateAndStoreTokenWithOptions.yield null
@nanocyteDeployer.sendStopFlowMessage.yield null
@nanocyteDeployer.deploy.yield new Error 'something wrong'
it 'should respond with a 422', ->
expect(@response.status).to.have.been.calledWith 422
expect(@response.send).to.have.been.calledWith 'something wrong'
describe 'when /instances receives a different post message', ->
beforeEach ->
request =
get: sinon.stub().withArgs('deploymentUuid').returns('some-other-deployment-uuid')
params:
flowId: 'some-other-flow-uuid'
meshbluAuth:
uuid: 'the-user-uuid'
token: 'the-user-token'
@UUID.v4.returns 'an-instance-uuid'
@sut.create request, @response
describe 'when deploy is successful', ->
beforeEach ->
@meshbluHttp.generateAndStoreTokenWithOptions.yield null, token: 'do-you-even-token-bro'
@nanocyteDeployer.sendStopFlowMessage.yield null
@nanocyteDeployer.deploy.yield null
@nanocyteDeployer.startFlow.yield null
it 'should call generateAndStoreTokenWithOptions', ->
expect(@meshbluHttp.generateAndStoreTokenWithOptions).to.have.been.calledWith 'some-other-flow-uuid'
it 'should call _createNanocyteDeployer', ->
expect(@_createNanocyteDeployer).to.have.been.calledWith
client: @sut.client
deploymentUuid: 'some-other-deployment-uuid'
flowUuid: 'some-other-flow-uuid'
instanceId: 'an-instance-uuid'
flowToken: 'do-you-even-token-bro'
userUuid: 'the-user-uuid'
userToken: 'the-user-token'
octobluUrl: 'http://yahho.com'
forwardUrl: 'https://genisys.com/flows/some-other-flow-uuid/instances/an-instance-uuid/messages'
flowLoggerUuid: 'flow-logger-uuid'
intervalServiceUri: 'http://interval.octoblu.dev'
it 'should respond with a 201', ->
expect(@response.status).to.have.been.calledWith 201
expect(@response.location).to.have.been.calledWith '/flows/some-other-flow-uuid/instances/an-instance-uuid'
expect(@response.end).to.have.been.called
it 'should call deploy on the nanocyte deployer', ->
expect(@nanocyteDeployer.deploy).to.have.been.called
describe 'when nanocyte deployer is given a new instance uuid with post', ->
beforeEach ->
request =
get: sinon.stub().withArgs('deploymentUuid').returns 'this-deployment-uuid'
params:
flowId: 'some-other-new-flow-uuid'
meshbluAuth:
uuid: 'the-user-uuid'
token: 'the-user-token'
@UUID.v4.returns 'a-new-instance-uuid'
@sut.create request, @response
describe 'when deploy is successful', ->
beforeEach ->
@meshbluHttp.generateAndStoreTokenWithOptions.yield null, token: 'lame-token-bro'
@nanocyteDeployer.sendStopFlowMessage.yield null
@nanocyteDeployer.deploy.yield null
@nanocyteDeployer.startFlow.yield null
it 'should call _createNanocyteDeployer', ->
expect(@_createNanocyteDeployer).to.have.been.calledWith
client: @sut.client
deploymentUuid: 'this-deployment-uuid'
flowUuid: 'some-other-new-flow-uuid'
instanceId: 'a-new-instance-uuid'
flowToken: 'lame-token-bro'
userUuid: 'the-user-uuid'
userToken: 'the-user-token'
octobluUrl: 'http://yahho.com'
forwardUrl: 'https://genisys.com/flows/some-other-new-flow-uuid/instances/a-new-instance-uuid/messages'
flowLoggerUuid: 'flow-logger-uuid'
intervalServiceUri: 'http://interval.octoblu.dev'
it 'should respond with a 201', ->
expect(@response.status).to.have.been.calledWith 201
expect(@response.location).to.have.been.calledWith '/flows/some-other-new-flow-uuid/instances/a-new-instance-uuid'
expect(@response.end).to.have.been.called
it 'should call deploy on the nanocyte deployer', ->
expect(@nanocyteDeployer.deploy).to.have.been.called
describe 'when /instances receives a delete message', ->
beforeEach ->
request =
get: sinon.stub().withArgs('deploymentUuid').returns 'this-deployment-uuid'
params:
flowId: 'some-flow-uuid'
meshbluAuth:
uuid: 'awesome-user-uuid'
token: 'super-cool-user-token'
@UUID.v4.returns 'an-instance-uuid'
@sut.destroy request, @response
describe 'when stopFlow is successful', ->
beforeEach ->
@meshbluHttp.generateAndStoreTokenWithOptions.yield null, token: 'cool-token-bro'
@nanocyteDeployer.stopFlow.yield null
it 'should call generateAndStoreTokenWithOptions', ->
expect(@meshbluHttp.generateAndStoreTokenWithOptions).to.have.been.calledWith 'some-flow-uuid'
it 'should call _createNanocyteDeployer', ->
expect(@_createNanocyteDeployer).to.have.been.calledWith
client: @sut.client
flowUuid: 'some-flow-uuid'
instanceId: 'an-instance-uuid'
flowToken: 'cool-token-bro'
userUuid: 'awesome-user-uuid'
userToken: 'super-cool-user-token'
deploymentUuid: 'this-deployment-uuid'
octobluUrl: 'http://yahho.com'
forwardUrl: 'https://genisys.com/flows/some-flow-uuid/instances/an-instance-uuid/messages'
flowLoggerUuid: 'flow-logger-uuid'
intervalServiceUri: 'http://interval.octoblu.dev'
it 'should call nanocyteDeployer.stopFlow', ->
expect(@nanocyteDeployer.stopFlow).to.have.been.called
describe 'and nanocyteDeployer.destroy is a success', ->
beforeEach ->
@nanocyteDeployer.destroy.yield null
it 'should call nanocyteDeployer.destroy', ->
expect(@nanocyteDeployer.destroy).to.have.been.called
it 'should respond with a 204', ->
expect(@response.status).to.have.been.calledWith 204
expect(@response.end).to.have.been.called
describe 'and nanocyteDeployer.destroy is a failure', ->
beforeEach ->
@nanocyteDeployer.destroy.yield new Error "wrong things happened"
it 'should call nanocyteDeployer.destroy', ->
expect(@nanocyteDeployer.destroy).to.have.been.called
it 'should respond with a 422', ->
expect(@response.status).to.have.been.calledWith 422
expect(@response.send).to.have.been.calledWith "wrong things happened"
describe 'when stopFlow is failure', ->
beforeEach ->
@meshbluHttp.generateAndStoreTokenWithOptions.yield null, token: 'cool-token-bro'
@nanocyteDeployer.stopFlow.yield new Error "Oh no!"
it 'should call generateAndStoreTokenWithOptions', ->
expect(@meshbluHttp.generateAndStoreTokenWithOptions).to.have.been.calledWith 'some-flow-uuid'
it 'should call _createNanocyteDeployer', ->
expect(@_createNanocyteDeployer).to.have.been.calledWith
client: @sut.client
deploymentUuid: 'this-deployment-uuid'
flowUuid: 'some-flow-uuid'
instanceId: 'an-instance-uuid'
flowToken: 'cool-token-bro'
userUuid: 'awesome-user-uuid'
userToken: 'super-cool-user-token'
octobluUrl: 'http://yahho.com'
forwardUrl: 'https://genisys.com/flows/some-flow-uuid/instances/an-instance-uuid/messages'
flowLoggerUuid: 'flow-logger-uuid'
intervalServiceUri: 'http://interval.octoblu.dev'
it 'should respond with a 422 and Error', ->
expect(@response.status).to.have.been.calledWith 422
expect(@response.send).to.have.been.calledWith 'Oh no!'
it 'should call nanocyteDeployer.stopFlow', ->
expect(@nanocyteDeployer.stopFlow).to.have.been.called
| 146734 | InstancesController = require '../../src/controllers/instances-controller'
NanocyteDeployer = require 'nanocyte-deployer'
describe '/instances', ->
beforeEach ->
@response =
location: sinon.spy => @response
status: sinon.spy => @response
end: sinon.spy => @response
send: sinon.spy => @response
@UUID =
v4: sinon.stub()
@nanocyteDeployer =
deploy: sinon.stub()
destroy: sinon.stub()
startFlow: sinon.stub()
stopFlow: sinon.stub()
sendStopFlowMessage: sinon.stub()
@meshbluHttp =
generateAndStoreTokenWithOptions: sinon.stub()
options = {
UUID: @UUID
mongoDbUri: 'localhost'
redisUri: 'localhost'
octobluUrl: 'http://yahho.com'
flowLoggerUuid: 'flow-logger-uuid'
nanocyteEngineUrl: 'https://genisys.com'
intervalServiceUri: 'http://interval.octoblu.dev'
nodeRegistryUrl: 'http://registry.octoblu.dev'
}
@sut = new InstancesController options
@_createNanocyteDeployer = sinon.stub @sut, '_createNanocyteDeployer'
@_createNanocyteDeployer.returns @nanocyteDeployer
@_createMeshbluHttp = sinon.stub @sut, '_createMeshbluHttp'
@_createMeshbluHttp.returns @meshbluHttp
describe 'when /instances receives a post message', ->
beforeEach ->
request =
get: sinon.stub().withArgs('deploymentUuid').returns('the-deployment-uuid')
params:
flowId: 'some-flow-uuid'
meshbluAuth:
uuid: 'the-user-uuid'
token: '<PASSWORD>'
@UUID.v4.returns 'an-instance-uuid'
@sut.create request, @response
describe 'when deploy is successful', ->
beforeEach ->
@meshbluHttp.generateAndStoreTokenWithOptions.yield null, token: '<KEY>'
@nanocyteDeployer.sendStopFlowMessage.yield null
@nanocyteDeployer.deploy.yield null
it 'should call _createMeshbluHttp', ->
expect(@_createMeshbluHttp).to.have.been.calledWith uuid: 'the-user-uuid', token: '<PASSWORD>'
it 'should call generateAndStoreTokenWithOptions', ->
expect(@meshbluHttp.generateAndStoreTokenWithOptions).to.have.been.calledWith 'some-flow-uuid'
it 'should call deploy on the nanocyte deployer', ->
expect(@nanocyteDeployer.deploy).to.have.been.called
it 'should call _createNanocyteDeployer', ->
expect(@_createNanocyteDeployer).to.have.been.calledWith
client: @sut.client
deploymentUuid: 'the-deployment-uuid'
flowUuid: 'some-flow-uuid'
instanceId: 'an-instance-uuid'
flowToken: '<KEY>'
userUuid: 'the-user-uuid'
userToken: '<PASSWORD>'
octobluUrl: 'http://yahho.com'
forwardUrl: 'https://genisys.com/flows/some-flow-uuid/instances/an-instance-uuid/messages'
flowLoggerUuid: 'flow-logger-uuid'
intervalServiceUri: 'http://interval.octoblu.dev'
describe 'and startFlow fails', ->
beforeEach ->
@nanocyteDeployer.startFlow.yield new Error 'something wrong'
it 'should respond with a 422', ->
expect(@response.status).to.have.been.calledWith 422
expect(@response.send).to.have.been.calledWith 'something wrong'
it 'should call startFlow on the nanocyte deployer', ->
expect(@nanocyteDeployer.startFlow).to.have.been.called
describe 'and startFlow succeeds', ->
beforeEach ->
@nanocyteDeployer.startFlow.yield null
it 'should call startFlow on the nanocyte deployer', ->
expect(@nanocyteDeployer.startFlow).to.have.been.called
it 'should respond with a 201', ->
expect(@response.status).to.have.been.calledWith 201
expect(@response.location).to.have.been.calledWith '/flows/some-flow-uuid/instances/an-instance-uuid'
expect(@response.end).to.have.been.called
describe 'when deploy is failure', ->
beforeEach ->
@meshbluHttp.generateAndStoreTokenWithOptions.yield null
@nanocyteDeployer.sendStopFlowMessage.yield null
@nanocyteDeployer.deploy.yield new Error 'something wrong'
it 'should respond with a 422', ->
expect(@response.status).to.have.been.calledWith 422
expect(@response.send).to.have.been.calledWith 'something wrong'
describe 'when /instances receives a different post message', ->
beforeEach ->
request =
get: sinon.stub().withArgs('deploymentUuid').returns('some-other-deployment-uuid')
params:
flowId: 'some-other-flow-uuid'
meshbluAuth:
uuid: 'the-user-uuid'
token: '<PASSWORD>'
@UUID.v4.returns 'an-instance-uuid'
@sut.create request, @response
describe 'when deploy is successful', ->
beforeEach ->
@meshbluHttp.generateAndStoreTokenWithOptions.yield null, token: '<KEY>-<PASSWORD>'
@nanocyteDeployer.sendStopFlowMessage.yield null
@nanocyteDeployer.deploy.yield null
@nanocyteDeployer.startFlow.yield null
it 'should call generateAndStoreTokenWithOptions', ->
expect(@meshbluHttp.generateAndStoreTokenWithOptions).to.have.been.calledWith 'some-other-flow-uuid'
it 'should call _createNanocyteDeployer', ->
expect(@_createNanocyteDeployer).to.have.been.calledWith
client: @sut.client
deploymentUuid: 'some-other-deployment-uuid'
flowUuid: 'some-other-flow-uuid'
instanceId: 'an-instance-uuid'
flowToken: '<KEY>-<PASSWORD>'
userUuid: 'the-user-uuid'
userToken: '<PASSWORD>'
octobluUrl: 'http://yahho.com'
forwardUrl: 'https://genisys.com/flows/some-other-flow-uuid/instances/an-instance-uuid/messages'
flowLoggerUuid: 'flow-logger-uuid'
intervalServiceUri: 'http://interval.octoblu.dev'
it 'should respond with a 201', ->
expect(@response.status).to.have.been.calledWith 201
expect(@response.location).to.have.been.calledWith '/flows/some-other-flow-uuid/instances/an-instance-uuid'
expect(@response.end).to.have.been.called
it 'should call deploy on the nanocyte deployer', ->
expect(@nanocyteDeployer.deploy).to.have.been.called
describe 'when nanocyte deployer is given a new instance uuid with post', ->
beforeEach ->
request =
get: sinon.stub().withArgs('deploymentUuid').returns 'this-deployment-uuid'
params:
flowId: 'some-other-new-flow-uuid'
meshbluAuth:
uuid: 'the-user-uuid'
token: '<PASSWORD>'
@UUID.v4.returns 'a-new-instance-uuid'
@sut.create request, @response
describe 'when deploy is successful', ->
beforeEach ->
@meshbluHttp.generateAndStoreTokenWithOptions.yield null, token: '<PASSWORD>'
@nanocyteDeployer.sendStopFlowMessage.yield null
@nanocyteDeployer.deploy.yield null
@nanocyteDeployer.startFlow.yield null
it 'should call _createNanocyteDeployer', ->
expect(@_createNanocyteDeployer).to.have.been.calledWith
client: @sut.client
deploymentUuid: 'this-deployment-uuid'
flowUuid: 'some-other-new-flow-uuid'
instanceId: 'a-new-instance-uuid'
flowToken: '<PASSWORD>'
userUuid: 'the-user-uuid'
userToken: '<PASSWORD>'
octobluUrl: 'http://yahho.com'
forwardUrl: 'https://genisys.com/flows/some-other-new-flow-uuid/instances/a-new-instance-uuid/messages'
flowLoggerUuid: 'flow-logger-uuid'
intervalServiceUri: 'http://interval.octoblu.dev'
it 'should respond with a 201', ->
expect(@response.status).to.have.been.calledWith 201
expect(@response.location).to.have.been.calledWith '/flows/some-other-new-flow-uuid/instances/a-new-instance-uuid'
expect(@response.end).to.have.been.called
it 'should call deploy on the nanocyte deployer', ->
expect(@nanocyteDeployer.deploy).to.have.been.called
describe 'when /instances receives a delete message', ->
beforeEach ->
request =
get: sinon.stub().withArgs('deploymentUuid').returns 'this-deployment-uuid'
params:
flowId: 'some-flow-uuid'
meshbluAuth:
uuid: 'awesome-user-uuid'
token: '<PASSWORD>'
@UUID.v4.returns 'an-instance-uuid'
@sut.destroy request, @response
describe 'when stopFlow is successful', ->
beforeEach ->
@meshbluHttp.generateAndStoreTokenWithOptions.yield null, token: 'cool-token-bro'
@nanocyteDeployer.stopFlow.yield null
it 'should call generateAndStoreTokenWithOptions', ->
expect(@meshbluHttp.generateAndStoreTokenWithOptions).to.have.been.calledWith 'some-flow-uuid'
it 'should call _createNanocyteDeployer', ->
expect(@_createNanocyteDeployer).to.have.been.calledWith
client: @sut.client
flowUuid: 'some-flow-uuid'
instanceId: 'an-instance-uuid'
flowToken: '<PASSWORD>-<KEY>-bro'
userUuid: 'awesome-user-uuid'
userToken: '<PASSWORD>'
deploymentUuid: 'this-deployment-uuid'
octobluUrl: 'http://yahho.com'
forwardUrl: 'https://genisys.com/flows/some-flow-uuid/instances/an-instance-uuid/messages'
flowLoggerUuid: 'flow-logger-uuid'
intervalServiceUri: 'http://interval.octoblu.dev'
it 'should call nanocyteDeployer.stopFlow', ->
expect(@nanocyteDeployer.stopFlow).to.have.been.called
describe 'and nanocyteDeployer.destroy is a success', ->
beforeEach ->
@nanocyteDeployer.destroy.yield null
it 'should call nanocyteDeployer.destroy', ->
expect(@nanocyteDeployer.destroy).to.have.been.called
it 'should respond with a 204', ->
expect(@response.status).to.have.been.calledWith 204
expect(@response.end).to.have.been.called
describe 'and nanocyteDeployer.destroy is a failure', ->
beforeEach ->
@nanocyteDeployer.destroy.yield new Error "wrong things happened"
it 'should call nanocyteDeployer.destroy', ->
expect(@nanocyteDeployer.destroy).to.have.been.called
it 'should respond with a 422', ->
expect(@response.status).to.have.been.calledWith 422
expect(@response.send).to.have.been.calledWith "wrong things happened"
describe 'when stopFlow is failure', ->
beforeEach ->
@meshbluHttp.generateAndStoreTokenWithOptions.yield null, token: '<KEY>'
@nanocyteDeployer.stopFlow.yield new Error "Oh no!"
it 'should call generateAndStoreTokenWithOptions', ->
expect(@meshbluHttp.generateAndStoreTokenWithOptions).to.have.been.calledWith 'some-flow-uuid'
it 'should call _createNanocyteDeployer', ->
expect(@_createNanocyteDeployer).to.have.been.calledWith
client: @sut.client
deploymentUuid: 'this-deployment-uuid'
flowUuid: 'some-flow-uuid'
instanceId: 'an-instance-uuid'
flowToken: '<PASSWORD>-<KEY> <PASSWORD>-<KEY>'
userUuid: 'awesome-user-uuid'
userToken: '<PASSWORD>'
octobluUrl: 'http://yahho.com'
forwardUrl: 'https://genisys.com/flows/some-flow-uuid/instances/an-instance-uuid/messages'
flowLoggerUuid: 'flow-logger-uuid'
intervalServiceUri: 'http://interval.octoblu.dev'
it 'should respond with a 422 and Error', ->
expect(@response.status).to.have.been.calledWith 422
expect(@response.send).to.have.been.calledWith 'Oh no!'
it 'should call nanocyteDeployer.stopFlow', ->
expect(@nanocyteDeployer.stopFlow).to.have.been.called
| true | InstancesController = require '../../src/controllers/instances-controller'
NanocyteDeployer = require 'nanocyte-deployer'
describe '/instances', ->
beforeEach ->
@response =
location: sinon.spy => @response
status: sinon.spy => @response
end: sinon.spy => @response
send: sinon.spy => @response
@UUID =
v4: sinon.stub()
@nanocyteDeployer =
deploy: sinon.stub()
destroy: sinon.stub()
startFlow: sinon.stub()
stopFlow: sinon.stub()
sendStopFlowMessage: sinon.stub()
@meshbluHttp =
generateAndStoreTokenWithOptions: sinon.stub()
options = {
UUID: @UUID
mongoDbUri: 'localhost'
redisUri: 'localhost'
octobluUrl: 'http://yahho.com'
flowLoggerUuid: 'flow-logger-uuid'
nanocyteEngineUrl: 'https://genisys.com'
intervalServiceUri: 'http://interval.octoblu.dev'
nodeRegistryUrl: 'http://registry.octoblu.dev'
}
@sut = new InstancesController options
@_createNanocyteDeployer = sinon.stub @sut, '_createNanocyteDeployer'
@_createNanocyteDeployer.returns @nanocyteDeployer
@_createMeshbluHttp = sinon.stub @sut, '_createMeshbluHttp'
@_createMeshbluHttp.returns @meshbluHttp
describe 'when /instances receives a post message', ->
beforeEach ->
request =
get: sinon.stub().withArgs('deploymentUuid').returns('the-deployment-uuid')
params:
flowId: 'some-flow-uuid'
meshbluAuth:
uuid: 'the-user-uuid'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
@UUID.v4.returns 'an-instance-uuid'
@sut.create request, @response
describe 'when deploy is successful', ->
beforeEach ->
@meshbluHttp.generateAndStoreTokenWithOptions.yield null, token: 'PI:KEY:<KEY>END_PI'
@nanocyteDeployer.sendStopFlowMessage.yield null
@nanocyteDeployer.deploy.yield null
it 'should call _createMeshbluHttp', ->
expect(@_createMeshbluHttp).to.have.been.calledWith uuid: 'the-user-uuid', token: 'PI:PASSWORD:<PASSWORD>END_PI'
it 'should call generateAndStoreTokenWithOptions', ->
expect(@meshbluHttp.generateAndStoreTokenWithOptions).to.have.been.calledWith 'some-flow-uuid'
it 'should call deploy on the nanocyte deployer', ->
expect(@nanocyteDeployer.deploy).to.have.been.called
it 'should call _createNanocyteDeployer', ->
expect(@_createNanocyteDeployer).to.have.been.calledWith
client: @sut.client
deploymentUuid: 'the-deployment-uuid'
flowUuid: 'some-flow-uuid'
instanceId: 'an-instance-uuid'
flowToken: 'PI:PASSWORD:<KEY>END_PI'
userUuid: 'the-user-uuid'
userToken: 'PI:PASSWORD:<PASSWORD>END_PI'
octobluUrl: 'http://yahho.com'
forwardUrl: 'https://genisys.com/flows/some-flow-uuid/instances/an-instance-uuid/messages'
flowLoggerUuid: 'flow-logger-uuid'
intervalServiceUri: 'http://interval.octoblu.dev'
describe 'and startFlow fails', ->
beforeEach ->
@nanocyteDeployer.startFlow.yield new Error 'something wrong'
it 'should respond with a 422', ->
expect(@response.status).to.have.been.calledWith 422
expect(@response.send).to.have.been.calledWith 'something wrong'
it 'should call startFlow on the nanocyte deployer', ->
expect(@nanocyteDeployer.startFlow).to.have.been.called
describe 'and startFlow succeeds', ->
beforeEach ->
@nanocyteDeployer.startFlow.yield null
it 'should call startFlow on the nanocyte deployer', ->
expect(@nanocyteDeployer.startFlow).to.have.been.called
it 'should respond with a 201', ->
expect(@response.status).to.have.been.calledWith 201
expect(@response.location).to.have.been.calledWith '/flows/some-flow-uuid/instances/an-instance-uuid'
expect(@response.end).to.have.been.called
describe 'when deploy is failure', ->
beforeEach ->
@meshbluHttp.generateAndStoreTokenWithOptions.yield null
@nanocyteDeployer.sendStopFlowMessage.yield null
@nanocyteDeployer.deploy.yield new Error 'something wrong'
it 'should respond with a 422', ->
expect(@response.status).to.have.been.calledWith 422
expect(@response.send).to.have.been.calledWith 'something wrong'
describe 'when /instances receives a different post message', ->
beforeEach ->
request =
get: sinon.stub().withArgs('deploymentUuid').returns('some-other-deployment-uuid')
params:
flowId: 'some-other-flow-uuid'
meshbluAuth:
uuid: 'the-user-uuid'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
@UUID.v4.returns 'an-instance-uuid'
@sut.create request, @response
describe 'when deploy is successful', ->
beforeEach ->
@meshbluHttp.generateAndStoreTokenWithOptions.yield null, token: 'PI:KEY:<KEY>END_PI-PI:PASSWORD:<PASSWORD>END_PI'
@nanocyteDeployer.sendStopFlowMessage.yield null
@nanocyteDeployer.deploy.yield null
@nanocyteDeployer.startFlow.yield null
it 'should call generateAndStoreTokenWithOptions', ->
expect(@meshbluHttp.generateAndStoreTokenWithOptions).to.have.been.calledWith 'some-other-flow-uuid'
it 'should call _createNanocyteDeployer', ->
expect(@_createNanocyteDeployer).to.have.been.calledWith
client: @sut.client
deploymentUuid: 'some-other-deployment-uuid'
flowUuid: 'some-other-flow-uuid'
instanceId: 'an-instance-uuid'
flowToken: 'PI:KEY:<KEY>END_PI-PI:PASSWORD:<PASSWORD>END_PI'
userUuid: 'the-user-uuid'
userToken: 'PI:PASSWORD:<PASSWORD>END_PI'
octobluUrl: 'http://yahho.com'
forwardUrl: 'https://genisys.com/flows/some-other-flow-uuid/instances/an-instance-uuid/messages'
flowLoggerUuid: 'flow-logger-uuid'
intervalServiceUri: 'http://interval.octoblu.dev'
it 'should respond with a 201', ->
expect(@response.status).to.have.been.calledWith 201
expect(@response.location).to.have.been.calledWith '/flows/some-other-flow-uuid/instances/an-instance-uuid'
expect(@response.end).to.have.been.called
it 'should call deploy on the nanocyte deployer', ->
expect(@nanocyteDeployer.deploy).to.have.been.called
describe 'when nanocyte deployer is given a new instance uuid with post', ->
beforeEach ->
request =
get: sinon.stub().withArgs('deploymentUuid').returns 'this-deployment-uuid'
params:
flowId: 'some-other-new-flow-uuid'
meshbluAuth:
uuid: 'the-user-uuid'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
@UUID.v4.returns 'a-new-instance-uuid'
@sut.create request, @response
describe 'when deploy is successful', ->
beforeEach ->
@meshbluHttp.generateAndStoreTokenWithOptions.yield null, token: 'PI:PASSWORD:<PASSWORD>END_PI'
@nanocyteDeployer.sendStopFlowMessage.yield null
@nanocyteDeployer.deploy.yield null
@nanocyteDeployer.startFlow.yield null
it 'should call _createNanocyteDeployer', ->
expect(@_createNanocyteDeployer).to.have.been.calledWith
client: @sut.client
deploymentUuid: 'this-deployment-uuid'
flowUuid: 'some-other-new-flow-uuid'
instanceId: 'a-new-instance-uuid'
flowToken: 'PI:PASSWORD:<PASSWORD>END_PI'
userUuid: 'the-user-uuid'
userToken: 'PI:PASSWORD:<PASSWORD>END_PI'
octobluUrl: 'http://yahho.com'
forwardUrl: 'https://genisys.com/flows/some-other-new-flow-uuid/instances/a-new-instance-uuid/messages'
flowLoggerUuid: 'flow-logger-uuid'
intervalServiceUri: 'http://interval.octoblu.dev'
it 'should respond with a 201', ->
expect(@response.status).to.have.been.calledWith 201
expect(@response.location).to.have.been.calledWith '/flows/some-other-new-flow-uuid/instances/a-new-instance-uuid'
expect(@response.end).to.have.been.called
it 'should call deploy on the nanocyte deployer', ->
expect(@nanocyteDeployer.deploy).to.have.been.called
describe 'when /instances receives a delete message', ->
beforeEach ->
request =
get: sinon.stub().withArgs('deploymentUuid').returns 'this-deployment-uuid'
params:
flowId: 'some-flow-uuid'
meshbluAuth:
uuid: 'awesome-user-uuid'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
@UUID.v4.returns 'an-instance-uuid'
@sut.destroy request, @response
describe 'when stopFlow is successful', ->
beforeEach ->
@meshbluHttp.generateAndStoreTokenWithOptions.yield null, token: 'cool-token-bro'
@nanocyteDeployer.stopFlow.yield null
it 'should call generateAndStoreTokenWithOptions', ->
expect(@meshbluHttp.generateAndStoreTokenWithOptions).to.have.been.calledWith 'some-flow-uuid'
it 'should call _createNanocyteDeployer', ->
expect(@_createNanocyteDeployer).to.have.been.calledWith
client: @sut.client
flowUuid: 'some-flow-uuid'
instanceId: 'an-instance-uuid'
flowToken: 'PI:PASSWORD:<PASSWORD>END_PI-PI:KEY:<KEY>END_PI-bro'
userUuid: 'awesome-user-uuid'
userToken: 'PI:PASSWORD:<PASSWORD>END_PI'
deploymentUuid: 'this-deployment-uuid'
octobluUrl: 'http://yahho.com'
forwardUrl: 'https://genisys.com/flows/some-flow-uuid/instances/an-instance-uuid/messages'
flowLoggerUuid: 'flow-logger-uuid'
intervalServiceUri: 'http://interval.octoblu.dev'
it 'should call nanocyteDeployer.stopFlow', ->
expect(@nanocyteDeployer.stopFlow).to.have.been.called
describe 'and nanocyteDeployer.destroy is a success', ->
beforeEach ->
@nanocyteDeployer.destroy.yield null
it 'should call nanocyteDeployer.destroy', ->
expect(@nanocyteDeployer.destroy).to.have.been.called
it 'should respond with a 204', ->
expect(@response.status).to.have.been.calledWith 204
expect(@response.end).to.have.been.called
describe 'and nanocyteDeployer.destroy is a failure', ->
beforeEach ->
@nanocyteDeployer.destroy.yield new Error "wrong things happened"
it 'should call nanocyteDeployer.destroy', ->
expect(@nanocyteDeployer.destroy).to.have.been.called
it 'should respond with a 422', ->
expect(@response.status).to.have.been.calledWith 422
expect(@response.send).to.have.been.calledWith "wrong things happened"
describe 'when stopFlow is failure', ->
beforeEach ->
@meshbluHttp.generateAndStoreTokenWithOptions.yield null, token: 'PI:PASSWORD:<KEY>END_PI'
@nanocyteDeployer.stopFlow.yield new Error "Oh no!"
it 'should call generateAndStoreTokenWithOptions', ->
expect(@meshbluHttp.generateAndStoreTokenWithOptions).to.have.been.calledWith 'some-flow-uuid'
it 'should call _createNanocyteDeployer', ->
expect(@_createNanocyteDeployer).to.have.been.calledWith
client: @sut.client
deploymentUuid: 'this-deployment-uuid'
flowUuid: 'some-flow-uuid'
instanceId: 'an-instance-uuid'
flowToken: 'PI:PASSWORD:<PASSWORD>END_PI-PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI-PI:KEY:<KEY>END_PI'
userUuid: 'awesome-user-uuid'
userToken: 'PI:PASSWORD:<PASSWORD>END_PI'
octobluUrl: 'http://yahho.com'
forwardUrl: 'https://genisys.com/flows/some-flow-uuid/instances/an-instance-uuid/messages'
flowLoggerUuid: 'flow-logger-uuid'
intervalServiceUri: 'http://interval.octoblu.dev'
it 'should respond with a 422 and Error', ->
expect(@response.status).to.have.been.calledWith 422
expect(@response.send).to.have.been.calledWith 'Oh no!'
it 'should call nanocyteDeployer.stopFlow', ->
expect(@nanocyteDeployer.stopFlow).to.have.been.called
|
[
{
"context": "# Copyright 2015, Christopher Joakim <christopher.joakim@gmail.com>\n\ndescribe 'AgeCalc",
"end": 36,
"score": 0.9998895525932312,
"start": 18,
"tag": "NAME",
"value": "Christopher Joakim"
},
{
"context": "# Copyright 2015, Christopher Joakim <christopher.joakim@gmail.c... | m26-js/test-src/m26_age_calculator_spec.coffee | cjoakim/oss | 0 | # Copyright 2015, Christopher Joakim <christopher.joakim@gmail.com>
describe 'AgeCalculator', ->
it "should define milliseconds_per_year", ->
expect(AgeCalculator.milliseconds_per_year()).toEqual(31557600000)
it "should calculate and construct and Age", ->
a1 = AgeCalculator.calculate('1960-10-01', '2014-10-01')
a2 = AgeCalculator.calculate('2013-11-01')
expect(a1.val()).isWithin(0.01, 54.0)
expect(a2.val()).toBeGreaterThan(0.999)
expect(a2.val()).toBeLessThan(2) # TODO - update before November 2015
| 83303 | # Copyright 2015, <NAME> <<EMAIL>>
describe 'AgeCalculator', ->
it "should define milliseconds_per_year", ->
expect(AgeCalculator.milliseconds_per_year()).toEqual(31557600000)
it "should calculate and construct and Age", ->
a1 = AgeCalculator.calculate('1960-10-01', '2014-10-01')
a2 = AgeCalculator.calculate('2013-11-01')
expect(a1.val()).isWithin(0.01, 54.0)
expect(a2.val()).toBeGreaterThan(0.999)
expect(a2.val()).toBeLessThan(2) # TODO - update before November 2015
| true | # Copyright 2015, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
describe 'AgeCalculator', ->
it "should define milliseconds_per_year", ->
expect(AgeCalculator.milliseconds_per_year()).toEqual(31557600000)
it "should calculate and construct and Age", ->
a1 = AgeCalculator.calculate('1960-10-01', '2014-10-01')
a2 = AgeCalculator.calculate('2013-11-01')
expect(a1.val()).isWithin(0.01, 54.0)
expect(a2.val()).toBeGreaterThan(0.999)
expect(a2.val()).toBeLessThan(2) # TODO - update before November 2015
|
[
{
"context": "ace, object)\", ->\n o = \n name: \"jim\"\n age: 18\n sayHello: ->\n\n ",
"end": 3881,
"score": 0.9987173676490784,
"start": 3878,
"tag": "NAME",
"value": "jim"
},
{
"context": " IMan = M.$interface(\n name: \... | test/interfaceSpec.coffee | zhongxingdou/mayjs | 0 | # encoding: utf-8
describe 'interface.js', ->
M = require("../may.js")
$is = M.$is
$hasProto = M.$hasProto
describe '#parseArguNames()', ->
it 'should parse function parameter names', ->
fn = (p1, p2, p3) ->
names = M.util.parseArguNames(fn)
names.should.have.property('length', 3)
names.should.containEql('p1')
names.should.containEql('p2')
names.should.containEql('p3')
fn2 = ->
names2 = M.util.parseArguNames(fn2)
names2.should.be.empty
describe "#$is(type, object)", ->
it "$is()检验值类型", ->
$is('string', '').should.be.true
$is(String, '').should.be.true
$is('string', 'abc').should.be.true
$is('number', 0).should.be.true
$is('number', 8).should.be.true
$is(Number, 8).should.be.true
$is('number', - 1).should.be.true
$is('number', - 1.3).should.be.true
$is('boolean', true).should.be.true
$is('boolean', false).should.be.true
$is(Boolean, false).should.be.true
$is(undefined, null).should.be.true
$is(null, undefined).should.be.true
$is('boolean', undefined).should.be.false
it "$isA()检验引用类型", ->
$is(Function, ->).should.be.true
$is(Object, ->).should.be.true
$is(Object, {}).should.be.true
$is(Date, new Date()).should.be.true
$is(RegExp, /abc/).should.be.true
$is(Array, []).should.be.true
$is(Object, []).should.be.true
it "$is()检验null", ->
$is(null, null).should.be.true
$is(null, undefined).should.be.true
$is(null, 8).should.be.false
$is(null, {}).should.be.false
it "$is()检验undefined", ->
$is('undefined', undefined).should.be.true
$is(undefined, undefined).should.be.true
$is('undefined', null).should.be.true
a = {};
$is('undefined', a.b).should.be.true
t = (a, b) ->
$is(undefined, b).should.be.true
t(8);
it "$hasProto()检验原型链", ->
A = ->
B = ->
B.prototype = new A();
$hasProto(B.prototype, new B()).should.be.true
C = ->
C.prototype = new B();
$hasProto(B.prototype, new C()).should.be.true
$hasProto(Array.prototype, []).should.be.true
it "$is(type, o1, o2, o3)", ->
$is('string', "", "a", "b").should.be.true
$is('string', "", "a", 8).should.be.false
describe "#$func(arguTypes, fn)", ->
it "should add property __argu__types__ to fn", ->
arguType = [String, Number]
fn = (name, age) ->
M.$func(arguType, fn)
fn.should.have.property("__argu_types__")
types = fn.__argu_types__
types[0].name.should.eql "name"
types[1].name.should.eql "age"
types[0].type.should.eql arguType[0]
types[1].type.should.eql arguType[1]
describe "#$interface(define, base)", ->
it "should return a new interface that prototype is Interface", ->
a = M.$interface({})
M.Interface.isPrototypeOf(a).should.be.true
it "should return a new object that prototype is given base", ->
base = M.$interface()
define =
t1 : String
t2 : Number
a = M.$interface(define, base)
base.isPrototypeOf(a).should.be.true
a.should.have.property "t1", define.t1
a.should.have.property "t2", define.t2
describe "#$support(interface, object)", ->
o =
name: "jim"
age: 18
sayHello: ->
IMan = M.$interface(
name: "string"
age: "number"
sayHello: "function"
)
it "should be true if object supported protocol", ->
M.$support(IMan, o).should.be.true
it "should be true if the object members count great more than interface members", ->
o.score = 90
M.$support(IMan, o).should.be.true
it "should throw error if object does not have required member", ->
IMan.height = "number"
(->
M.$support(IMan, o)).should.thrown
it "should pass and return true if object.__interfaces__ contains interface object", ->
a =
__interfaces__: [IMan]
M.$support(IMan, a).should.be.true
it "should support declare function member by array which contains parameters type info", ->
IA = M.$interface(
sayHello: ["string"]
)
a = { sayHello: -> }
M.$support(IA, a).should.be.true
it "should support any object as interface agaist a object which link to Interfact as prototype", ->
IA = { sayHello: "function"}
a = { sayHello: -> }
M.$support(IA, a).should.be.true
describe "$implement(interface, object)", ->
it "should add interface object to object.__interfaces__ if the object supported", ->
o = {}
IA = {}
M.$implement(IA, o)
o.__interfaces__.should.containEql IA
it "should throw error if object not supported interface", ->
o = {}
IA = {m: String}
(->
M.$implement(IA, o)
).should.throw
describe "$check(express)", ->
it "should throw error if express equals false", ->
(->
M.$check(false)).should.throw
it "should not throw error if express not equals false", ->
(->
M.$check(null)
M.$check("")
M.$check(true)
M.$check(undefined)
M.$check(0)).should.not.throw
describe "$checkArgu(Type1, Type2)", ->
fn = (name, age) ->
return M.$checkArgu("string", "number")
it "should return true when the arguments valid", ->
fn("jim", 18).should.be.true
it "should return false when the arguments invalid", ->
fn("jim", "18").should.be.false
it "should pass by any value when the check type is defined be undefined", ->
fn2 = (name, age) ->
return M.$checkArgu("string", undefined, "number")
fn2("jim", "xx", 18).should.be.true
fn2("jim", null, 19).should.be.true
| 72635 | # encoding: utf-8
describe 'interface.js', ->
M = require("../may.js")
$is = M.$is
$hasProto = M.$hasProto
describe '#parseArguNames()', ->
it 'should parse function parameter names', ->
fn = (p1, p2, p3) ->
names = M.util.parseArguNames(fn)
names.should.have.property('length', 3)
names.should.containEql('p1')
names.should.containEql('p2')
names.should.containEql('p3')
fn2 = ->
names2 = M.util.parseArguNames(fn2)
names2.should.be.empty
describe "#$is(type, object)", ->
it "$is()检验值类型", ->
$is('string', '').should.be.true
$is(String, '').should.be.true
$is('string', 'abc').should.be.true
$is('number', 0).should.be.true
$is('number', 8).should.be.true
$is(Number, 8).should.be.true
$is('number', - 1).should.be.true
$is('number', - 1.3).should.be.true
$is('boolean', true).should.be.true
$is('boolean', false).should.be.true
$is(Boolean, false).should.be.true
$is(undefined, null).should.be.true
$is(null, undefined).should.be.true
$is('boolean', undefined).should.be.false
it "$isA()检验引用类型", ->
$is(Function, ->).should.be.true
$is(Object, ->).should.be.true
$is(Object, {}).should.be.true
$is(Date, new Date()).should.be.true
$is(RegExp, /abc/).should.be.true
$is(Array, []).should.be.true
$is(Object, []).should.be.true
it "$is()检验null", ->
$is(null, null).should.be.true
$is(null, undefined).should.be.true
$is(null, 8).should.be.false
$is(null, {}).should.be.false
it "$is()检验undefined", ->
$is('undefined', undefined).should.be.true
$is(undefined, undefined).should.be.true
$is('undefined', null).should.be.true
a = {};
$is('undefined', a.b).should.be.true
t = (a, b) ->
$is(undefined, b).should.be.true
t(8);
it "$hasProto()检验原型链", ->
A = ->
B = ->
B.prototype = new A();
$hasProto(B.prototype, new B()).should.be.true
C = ->
C.prototype = new B();
$hasProto(B.prototype, new C()).should.be.true
$hasProto(Array.prototype, []).should.be.true
it "$is(type, o1, o2, o3)", ->
$is('string', "", "a", "b").should.be.true
$is('string', "", "a", 8).should.be.false
describe "#$func(arguTypes, fn)", ->
it "should add property __argu__types__ to fn", ->
arguType = [String, Number]
fn = (name, age) ->
M.$func(arguType, fn)
fn.should.have.property("__argu_types__")
types = fn.__argu_types__
types[0].name.should.eql "name"
types[1].name.should.eql "age"
types[0].type.should.eql arguType[0]
types[1].type.should.eql arguType[1]
describe "#$interface(define, base)", ->
it "should return a new interface that prototype is Interface", ->
a = M.$interface({})
M.Interface.isPrototypeOf(a).should.be.true
it "should return a new object that prototype is given base", ->
base = M.$interface()
define =
t1 : String
t2 : Number
a = M.$interface(define, base)
base.isPrototypeOf(a).should.be.true
a.should.have.property "t1", define.t1
a.should.have.property "t2", define.t2
describe "#$support(interface, object)", ->
o =
name: "<NAME>"
age: 18
sayHello: ->
IMan = M.$interface(
name: "<NAME>"
age: "number"
sayHello: "function"
)
it "should be true if object supported protocol", ->
M.$support(IMan, o).should.be.true
it "should be true if the object members count great more than interface members", ->
o.score = 90
M.$support(IMan, o).should.be.true
it "should throw error if object does not have required member", ->
IMan.height = "number"
(->
M.$support(IMan, o)).should.thrown
it "should pass and return true if object.__interfaces__ contains interface object", ->
a =
__interfaces__: [IMan]
M.$support(IMan, a).should.be.true
it "should support declare function member by array which contains parameters type info", ->
IA = M.$interface(
sayHello: ["string"]
)
a = { sayHello: -> }
M.$support(IA, a).should.be.true
it "should support any object as interface agaist a object which link to Interfact as prototype", ->
IA = { sayHello: "function"}
a = { sayHello: -> }
M.$support(IA, a).should.be.true
describe "$implement(interface, object)", ->
it "should add interface object to object.__interfaces__ if the object supported", ->
o = {}
IA = {}
M.$implement(IA, o)
o.__interfaces__.should.containEql IA
it "should throw error if object not supported interface", ->
o = {}
IA = {m: String}
(->
M.$implement(IA, o)
).should.throw
describe "$check(express)", ->
it "should throw error if express equals false", ->
(->
M.$check(false)).should.throw
it "should not throw error if express not equals false", ->
(->
M.$check(null)
M.$check("")
M.$check(true)
M.$check(undefined)
M.$check(0)).should.not.throw
describe "$checkArgu(Type1, Type2)", ->
fn = (name, age) ->
return M.$checkArgu("string", "number")
it "should return true when the arguments valid", ->
fn("jim", 18).should.be.true
it "should return false when the arguments invalid", ->
fn("jim", "18").should.be.false
it "should pass by any value when the check type is defined be undefined", ->
fn2 = (name, age) ->
return M.$checkArgu("string", undefined, "number")
fn2("jim", "xx", 18).should.be.true
fn2("jim", null, 19).should.be.true
| true | # encoding: utf-8
describe 'interface.js', ->
M = require("../may.js")
$is = M.$is
$hasProto = M.$hasProto
describe '#parseArguNames()', ->
it 'should parse function parameter names', ->
fn = (p1, p2, p3) ->
names = M.util.parseArguNames(fn)
names.should.have.property('length', 3)
names.should.containEql('p1')
names.should.containEql('p2')
names.should.containEql('p3')
fn2 = ->
names2 = M.util.parseArguNames(fn2)
names2.should.be.empty
describe "#$is(type, object)", ->
it "$is()检验值类型", ->
$is('string', '').should.be.true
$is(String, '').should.be.true
$is('string', 'abc').should.be.true
$is('number', 0).should.be.true
$is('number', 8).should.be.true
$is(Number, 8).should.be.true
$is('number', - 1).should.be.true
$is('number', - 1.3).should.be.true
$is('boolean', true).should.be.true
$is('boolean', false).should.be.true
$is(Boolean, false).should.be.true
$is(undefined, null).should.be.true
$is(null, undefined).should.be.true
$is('boolean', undefined).should.be.false
it "$isA()检验引用类型", ->
$is(Function, ->).should.be.true
$is(Object, ->).should.be.true
$is(Object, {}).should.be.true
$is(Date, new Date()).should.be.true
$is(RegExp, /abc/).should.be.true
$is(Array, []).should.be.true
$is(Object, []).should.be.true
it "$is()检验null", ->
$is(null, null).should.be.true
$is(null, undefined).should.be.true
$is(null, 8).should.be.false
$is(null, {}).should.be.false
it "$is()检验undefined", ->
$is('undefined', undefined).should.be.true
$is(undefined, undefined).should.be.true
$is('undefined', null).should.be.true
a = {};
$is('undefined', a.b).should.be.true
t = (a, b) ->
$is(undefined, b).should.be.true
t(8);
it "$hasProto()检验原型链", ->
A = ->
B = ->
B.prototype = new A();
$hasProto(B.prototype, new B()).should.be.true
C = ->
C.prototype = new B();
$hasProto(B.prototype, new C()).should.be.true
$hasProto(Array.prototype, []).should.be.true
it "$is(type, o1, o2, o3)", ->
$is('string', "", "a", "b").should.be.true
$is('string', "", "a", 8).should.be.false
describe "#$func(arguTypes, fn)", ->
it "should add property __argu__types__ to fn", ->
arguType = [String, Number]
fn = (name, age) ->
M.$func(arguType, fn)
fn.should.have.property("__argu_types__")
types = fn.__argu_types__
types[0].name.should.eql "name"
types[1].name.should.eql "age"
types[0].type.should.eql arguType[0]
types[1].type.should.eql arguType[1]
describe "#$interface(define, base)", ->
it "should return a new interface that prototype is Interface", ->
a = M.$interface({})
M.Interface.isPrototypeOf(a).should.be.true
it "should return a new object that prototype is given base", ->
base = M.$interface()
define =
t1 : String
t2 : Number
a = M.$interface(define, base)
base.isPrototypeOf(a).should.be.true
a.should.have.property "t1", define.t1
a.should.have.property "t2", define.t2
describe "#$support(interface, object)", ->
o =
name: "PI:NAME:<NAME>END_PI"
age: 18
sayHello: ->
IMan = M.$interface(
name: "PI:NAME:<NAME>END_PI"
age: "number"
sayHello: "function"
)
it "should be true if object supported protocol", ->
M.$support(IMan, o).should.be.true
it "should be true if the object members count great more than interface members", ->
o.score = 90
M.$support(IMan, o).should.be.true
it "should throw error if object does not have required member", ->
IMan.height = "number"
(->
M.$support(IMan, o)).should.thrown
it "should pass and return true if object.__interfaces__ contains interface object", ->
a =
__interfaces__: [IMan]
M.$support(IMan, a).should.be.true
it "should support declare function member by array which contains parameters type info", ->
IA = M.$interface(
sayHello: ["string"]
)
a = { sayHello: -> }
M.$support(IA, a).should.be.true
it "should support any object as interface agaist a object which link to Interfact as prototype", ->
IA = { sayHello: "function"}
a = { sayHello: -> }
M.$support(IA, a).should.be.true
describe "$implement(interface, object)", ->
it "should add interface object to object.__interfaces__ if the object supported", ->
o = {}
IA = {}
M.$implement(IA, o)
o.__interfaces__.should.containEql IA
it "should throw error if object not supported interface", ->
o = {}
IA = {m: String}
(->
M.$implement(IA, o)
).should.throw
describe "$check(express)", ->
it "should throw error if express equals false", ->
(->
M.$check(false)).should.throw
it "should not throw error if express not equals false", ->
(->
M.$check(null)
M.$check("")
M.$check(true)
M.$check(undefined)
M.$check(0)).should.not.throw
describe "$checkArgu(Type1, Type2)", ->
fn = (name, age) ->
return M.$checkArgu("string", "number")
it "should return true when the arguments valid", ->
fn("jim", 18).should.be.true
it "should return false when the arguments invalid", ->
fn("jim", "18").should.be.false
it "should pass by any value when the check type is defined be undefined", ->
fn2 = (name, age) ->
return M.$checkArgu("string", undefined, "number")
fn2("jim", "xx", 18).should.be.true
fn2("jim", null, 19).should.be.true
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999135732650757,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/_classes/tooltip-beatmap.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.
class @TooltipBeatmap
tmpl: _.template '<div class="tooltip-beatmap__text tooltip-beatmap__text--title"><%- beatmapTitle %></div>' +
'<div class="tooltip-beatmap__text tooltip-beatmap__text--<%- difficulty %>"><%- stars %> <i class="fas fa-star" aria-hidden="true"></i></div>'
constructor: ->
$(document).on 'mouseover touchstart', '.js-beatmap-tooltip', @onMouseOver
onMouseOver: (event) =>
el = event.currentTarget
return if !el.dataset.beatmapTitle?
content = @tmpl el.dataset
if el._tooltip
$(el).qtip 'set', 'content.text': content
return
at = el.dataset.tooltipPosition ? 'top center'
my = switch at
when 'top center' then 'bottom center'
when 'left center' then 'right center'
when 'right center' then 'left center'
options =
overwrite: false
content: content
position:
my: my
at: at
viewport: $(window)
show:
event: event.type
ready: true
hide:
event: 'click mouseleave'
style:
classes: 'qtip tooltip-beatmap'
tip:
width: 10
height: 9
if event.type == 'touchstart'
options.hide = inactive: 3000
$(el).qtip options, event
el._tooltip = true
| 128644 | # 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.
class @TooltipBeatmap
tmpl: _.template '<div class="tooltip-beatmap__text tooltip-beatmap__text--title"><%- beatmapTitle %></div>' +
'<div class="tooltip-beatmap__text tooltip-beatmap__text--<%- difficulty %>"><%- stars %> <i class="fas fa-star" aria-hidden="true"></i></div>'
constructor: ->
$(document).on 'mouseover touchstart', '.js-beatmap-tooltip', @onMouseOver
onMouseOver: (event) =>
el = event.currentTarget
return if !el.dataset.beatmapTitle?
content = @tmpl el.dataset
if el._tooltip
$(el).qtip 'set', 'content.text': content
return
at = el.dataset.tooltipPosition ? 'top center'
my = switch at
when 'top center' then 'bottom center'
when 'left center' then 'right center'
when 'right center' then 'left center'
options =
overwrite: false
content: content
position:
my: my
at: at
viewport: $(window)
show:
event: event.type
ready: true
hide:
event: 'click mouseleave'
style:
classes: 'qtip tooltip-beatmap'
tip:
width: 10
height: 9
if event.type == 'touchstart'
options.hide = inactive: 3000
$(el).qtip options, event
el._tooltip = true
| 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.
class @TooltipBeatmap
tmpl: _.template '<div class="tooltip-beatmap__text tooltip-beatmap__text--title"><%- beatmapTitle %></div>' +
'<div class="tooltip-beatmap__text tooltip-beatmap__text--<%- difficulty %>"><%- stars %> <i class="fas fa-star" aria-hidden="true"></i></div>'
constructor: ->
$(document).on 'mouseover touchstart', '.js-beatmap-tooltip', @onMouseOver
onMouseOver: (event) =>
el = event.currentTarget
return if !el.dataset.beatmapTitle?
content = @tmpl el.dataset
if el._tooltip
$(el).qtip 'set', 'content.text': content
return
at = el.dataset.tooltipPosition ? 'top center'
my = switch at
when 'top center' then 'bottom center'
when 'left center' then 'right center'
when 'right center' then 'left center'
options =
overwrite: false
content: content
position:
my: my
at: at
viewport: $(window)
show:
event: event.type
ready: true
hide:
event: 'click mouseleave'
style:
classes: 'qtip tooltip-beatmap'
tip:
width: 10
height: 9
if event.type == 'touchstart'
options.hide = inactive: 3000
$(el).qtip options, event
el._tooltip = true
|
[
{
"context": "->\n service = new AWS.MetadataService(host: '127.0.0.1:' + port)\n server = http.createServer (req, ",
"end": 889,
"score": 0.9995419979095459,
"start": 880,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " data = '{\"Code\":\"Success\",\"A... | node_modules/grunt-aws-s3/node_modules/aws-sdk/test/metadata_service.spec.coffee | uqlibrary/summonhacks | 2 | # Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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.
helpers = require('./helpers')
url = require('url')
http = require('http')
AWS = helpers.AWS
describe 'AWS.MetadataService', ->
describe 'loadCredentials', ->
[server, port, service] = [null, 1024 + parseInt(Math.random() * 100), null]
beforeEach ->
service = new AWS.MetadataService(host: '127.0.0.1:' + port)
server = http.createServer (req, res) ->
re = new RegExp('^/latest/meta-data/iam/security-credentials/(.*)$')
match = url.parse(req.url).pathname.match(re)
if match
res.writeHead(200, 'Content-Type': 'text/plain')
if match[1] == ''
res.write('TestingRole\n')
res.write('TestingRole2\n')
else
data = '{"Code":"Success","AccessKeyId":"KEY","SecretAccessKey":"SECRET","Token":"TOKEN"}'
res.write(data)
else
res.writeHead(404, {})
res.end()
server.listen(port)
afterEach -> server.close() if server
it 'should load credentials from metadata service', ->
[err, data] = [null, null]
runs ->
service.loadCredentials (e, d) -> [err, data] = [e, d]
waitsFor -> err || data
runs ->
expect(err).toBe(null)
expect(data.Code).toEqual('Success')
expect(data.AccessKeyId).toEqual('KEY')
expect(data.SecretAccessKey).toEqual('SECRET')
expect(data.Token).toEqual('TOKEN')
it 'should fail if server is not up', ->
server.close(); server = null
service = new AWS.MetadataService(host: '255.255.255.255')
service.httpOptions.timeout = 10
[err, data] = [null, null]
runs ->
service.loadCredentials (e, d) -> [err, data] = [e, d]
waitsFor -> err || data
runs ->
expect(err instanceof Error).toBe(true)
expect(data).toEqual(null)
| 115406 | # Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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.
helpers = require('./helpers')
url = require('url')
http = require('http')
AWS = helpers.AWS
describe 'AWS.MetadataService', ->
describe 'loadCredentials', ->
[server, port, service] = [null, 1024 + parseInt(Math.random() * 100), null]
beforeEach ->
service = new AWS.MetadataService(host: '127.0.0.1:' + port)
server = http.createServer (req, res) ->
re = new RegExp('^/latest/meta-data/iam/security-credentials/(.*)$')
match = url.parse(req.url).pathname.match(re)
if match
res.writeHead(200, 'Content-Type': 'text/plain')
if match[1] == ''
res.write('TestingRole\n')
res.write('TestingRole2\n')
else
data = '{"Code":"Success","AccessKeyId":"<KEY>","SecretAccessKey":"<KEY>","Token":"<KEY>"}'
res.write(data)
else
res.writeHead(404, {})
res.end()
server.listen(port)
afterEach -> server.close() if server
it 'should load credentials from metadata service', ->
[err, data] = [null, null]
runs ->
service.loadCredentials (e, d) -> [err, data] = [e, d]
waitsFor -> err || data
runs ->
expect(err).toBe(null)
expect(data.Code).toEqual('Success')
expect(data.AccessKeyId).toEqual('KEY')
expect(data.SecretAccessKey).toEqual('SECRET')
expect(data.Token).toEqual('TOKEN')
it 'should fail if server is not up', ->
server.close(); server = null
service = new AWS.MetadataService(host: '255.255.255.255')
service.httpOptions.timeout = 10
[err, data] = [null, null]
runs ->
service.loadCredentials (e, d) -> [err, data] = [e, d]
waitsFor -> err || data
runs ->
expect(err instanceof Error).toBe(true)
expect(data).toEqual(null)
| true | # Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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.
helpers = require('./helpers')
url = require('url')
http = require('http')
AWS = helpers.AWS
describe 'AWS.MetadataService', ->
describe 'loadCredentials', ->
[server, port, service] = [null, 1024 + parseInt(Math.random() * 100), null]
beforeEach ->
service = new AWS.MetadataService(host: '127.0.0.1:' + port)
server = http.createServer (req, res) ->
re = new RegExp('^/latest/meta-data/iam/security-credentials/(.*)$')
match = url.parse(req.url).pathname.match(re)
if match
res.writeHead(200, 'Content-Type': 'text/plain')
if match[1] == ''
res.write('TestingRole\n')
res.write('TestingRole2\n')
else
data = '{"Code":"Success","AccessKeyId":"PI:KEY:<KEY>END_PI","SecretAccessKey":"PI:KEY:<KEY>END_PI","Token":"PI:KEY:<KEY>END_PI"}'
res.write(data)
else
res.writeHead(404, {})
res.end()
server.listen(port)
afterEach -> server.close() if server
it 'should load credentials from metadata service', ->
[err, data] = [null, null]
runs ->
service.loadCredentials (e, d) -> [err, data] = [e, d]
waitsFor -> err || data
runs ->
expect(err).toBe(null)
expect(data.Code).toEqual('Success')
expect(data.AccessKeyId).toEqual('KEY')
expect(data.SecretAccessKey).toEqual('SECRET')
expect(data.Token).toEqual('TOKEN')
it 'should fail if server is not up', ->
server.close(); server = null
service = new AWS.MetadataService(host: '255.255.255.255')
service.httpOptions.timeout = 10
[err, data] = [null, null]
runs ->
service.loadCredentials (e, d) -> [err, data] = [e, d]
waitsFor -> err || data
runs ->
expect(err instanceof Error).toBe(true)
expect(data).toEqual(null)
|
[
{
"context": "n systems', ->\n systems = [\n { name: 'ОСН' }\n { name: 'УСН' }\n ]\n expect(",
"end": 586,
"score": 0.7957721948623657,
"start": 584,
"tag": "NAME",
"value": "ОС"
},
{
"context": "tems = [\n { name: 'ОСН' }\n { name: 'УСН' }\... | src/Vifeed/FrontendBundle/Tests/unit/advertiser/resources/companies.spec.coffee | bzis/zomba | 0 | describe 'Companies', ->
beforeEach( -> module 'resources.companies' )
describe 'Resource', ->
companies = {}
$httpBackend = {}
mock = {}
expect = chai.expect
beforeEach(inject (_$httpBackend_, Companies) ->
$httpBackend = _$httpBackend_
companies = Companies
mock = new CompaniesMock($httpBackend)
# mock.mockOkResponse()
)
it 'should have default resource url', ->
expect(companies.resourceUrl).to.equal '/api/users/current/company'
it 'should return all taxation systems', ->
systems = [
{ name: 'ОСН' }
{ name: 'УСН' }
]
expect(companies.getTaxationSystems()).to.eql systems
it 'should return an empty company if new() method called', ->
company =
system:
name: 'ОСН'
name: ''
address: ''
inn: ''
kpp: ''
bic: ''
bankAccount: ''
correspondentAccount: ''
contactName: ''
position: ''
phone: ''
isApproved: false
expect(companies.new()).to.eql company
it 'should return empty response when no companies', ->
mock.mockNoCompanyResponse()
reply = null
companies.getCurrent().then (response) -> reply = response
$httpBackend.flush()
expect(reply).to.eql ''
it 'should return empty response when getCurrentOrNew() method called and no companies', ->
company =
system:
name: 'ОСН'
name: ''
address: ''
inn: ''
kpp: ''
bic: ''
bankAccount: ''
correspondentAccount: ''
contactName: ''
position: ''
phone: ''
isApproved: false
mock.mockNoCompanyResponse()
reply = null
companies.getCurrentOrNew().then (response) -> reply = response
$httpBackend.flush()
expect(reply).to.eql company
| 127643 | describe 'Companies', ->
beforeEach( -> module 'resources.companies' )
describe 'Resource', ->
companies = {}
$httpBackend = {}
mock = {}
expect = chai.expect
beforeEach(inject (_$httpBackend_, Companies) ->
$httpBackend = _$httpBackend_
companies = Companies
mock = new CompaniesMock($httpBackend)
# mock.mockOkResponse()
)
it 'should have default resource url', ->
expect(companies.resourceUrl).to.equal '/api/users/current/company'
it 'should return all taxation systems', ->
systems = [
{ name: '<NAME>Н' }
{ name: '<NAME>СН' }
]
expect(companies.getTaxationSystems()).to.eql systems
it 'should return an empty company if new() method called', ->
company =
system:
name: '<NAME>'
name: ''
address: ''
inn: ''
kpp: ''
bic: ''
bankAccount: ''
correspondentAccount: ''
contactName: ''
position: ''
phone: ''
isApproved: false
expect(companies.new()).to.eql company
it 'should return empty response when no companies', ->
mock.mockNoCompanyResponse()
reply = null
companies.getCurrent().then (response) -> reply = response
$httpBackend.flush()
expect(reply).to.eql ''
it 'should return empty response when getCurrentOrNew() method called and no companies', ->
company =
system:
name: '<NAME>'
name: ''
address: ''
inn: ''
kpp: ''
bic: ''
bankAccount: ''
correspondentAccount: ''
contactName: ''
position: ''
phone: ''
isApproved: false
mock.mockNoCompanyResponse()
reply = null
companies.getCurrentOrNew().then (response) -> reply = response
$httpBackend.flush()
expect(reply).to.eql company
| true | describe 'Companies', ->
beforeEach( -> module 'resources.companies' )
describe 'Resource', ->
companies = {}
$httpBackend = {}
mock = {}
expect = chai.expect
beforeEach(inject (_$httpBackend_, Companies) ->
$httpBackend = _$httpBackend_
companies = Companies
mock = new CompaniesMock($httpBackend)
# mock.mockOkResponse()
)
it 'should have default resource url', ->
expect(companies.resourceUrl).to.equal '/api/users/current/company'
it 'should return all taxation systems', ->
systems = [
{ name: 'PI:NAME:<NAME>END_PIН' }
{ name: 'PI:NAME:<NAME>END_PIСН' }
]
expect(companies.getTaxationSystems()).to.eql systems
it 'should return an empty company if new() method called', ->
company =
system:
name: 'PI:NAME:<NAME>END_PI'
name: ''
address: ''
inn: ''
kpp: ''
bic: ''
bankAccount: ''
correspondentAccount: ''
contactName: ''
position: ''
phone: ''
isApproved: false
expect(companies.new()).to.eql company
it 'should return empty response when no companies', ->
mock.mockNoCompanyResponse()
reply = null
companies.getCurrent().then (response) -> reply = response
$httpBackend.flush()
expect(reply).to.eql ''
it 'should return empty response when getCurrentOrNew() method called and no companies', ->
company =
system:
name: 'PI:NAME:<NAME>END_PI'
name: ''
address: ''
inn: ''
kpp: ''
bic: ''
bankAccount: ''
correspondentAccount: ''
contactName: ''
position: ''
phone: ''
isApproved: false
mock.mockNoCompanyResponse()
reply = null
companies.getCurrentOrNew().then (response) -> reply = response
$httpBackend.flush()
expect(reply).to.eql company
|
[
{
"context": "re is licensed under the MIT License.\n\n Copyright Fedor Indutny, 2011.\n\n Permission is hereby granted, free of c",
"end": 125,
"score": 0.9995514154434204,
"start": 112,
"tag": "NAME",
"value": "Fedor Indutny"
}
] | node_modules/index/lib/index/utils.coffee | beshrkayali/monkey-release-action | 12 | ###
Various utilities for Node index library
This software is licensed under the MIT License.
Copyright Fedor Indutny, 2011.
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.
###
crypto = require 'crypto'
utils = exports
###
Merge two objects
###
merge = utils.merge = (a, b) ->
unless a and b
return a or b or {}
c = {}
for k,v of a
unless a.hasOwnProperty k
continue
c[k] = v
for k, v of b
unless b.hasOwnProperty k
continue
c[k] = if typeof c[k] is 'object'
merge c[k], v
else
v
c
###
Perform a binary search in following array
[[key, value], [key, value], ...]
@return value or undefined.
###
utils.search = (index, sort, key) ->
len = index.length - 1
i = len
while i >= 0 and sort(index[i][0], key) > 0
i--
if i == len and len >= 0 and sort(index[i][0], key) == 0
null
if i < 0
null
else
i
###
Hash function wrapper
###
utils.hash = (data) ->
hash = crypto.createHash 'md5'
hash.update data
hash.digest 'hex'
utils.hash.len = 32
| 10721 | ###
Various utilities for Node index library
This software is licensed under the MIT License.
Copyright <NAME>, 2011.
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.
###
crypto = require 'crypto'
utils = exports
###
Merge two objects
###
merge = utils.merge = (a, b) ->
unless a and b
return a or b or {}
c = {}
for k,v of a
unless a.hasOwnProperty k
continue
c[k] = v
for k, v of b
unless b.hasOwnProperty k
continue
c[k] = if typeof c[k] is 'object'
merge c[k], v
else
v
c
###
Perform a binary search in following array
[[key, value], [key, value], ...]
@return value or undefined.
###
utils.search = (index, sort, key) ->
len = index.length - 1
i = len
while i >= 0 and sort(index[i][0], key) > 0
i--
if i == len and len >= 0 and sort(index[i][0], key) == 0
null
if i < 0
null
else
i
###
Hash function wrapper
###
utils.hash = (data) ->
hash = crypto.createHash 'md5'
hash.update data
hash.digest 'hex'
utils.hash.len = 32
| true | ###
Various utilities for Node index library
This software is licensed under the MIT License.
Copyright PI:NAME:<NAME>END_PI, 2011.
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.
###
crypto = require 'crypto'
utils = exports
###
Merge two objects
###
merge = utils.merge = (a, b) ->
unless a and b
return a or b or {}
c = {}
for k,v of a
unless a.hasOwnProperty k
continue
c[k] = v
for k, v of b
unless b.hasOwnProperty k
continue
c[k] = if typeof c[k] is 'object'
merge c[k], v
else
v
c
###
Perform a binary search in following array
[[key, value], [key, value], ...]
@return value or undefined.
###
utils.search = (index, sort, key) ->
len = index.length - 1
i = len
while i >= 0 and sort(index[i][0], key) > 0
i--
if i == len and len >= 0 and sort(index[i][0], key) == 0
null
if i < 0
null
else
i
###
Hash function wrapper
###
utils.hash = (data) ->
hash = crypto.createHash 'md5'
hash.update data
hash.digest 'hex'
utils.hash.len = 32
|
[
{
"context": "= require \"../lib/config\"\n\ngapi.server.setApiKey \"AIzaSyB14Ua7k5_wusxHTQEH3sqmglO7MHjHPCI\"\n\ndescribe \"calling load with 'plus' and 'v1'\", -",
"end": 122,
"score": 0.9997539520263672,
"start": 83,
"tag": "KEY",
"value": "AIzaSyB14Ua7k5_wusxHTQEH3sqmglO7MHjHPCI"
}
] | static/node_modules/gapi/test/plus.v1.coffee | nohharri/chator | 4 | gapi = require "../index"
config = require "../lib/config"
gapi.server.setApiKey "AIzaSyB14Ua7k5_wusxHTQEH3sqmglO7MHjHPCI"
describe "calling load with 'plus' and 'v1'", ->
it "should add plus namespace to gapi.server", ->
gapi.server.load "plus", "v1", ->
gapi.server.should.have.property "plus"
describe "plus namespace", ->
it "should contain activities", ->
gapi.server.plus.should.have.property "activities"
it "should contain comments", ->
gapi.server.plus.should.have.property "comments"
it "should contain people", ->
gapi.server.plus.should.have.property "people" | 43866 | gapi = require "../index"
config = require "../lib/config"
gapi.server.setApiKey "<KEY>"
describe "calling load with 'plus' and 'v1'", ->
it "should add plus namespace to gapi.server", ->
gapi.server.load "plus", "v1", ->
gapi.server.should.have.property "plus"
describe "plus namespace", ->
it "should contain activities", ->
gapi.server.plus.should.have.property "activities"
it "should contain comments", ->
gapi.server.plus.should.have.property "comments"
it "should contain people", ->
gapi.server.plus.should.have.property "people" | true | gapi = require "../index"
config = require "../lib/config"
gapi.server.setApiKey "PI:KEY:<KEY>END_PI"
describe "calling load with 'plus' and 'v1'", ->
it "should add plus namespace to gapi.server", ->
gapi.server.load "plus", "v1", ->
gapi.server.should.have.property "plus"
describe "plus namespace", ->
it "should contain activities", ->
gapi.server.plus.should.have.property "activities"
it "should contain comments", ->
gapi.server.plus.should.have.property "comments"
it "should contain people", ->
gapi.server.plus.should.have.property "people" |
[
{
"context": " = class Alarm\n getAttendeesEmail: -> return ['test@cozycloud.cc']\nEvent = class Event\n @dateFormat = 'YYYY-MM-",
"end": 326,
"score": 0.9999302625656128,
"start": 309,
"tag": "EMAIL",
"value": "test@cozycloud.cc"
},
{
"context": "000\n ATTENDEE;PARTSTAT... | test/decorator.coffee | RubenVerborgh/cozy-ical | 25 | path = require 'path'
should = require 'should'
moment = require 'moment-timezone'
{RRule} = require 'rrule'
{ICalParser, VCalendar, VAlarm, VTodo, VEvent} = require '../src/index'
{decorateAlarm, decorateEvent} = require '../src/index'
# mock classes
Alarm = class Alarm
getAttendeesEmail: -> return ['test@cozycloud.cc']
Event = class Event
@dateFormat = 'YYYY-MM-DD'
@ambiguousDTFormat = 'YYYY-MM-DD[T]HH:mm:00.000'
@utcDTFormat = 'YYYY-MM-DD[T]HH:mm:00.000[Z]'
describe "Cozy models decorator", ->
globalSource = """
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Cozy Cloud//NONSGML Cozy Agenda//EN
BEGIN:VEVENT
UID:aeba6310b07a22a72423b2b11f320692
DTSTAMP:20141107T153700Z
DTSTART;TZID=Europe/Paris:20141106T120000
DTEND;TZID=Europe/Paris:20141106T130000
ATTENDEE;PARTSTAT=NEEDS-ACTION:mailto:test@cozycloud.cc
DESCRIPTION:Crawling a hidden dungeon
LOCATION:Hidden dungeon
RRULE:FREQ=WEEKLY;INTERVAL=1;UNTIL=20150101T000000Z;BYDAY=TH
SUMMARY:Recurring event
END:VEVENT
BEGIN:VTODO
UID:aeba6310b07a22a72423b2b11f320693
SUMMARY:Something to remind
DTSTART:20141108T150000Z
DTSTAMP:20141108T150000Z
BEGIN:VALARM
ACTION:EMAIL
ATTENDEE:mailto:test@cozycloud.cc
TRIGGER:PT0M
DESCRIPTION:Something to remind
END:VALARM
END:VTODO
END:VCALENDAR
"""
describe "Event", ->
it "decorating shouldn't trigger an error", ->
decorateEvent.bind(null, Event).should.not.throw()
it "::extractEvents should retrieve all the events from the source", (done) ->
new ICalParser().parseString globalSource, (err, comp) =>
should.not.exist err
@events = Event.extractEvents comp
should.exist @events
@events.length.should.equal 1
done()
it "::fromIcal should generate a proper Cozy Event", ->
# events comes from extractEvents, that uses fromIcal under the hood
event = @events[0]
should.exist event
event.should.have.property 'uid', 'aeba6310b07a22a72423b2b11f320692'
event.should.have.property 'description', 'Recurring event'
event.should.have.property 'start', '2014-11-06T12:00:00.000'
event.should.have.property 'end', '2014-11-06T13:00:00.000'
event.should.have.property 'place', 'Hidden dungeon'
event.should.have.property 'details', 'Crawling a hidden dungeon'
event.should.have.property 'rrule', 'FREQ=WEEKLY;INTERVAL=1;UNTIL=20150101T000000Z;BYDAY=TH'
event.should.have.property 'alarms', []
event.should.have.property 'timezone', 'Europe/Paris'
event.should.have.property 'tags', ['my calendar']
event.should.have.property 'lastModification', '2014-11-07T15:37:00.000Z'
event.should.have.property 'attendees'
event.attendees.length.should.equal 1
event.attendees[0].should.have.property 'email', 'test@cozycloud.cc'
event.attendees[0].should.have.property 'status', 'INVITATION-NOT-SENT'
it "::toIcal should generate a proper vEvent based on Cozy Event", ->
event = @events[0]
should.exist event
vEvent = event.toIcal()
vEvent.toString().should.equal """
BEGIN:VEVENT
UID:aeba6310b07a22a72423b2b11f320692
DTSTAMP:20141107T153700Z
DTSTART;TZID=Europe/Paris:20141106T120000
DTEND;TZID=Europe/Paris:20141106T130000
ATTENDEE;PARTSTAT=NEEDS-ACTION;CN=test@cozycloud.cc:mailto:test@cozycloud.cc
DESCRIPTION:Crawling a hidden dungeon
LAST-MODIFIED:20141107T153700Z
LOCATION:Hidden dungeon
RRULE:FREQ=WEEKLY;INTERVAL=1;UNTIL=20150101T000000Z;BYDAY=TH
SUMMARY:Recurring event
END:VEVENT
""".replace /\n/g, '\r\n'
describe "Specific cases", ->
it 'should generate identical ical as source', ->
new ICalParser().parseString globalSource, (err, cal) ->
should.not.exist err
newCal = cal.toString().replace(new RegExp("\r", 'g'), "").split("\n")
sourceCal = globalSource.split("\n")
newCal.should.eql sourceCal
it "should generate a propery Cozy Event for event with duration", ->
source = """
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//dmfs.org//mimedir.icalendar//EN
BEGIN:VEVENT
DTSTART;TZID=Europe/Paris:20141111T140000
SUMMARY:Recurring
RRULE:FREQ=WEEKLY;UNTIL=20141231T130000Z;WKST=MO;BYDAY=TU
TRANSP:OPAQUE
STATUS:CONFIRMED
DURATION:PT1H
LAST-MODIFIED:20141110T111600Z
DTSTAMP:20141110T111600Z
CREATED:20141110T111600Z
UID:b4fc5c25-17d7-4849-b06a-af936cc08da8
BEGIN:VALARM
TRIGGER;VALUE=DURATION:-PT10M
ACTION:DISPLAY
DESCRIPTION:Default Event Notification
X-WR-ALARMUID:d7c56cf9-52b0-4c89-8ba7-292e13cefcaa
END:VALARM
END:VEVENT
END:VCALENDAR"""
new ICalParser().parseString source, (err, comp) ->
should.not.exist err
should.exist comp
events = Event.extractEvents comp
events.length.should.equal 1
event = events[0]
event.should.have.property 'start', '2014-11-11T14:00:00.000'
event.should.have.property 'end', '2014-11-11T15:00:00.000'
it "should generate a propery Cozy Event for event with attendees", ->
source = """
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//dmfs.org//mimedir.icalendar//EN
BEGIN:VEVENT
DTSTART;TZID=Europe/Paris:20141111T140000
DESCRIPTION:Party
SUMMARY:Attendees
TRANSP:OPAQUE
STATUS:CONFIRMED
ATTENDEE;PARTSTAT=ACCEPTED;RSVP=TRUE;ROLE=REQ-PARTICIPANT:mailto:me@192.168.1
.67
ATTENDEE;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;ROLE=REQ-PARTICIPANT:mailto:test@cozy.io
DTEND;TZID=Europe/Paris:20141111T200000
LAST-MODIFIED:20141110T115555Z
DTSTAMP:20141110T115555Z
ORGANIZER:mailto:me@192.168.1.67
CREATED:20141110T115555Z
UID:240673b0-6dc0-4ced-9cec-d0e69e1d7cb5
BEGIN:VALARM
TRIGGER;VALUE=DURATION:-PT10M
ACTION:DISPLAY
DESCRIPTION:Default Event Notification
X-WR-ALARMUID:5cf3c1d2-17ec-4f70-9309-3180472042d6
END:VALARM
END:VEVENT
END:VCALENDAR"""
new ICalParser().parseString source, (err, comp) ->
should.not.exist err
should.exist comp
events = Event.extractEvents comp
events.length.should.equal 1
event = events[0]
event.should.have.property 'attendees'
should.exist event.attendees
event.attendees.length.should.equal 2
attendee = event.attendees[1]
attendee.should.have.property 'id', 2
attendee.should.have.property 'email', 'test@cozy.io'
attendee.should.have.property 'contactid', null
attendee.should.have.property 'status', 'INVITATION-NOT-SENT'
| 5901 | path = require 'path'
should = require 'should'
moment = require 'moment-timezone'
{RRule} = require 'rrule'
{ICalParser, VCalendar, VAlarm, VTodo, VEvent} = require '../src/index'
{decorateAlarm, decorateEvent} = require '../src/index'
# mock classes
Alarm = class Alarm
getAttendeesEmail: -> return ['<EMAIL>']
Event = class Event
@dateFormat = 'YYYY-MM-DD'
@ambiguousDTFormat = 'YYYY-MM-DD[T]HH:mm:00.000'
@utcDTFormat = 'YYYY-MM-DD[T]HH:mm:00.000[Z]'
describe "Cozy models decorator", ->
globalSource = """
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Cozy Cloud//NONSGML Cozy Agenda//EN
BEGIN:VEVENT
UID:aeba6310b07a22a72423b2b11f320692
DTSTAMP:20141107T153700Z
DTSTART;TZID=Europe/Paris:20141106T120000
DTEND;TZID=Europe/Paris:20141106T130000
ATTENDEE;PARTSTAT=NEEDS-ACTION:mailto:<EMAIL>
DESCRIPTION:Crawling a hidden dungeon
LOCATION:Hidden dungeon
RRULE:FREQ=WEEKLY;INTERVAL=1;UNTIL=20150101T000000Z;BYDAY=TH
SUMMARY:Recurring event
END:VEVENT
BEGIN:VTODO
UID:aeba6310b07a22a72423b2b11f320693
SUMMARY:Something to remind
DTSTART:20141108T150000Z
DTSTAMP:20141108T150000Z
BEGIN:VALARM
ACTION:EMAIL
ATTENDEE:mailto:<EMAIL>
TRIGGER:PT0M
DESCRIPTION:Something to remind
END:VALARM
END:VTODO
END:VCALENDAR
"""
describe "Event", ->
it "decorating shouldn't trigger an error", ->
decorateEvent.bind(null, Event).should.not.throw()
it "::extractEvents should retrieve all the events from the source", (done) ->
new ICalParser().parseString globalSource, (err, comp) =>
should.not.exist err
@events = Event.extractEvents comp
should.exist @events
@events.length.should.equal 1
done()
it "::fromIcal should generate a proper Cozy Event", ->
# events comes from extractEvents, that uses fromIcal under the hood
event = @events[0]
should.exist event
event.should.have.property 'uid', 'aeba6310b07a22a72423b2b11f320692'
event.should.have.property 'description', 'Recurring event'
event.should.have.property 'start', '2014-11-06T12:00:00.000'
event.should.have.property 'end', '2014-11-06T13:00:00.000'
event.should.have.property 'place', 'Hidden dungeon'
event.should.have.property 'details', 'Crawling a hidden dungeon'
event.should.have.property 'rrule', 'FREQ=WEEKLY;INTERVAL=1;UNTIL=20150101T000000Z;BYDAY=TH'
event.should.have.property 'alarms', []
event.should.have.property 'timezone', 'Europe/Paris'
event.should.have.property 'tags', ['my calendar']
event.should.have.property 'lastModification', '2014-11-07T15:37:00.000Z'
event.should.have.property 'attendees'
event.attendees.length.should.equal 1
event.attendees[0].should.have.property 'email', '<EMAIL>'
event.attendees[0].should.have.property 'status', 'INVITATION-NOT-SENT'
it "::toIcal should generate a proper vEvent based on Cozy Event", ->
event = @events[0]
should.exist event
vEvent = event.toIcal()
vEvent.toString().should.equal """
BEGIN:VEVENT
UID:aeba6310b07a22a72423b2b11f320692
DTSTAMP:20141107T153700Z
DTSTART;TZID=Europe/Paris:20141106T120000
DTEND;TZID=Europe/Paris:20141106T130000
ATTENDEE;PARTSTAT=NEEDS-ACTION;CN=<EMAIL>:mailto:<EMAIL>
DESCRIPTION:Crawling a hidden dungeon
LAST-MODIFIED:20141107T153700Z
LOCATION:Hidden dungeon
RRULE:FREQ=WEEKLY;INTERVAL=1;UNTIL=20150101T000000Z;BYDAY=TH
SUMMARY:Recurring event
END:VEVENT
""".replace /\n/g, '\r\n'
describe "Specific cases", ->
it 'should generate identical ical as source', ->
new ICalParser().parseString globalSource, (err, cal) ->
should.not.exist err
newCal = cal.toString().replace(new RegExp("\r", 'g'), "").split("\n")
sourceCal = globalSource.split("\n")
newCal.should.eql sourceCal
it "should generate a propery Cozy Event for event with duration", ->
source = """
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//dmfs.org//mimedir.icalendar//EN
BEGIN:VEVENT
DTSTART;TZID=Europe/Paris:20141111T140000
SUMMARY:Recurring
RRULE:FREQ=WEEKLY;UNTIL=20141231T130000Z;WKST=MO;BYDAY=TU
TRANSP:OPAQUE
STATUS:CONFIRMED
DURATION:PT1H
LAST-MODIFIED:20141110T111600Z
DTSTAMP:20141110T111600Z
CREATED:20141110T111600Z
UID:b4fc5c25-17d7-4849-b06a-af936cc08da8
BEGIN:VALARM
TRIGGER;VALUE=DURATION:-PT10M
ACTION:DISPLAY
DESCRIPTION:Default Event Notification
X-WR-ALARMUID:d7c56cf9-52b0-4c89-8ba7-292e13cefcaa
END:VALARM
END:VEVENT
END:VCALENDAR"""
new ICalParser().parseString source, (err, comp) ->
should.not.exist err
should.exist comp
events = Event.extractEvents comp
events.length.should.equal 1
event = events[0]
event.should.have.property 'start', '2014-11-11T14:00:00.000'
event.should.have.property 'end', '2014-11-11T15:00:00.000'
it "should generate a propery Cozy Event for event with attendees", ->
source = """
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//dmfs.org//mimedir.icalendar//EN
BEGIN:VEVENT
DTSTART;TZID=Europe/Paris:20141111T140000
DESCRIPTION:Party
SUMMARY:Attendees
TRANSP:OPAQUE
STATUS:CONFIRMED
ATTENDEE;PARTSTAT=ACCEPTED;RSVP=TRUE;ROLE=REQ-PARTICIPANT:mailto:me@192.168.1
.67
ATTENDEE;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;ROLE=REQ-PARTICIPANT:mailto:<EMAIL>
DTEND;TZID=Europe/Paris:20141111T200000
LAST-MODIFIED:20141110T115555Z
DTSTAMP:20141110T115555Z
ORGANIZER:mailto:me@192.168.1.67
CREATED:20141110T115555Z
UID:240673b0-6dc0-4ced-9cec-d0e69e1d7cb5
BEGIN:VALARM
TRIGGER;VALUE=DURATION:-PT10M
ACTION:DISPLAY
DESCRIPTION:Default Event Notification
X-WR-ALARMUID:5cf3c1d2-17ec-4f70-9309-3180472042d6
END:VALARM
END:VEVENT
END:VCALENDAR"""
new ICalParser().parseString source, (err, comp) ->
should.not.exist err
should.exist comp
events = Event.extractEvents comp
events.length.should.equal 1
event = events[0]
event.should.have.property 'attendees'
should.exist event.attendees
event.attendees.length.should.equal 2
attendee = event.attendees[1]
attendee.should.have.property 'id', 2
attendee.should.have.property 'email', '<EMAIL>'
attendee.should.have.property 'contactid', null
attendee.should.have.property 'status', 'INVITATION-NOT-SENT'
| true | path = require 'path'
should = require 'should'
moment = require 'moment-timezone'
{RRule} = require 'rrule'
{ICalParser, VCalendar, VAlarm, VTodo, VEvent} = require '../src/index'
{decorateAlarm, decorateEvent} = require '../src/index'
# mock classes
Alarm = class Alarm
getAttendeesEmail: -> return ['PI:EMAIL:<EMAIL>END_PI']
Event = class Event
@dateFormat = 'YYYY-MM-DD'
@ambiguousDTFormat = 'YYYY-MM-DD[T]HH:mm:00.000'
@utcDTFormat = 'YYYY-MM-DD[T]HH:mm:00.000[Z]'
describe "Cozy models decorator", ->
globalSource = """
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Cozy Cloud//NONSGML Cozy Agenda//EN
BEGIN:VEVENT
UID:aeba6310b07a22a72423b2b11f320692
DTSTAMP:20141107T153700Z
DTSTART;TZID=Europe/Paris:20141106T120000
DTEND;TZID=Europe/Paris:20141106T130000
ATTENDEE;PARTSTAT=NEEDS-ACTION:mailto:PI:EMAIL:<EMAIL>END_PI
DESCRIPTION:Crawling a hidden dungeon
LOCATION:Hidden dungeon
RRULE:FREQ=WEEKLY;INTERVAL=1;UNTIL=20150101T000000Z;BYDAY=TH
SUMMARY:Recurring event
END:VEVENT
BEGIN:VTODO
UID:aeba6310b07a22a72423b2b11f320693
SUMMARY:Something to remind
DTSTART:20141108T150000Z
DTSTAMP:20141108T150000Z
BEGIN:VALARM
ACTION:EMAIL
ATTENDEE:mailto:PI:EMAIL:<EMAIL>END_PI
TRIGGER:PT0M
DESCRIPTION:Something to remind
END:VALARM
END:VTODO
END:VCALENDAR
"""
describe "Event", ->
it "decorating shouldn't trigger an error", ->
decorateEvent.bind(null, Event).should.not.throw()
it "::extractEvents should retrieve all the events from the source", (done) ->
new ICalParser().parseString globalSource, (err, comp) =>
should.not.exist err
@events = Event.extractEvents comp
should.exist @events
@events.length.should.equal 1
done()
it "::fromIcal should generate a proper Cozy Event", ->
# events comes from extractEvents, that uses fromIcal under the hood
event = @events[0]
should.exist event
event.should.have.property 'uid', 'aeba6310b07a22a72423b2b11f320692'
event.should.have.property 'description', 'Recurring event'
event.should.have.property 'start', '2014-11-06T12:00:00.000'
event.should.have.property 'end', '2014-11-06T13:00:00.000'
event.should.have.property 'place', 'Hidden dungeon'
event.should.have.property 'details', 'Crawling a hidden dungeon'
event.should.have.property 'rrule', 'FREQ=WEEKLY;INTERVAL=1;UNTIL=20150101T000000Z;BYDAY=TH'
event.should.have.property 'alarms', []
event.should.have.property 'timezone', 'Europe/Paris'
event.should.have.property 'tags', ['my calendar']
event.should.have.property 'lastModification', '2014-11-07T15:37:00.000Z'
event.should.have.property 'attendees'
event.attendees.length.should.equal 1
event.attendees[0].should.have.property 'email', 'PI:EMAIL:<EMAIL>END_PI'
event.attendees[0].should.have.property 'status', 'INVITATION-NOT-SENT'
it "::toIcal should generate a proper vEvent based on Cozy Event", ->
event = @events[0]
should.exist event
vEvent = event.toIcal()
vEvent.toString().should.equal """
BEGIN:VEVENT
UID:aeba6310b07a22a72423b2b11f320692
DTSTAMP:20141107T153700Z
DTSTART;TZID=Europe/Paris:20141106T120000
DTEND;TZID=Europe/Paris:20141106T130000
ATTENDEE;PARTSTAT=NEEDS-ACTION;CN=PI:EMAIL:<EMAIL>END_PI:mailto:PI:EMAIL:<EMAIL>END_PI
DESCRIPTION:Crawling a hidden dungeon
LAST-MODIFIED:20141107T153700Z
LOCATION:Hidden dungeon
RRULE:FREQ=WEEKLY;INTERVAL=1;UNTIL=20150101T000000Z;BYDAY=TH
SUMMARY:Recurring event
END:VEVENT
""".replace /\n/g, '\r\n'
describe "Specific cases", ->
it 'should generate identical ical as source', ->
new ICalParser().parseString globalSource, (err, cal) ->
should.not.exist err
newCal = cal.toString().replace(new RegExp("\r", 'g'), "").split("\n")
sourceCal = globalSource.split("\n")
newCal.should.eql sourceCal
it "should generate a propery Cozy Event for event with duration", ->
source = """
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//dmfs.org//mimedir.icalendar//EN
BEGIN:VEVENT
DTSTART;TZID=Europe/Paris:20141111T140000
SUMMARY:Recurring
RRULE:FREQ=WEEKLY;UNTIL=20141231T130000Z;WKST=MO;BYDAY=TU
TRANSP:OPAQUE
STATUS:CONFIRMED
DURATION:PT1H
LAST-MODIFIED:20141110T111600Z
DTSTAMP:20141110T111600Z
CREATED:20141110T111600Z
UID:b4fc5c25-17d7-4849-b06a-af936cc08da8
BEGIN:VALARM
TRIGGER;VALUE=DURATION:-PT10M
ACTION:DISPLAY
DESCRIPTION:Default Event Notification
X-WR-ALARMUID:d7c56cf9-52b0-4c89-8ba7-292e13cefcaa
END:VALARM
END:VEVENT
END:VCALENDAR"""
new ICalParser().parseString source, (err, comp) ->
should.not.exist err
should.exist comp
events = Event.extractEvents comp
events.length.should.equal 1
event = events[0]
event.should.have.property 'start', '2014-11-11T14:00:00.000'
event.should.have.property 'end', '2014-11-11T15:00:00.000'
it "should generate a propery Cozy Event for event with attendees", ->
source = """
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//dmfs.org//mimedir.icalendar//EN
BEGIN:VEVENT
DTSTART;TZID=Europe/Paris:20141111T140000
DESCRIPTION:Party
SUMMARY:Attendees
TRANSP:OPAQUE
STATUS:CONFIRMED
ATTENDEE;PARTSTAT=ACCEPTED;RSVP=TRUE;ROLE=REQ-PARTICIPANT:mailto:me@192.168.1
.67
ATTENDEE;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;ROLE=REQ-PARTICIPANT:mailto:PI:EMAIL:<EMAIL>END_PI
DTEND;TZID=Europe/Paris:20141111T200000
LAST-MODIFIED:20141110T115555Z
DTSTAMP:20141110T115555Z
ORGANIZER:mailto:me@192.168.1.67
CREATED:20141110T115555Z
UID:240673b0-6dc0-4ced-9cec-d0e69e1d7cb5
BEGIN:VALARM
TRIGGER;VALUE=DURATION:-PT10M
ACTION:DISPLAY
DESCRIPTION:Default Event Notification
X-WR-ALARMUID:5cf3c1d2-17ec-4f70-9309-3180472042d6
END:VALARM
END:VEVENT
END:VCALENDAR"""
new ICalParser().parseString source, (err, comp) ->
should.not.exist err
should.exist comp
events = Event.extractEvents comp
events.length.should.equal 1
event = events[0]
event.should.have.property 'attendees'
should.exist event.attendees
event.attendees.length.should.equal 2
attendee = event.attendees[1]
attendee.should.have.property 'id', 2
attendee.should.have.property 'email', 'PI:EMAIL:<EMAIL>END_PI'
attendee.should.have.property 'contactid', null
attendee.should.have.property 'status', 'INVITATION-NOT-SENT'
|
[
{
"context": "xtensions: [\n contentful(\n access_token: 'YOUR_ACCESS_TOKEN'\n space_id: 'aqzq2qya2jm4'\n content_typ",
"end": 212,
"score": 0.8154392242431641,
"start": 195,
"tag": "PASSWORD",
"value": "YOUR_ACCESS_TOKEN"
}
] | test/fixtures/transform/app.coffee | viksoh/roots-contentful-GAR | 90 | contentful = require '../../..'
megaTransform = (entry)->
delete entry.body
entry
module.exports =
ignores: ["**/_*", "**/.DS_Store"]
extensions: [
contentful(
access_token: 'YOUR_ACCESS_TOKEN'
space_id: 'aqzq2qya2jm4'
content_types: [
{
id: '6BYT1gNiIEyIw8Og8aQAO6',
write: 'posts.json',
transform: megaTransform
}
]
)
]
| 170677 | contentful = require '../../..'
megaTransform = (entry)->
delete entry.body
entry
module.exports =
ignores: ["**/_*", "**/.DS_Store"]
extensions: [
contentful(
access_token: '<PASSWORD>'
space_id: 'aqzq2qya2jm4'
content_types: [
{
id: '6BYT1gNiIEyIw8Og8aQAO6',
write: 'posts.json',
transform: megaTransform
}
]
)
]
| true | contentful = require '../../..'
megaTransform = (entry)->
delete entry.body
entry
module.exports =
ignores: ["**/_*", "**/.DS_Store"]
extensions: [
contentful(
access_token: 'PI:PASSWORD:<PASSWORD>END_PI'
space_id: 'aqzq2qya2jm4'
content_types: [
{
id: '6BYT1gNiIEyIw8Og8aQAO6',
write: 'posts.json',
transform: megaTransform
}
]
)
]
|
[
{
"context": "st\": (test) ->\n res = lunch.set([], \"User\", \"Jimmy Johns\")\n test.deepEqual(res[0], {user: \"User\", cho",
"end": 178,
"score": 0.9997356534004211,
"start": 167,
"tag": "NAME",
"value": "Jimmy Johns"
},
{
"context": "immy Johns\")\n test.deepEqual(r... | test/apps.coffee | statianzo/hubot-lunch-rotation | 1 | Error.stackTraceLimit = 1
lunch = require("../src/lunch")
module.exports =
set:
"Sets preference to lunch list": (test) ->
res = lunch.set([], "User", "Jimmy Johns")
test.deepEqual(res[0], {user: "User", choice: "Jimmy Johns"})
test.done()
"Updates existing lunch preference": (test) ->
added = lunch.set([], "User", "Jimmy Johns")
updated = lunch.set(added, "User", "KFC")
test.equal(updated.length, 1)
test.deepEqual(updated[0], {user: "User", choice: "KFC"})
test.done()
unset:
"Unsets a preferred lunch": (test) ->
added = lunch.set([], "User", "Jimmy Johns")
updated = lunch.unset(added, "User")
test.deepEqual(updated, [])
test.done()
"Copes with entry not found": (test) ->
updated = lunch.unset([], "User")
test.deepEqual(updated, [])
test.done()
rotate:
"Rotates a list": (test) ->
orig = [1,2,3]
res = lunch.rotate(orig)
test.deepEqual(res, [2,3,1])
test.done()
"Rotates an empty list": (test) ->
res = lunch.rotate([])
test.deepEqual(res, [])
test.done()
queue:
"Lists queue of upcoming": (test) ->
expected = "1. B - A\n2. D - C"
res = lunch.queue([{user: 'A', choice: 'B'}, {user: 'C', choice:'D'}])
test.equal(res, expected)
test.done()
| 140600 | Error.stackTraceLimit = 1
lunch = require("../src/lunch")
module.exports =
set:
"Sets preference to lunch list": (test) ->
res = lunch.set([], "User", "<NAME>")
test.deepEqual(res[0], {user: "User", choice: "<NAME>"})
test.done()
"Updates existing lunch preference": (test) ->
added = lunch.set([], "User", "<NAME>")
updated = lunch.set(added, "User", "KFC")
test.equal(updated.length, 1)
test.deepEqual(updated[0], {user: "User", choice: "KFC"})
test.done()
unset:
"Unsets a preferred lunch": (test) ->
added = lunch.set([], "User", "<NAME>")
updated = lunch.unset(added, "User")
test.deepEqual(updated, [])
test.done()
"Copes with entry not found": (test) ->
updated = lunch.unset([], "User")
test.deepEqual(updated, [])
test.done()
rotate:
"Rotates a list": (test) ->
orig = [1,2,3]
res = lunch.rotate(orig)
test.deepEqual(res, [2,3,1])
test.done()
"Rotates an empty list": (test) ->
res = lunch.rotate([])
test.deepEqual(res, [])
test.done()
queue:
"Lists queue of upcoming": (test) ->
expected = "1. B - A\n2. D - C"
res = lunch.queue([{user: 'A', choice: 'B'}, {user: 'C', choice:'D'}])
test.equal(res, expected)
test.done()
| true | Error.stackTraceLimit = 1
lunch = require("../src/lunch")
module.exports =
set:
"Sets preference to lunch list": (test) ->
res = lunch.set([], "User", "PI:NAME:<NAME>END_PI")
test.deepEqual(res[0], {user: "User", choice: "PI:NAME:<NAME>END_PI"})
test.done()
"Updates existing lunch preference": (test) ->
added = lunch.set([], "User", "PI:NAME:<NAME>END_PI")
updated = lunch.set(added, "User", "KFC")
test.equal(updated.length, 1)
test.deepEqual(updated[0], {user: "User", choice: "KFC"})
test.done()
unset:
"Unsets a preferred lunch": (test) ->
added = lunch.set([], "User", "PI:NAME:<NAME>END_PI")
updated = lunch.unset(added, "User")
test.deepEqual(updated, [])
test.done()
"Copes with entry not found": (test) ->
updated = lunch.unset([], "User")
test.deepEqual(updated, [])
test.done()
rotate:
"Rotates a list": (test) ->
orig = [1,2,3]
res = lunch.rotate(orig)
test.deepEqual(res, [2,3,1])
test.done()
"Rotates an empty list": (test) ->
res = lunch.rotate([])
test.deepEqual(res, [])
test.done()
queue:
"Lists queue of upcoming": (test) ->
expected = "1. B - A\n2. D - C"
res = lunch.queue([{user: 'A', choice: 'B'}, {user: 'C', choice:'D'}])
test.equal(res, expected)
test.done()
|
[
{
"context": "set jira_lookup_style [long|short]\n#\n# Author:\n# Matthew Finlayson <matthew.finlayson@jivesoftware.com> (http://www.",
"end": 499,
"score": 0.9998307228088379,
"start": 482,
"tag": "NAME",
"value": "Matthew Finlayson"
},
{
"context": "e [long|short]\n#\n# Author:\n... | scripts/jira-lookup.coffee | jivesoftware/hubot-jira-lookup | 20 | # Description:
# Jira lookup when issues are heard
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_JIRA_LOOKUP_USERNAME
# HUBOT_JIRA_LOOKUP_PASSWORD
# HUBOT_JIRA_LOOKUP_URL
# HUBOT_JIRA_LOOKUP_IGNORE_USERS (optional, format: "user1|user2", default is "jira|github")
# HUBOT_JIRA_LOOKUP_INC_DESC
# HUBOT_JIRA_LOOKUP_MAX_DESC_LEN
# HUBOT_JIRA_LOOKUP_SIMPLE
# HUBOI_JIRA_LOOKUP_TIMEOUT
#
# Commands:
# hubot set jira_lookup_style [long|short]
#
# Author:
# Matthew Finlayson <matthew.finlayson@jivesoftware.com> (http://www.jivesoftware.com)
# Benjamin Sherman <benjamin@jivesoftware.com> (http://www.jivesoftware.com)
# Dustin Miller <dustin@sharepointexperts.com> (http://sharepointexperience.com)
## Prevent the bot sending the jira ticket details too often in any channel
## Store when a ticket was reported to a channel
# Key: channelid-ticketid
# Value: timestamp
#
LastHeard = {}
RecordLastHeard = (robot,channel,ticket) ->
ts = new Date()
key = "#{channel}-#{ticket}"
LastHeard[key] = ts
CheckLastHeard = (robot,channel,ticket) ->
now = new Date()
key = "#{channel}-#{ticket}"
last = LastHeard[key] || 0
timeout = process.env.HUBOT_JIRA_LOOKUP_TIMEOUT || 15
limit = (1000 * 60 * timeout)
diff = now - last
robot.logger.debug "Check: #{key} #{diff} #{limit}"
if diff < limit
return yes
no
StylePrefStore = {}
SetRoomStylePref = (robot, msg, pref) ->
room = msg.message.user.reply_to || msg.message.user.room
StylePrefStore[room] = pref
storePrefToBrain robot, room, pref
msg.send "Jira Lookup Style Set To #{pref} For #{room}"
GetRoomStylePref = (robot, msg) ->
room = msg.message.user.reply_to || msg.message.user.room
def_style = process.env.HUBOT_JIRA_LOOKUP_STYLE || "long"
rm_style = StylePrefStore[room]
if rm_style
return rm_style
def_style
storePrefToBrain = (robot, room, pref) ->
robot.brain.data.jiralookupprefs[room] = pref
syncPrefs = (robot) ->
nonCachedPrefs = difference(robot.brain.data.jiralookupprefs, StylePrefStore)
for own room, pref of nonCachedPrefs
StylePrefStore[room] = pref
nonStoredPrefs = difference(StylePrefStore, robot.brain.data.jiralookupprefs)
for own room, pref of nonStoredPrefs
storePrefToBrain robot, room, pref
difference = (obj1, obj2) ->
diff = {}
for room, pref of obj1
diff[room] = pref if room !of obj2
return diff
module.exports = (robot) ->
robot.brain.data.jiralookupprefs or= {}
robot.brain.on 'loaded', =>
syncPrefs robot
ignored_users = process.env.HUBOT_JIRA_LOOKUP_IGNORE_USERS
if ignored_users == undefined
ignored_users = "jira|github"
console.log "Ignore Users: #{ignored_users}"
robot.respond /set jira_lookup_style (long|short)/, (msg) ->
SetRoomStylePref robot, msg, msg.match[1]
robot.hear /\b[a-zA-Z]{2,12}-[0-9]{1,10}\b/g, (msg) ->
return if msg.message.user.name.match(new RegExp(ignored_users, "gi"))
robot.logger.debug "Matched: "+msg.match.join(',')
reportIssue robot, msg, issue for issue in msg.match
reportIssue = (robot, msg, issue) ->
room = msg.message.user.reply_to || msg.message.user.room
robot.logger.debug "Issue: #{issue} in channel #{room}"
return if CheckLastHeard(robot, room, issue)
RecordLastHeard robot, room, issue
if process.env.HUBOT_JIRA_LOOKUP_SIMPLE is "true"
msg.send "Issue: #{issue} - #{process.env.HUBOT_JIRA_LOOKUP_URL}/browse/#{issue}"
else
user = process.env.HUBOT_JIRA_LOOKUP_USERNAME
pass = process.env.HUBOT_JIRA_LOOKUP_PASSWORD
url = process.env.HUBOT_JIRA_LOOKUP_URL
inc_desc = process.env.HUBOT_JIRA_LOOKUP_INC_DESC
if inc_desc == undefined
inc_desc = "Y"
max_len = process.env.HUBOT_JIRA_LOOKUP_MAX_DESC_LEN
auth = 'Basic ' + new Buffer(user + ':' + pass).toString('base64')
robot.http("#{url}/rest/api/latest/issue/#{issue}")
.headers(Authorization: auth, Accept: 'application/json')
.get() (err, res, body) ->
try
json = JSON.parse(body)
data = {
'key': {
key: 'Key'
value: issue
}
'summary': {
key: 'Summary'
value: json.fields.summary || null
}
'link': {
key: 'Link'
value: "#{process.env.HUBOT_JIRA_LOOKUP_URL}/browse/#{json.key}"
}
'description': {
key: 'Description',
value: json.fields.description || null
}
'assignee': {
key: 'Assignee',
value: (json.fields.assignee && json.fields.assignee.displayName) || 'Unassigned'
}
'reporter': {
key: 'Reporter',
value: (json.fields.reporter && json.fields.reporter.displayName) || null
}
'created': {
key: 'Created',
value: json.fields.created && (new Date(json.fields.created)).toLocaleString() || null
}
'status': {
key: 'Status',
value: (json.fields.status && json.fields.status.name) || null
}
}
style = GetRoomStylePref robot, msg
if style is "long"
fallback = "Issue:\t #{data.key.value}: #{data.summary.value}\n"
if data.description.value? and inc_desc.toUpperCase() is "Y"
if max_len and data.description.value?.length > max_len
fallback += "Description:\t #{data.description.value.substring(0,max_len)} ...\n"
else
fallback += "Description:\t #{data.description.value}\n"
fallback += "Assignee:\t #{data.assignee.value}\nStatus:\t #{data.status.value}\nLink:\t #{data.link.value}\n"
else
fallback = "#{data.key.value}: #{data.summary.value} [status #{data.status.value}; assigned to #{data.assignee.value} ] #{data.link.value}"
if process.env.HUBOT_SLACK_INCOMING_WEBHOOK?
if style is "long"
robot.emit 'slack.attachment',
message: msg.message
content:
fallback: fallback
title: "#{data.key.value}: #{data.summary.value}"
title_link: data.link.value
text: data.description.value
fields: [
{
title: data.reporter.key
value: data.reporter.value
short: true
}
{
title: data.assignee.key
value: data.assignee.value
short: true
}
{
title: data.status.key
value: data.status.value
short: true
}
{
title: data.created.key
value: data.created.value
short: true
}
]
else
robot.emit 'slack.attachment',
message: msg.message
content:
fallback: fallback
title: "#{data.key.value}: #{data.summary.value}"
title_link: data.link.value
text: "Status: #{data.status.value}; Assigned: #{data.assignee.value}"
else
msg.send fallback
catch error
console.log error
| 49768 | # Description:
# Jira lookup when issues are heard
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_JIRA_LOOKUP_USERNAME
# HUBOT_JIRA_LOOKUP_PASSWORD
# HUBOT_JIRA_LOOKUP_URL
# HUBOT_JIRA_LOOKUP_IGNORE_USERS (optional, format: "user1|user2", default is "jira|github")
# HUBOT_JIRA_LOOKUP_INC_DESC
# HUBOT_JIRA_LOOKUP_MAX_DESC_LEN
# HUBOT_JIRA_LOOKUP_SIMPLE
# HUBOI_JIRA_LOOKUP_TIMEOUT
#
# Commands:
# hubot set jira_lookup_style [long|short]
#
# Author:
# <NAME> <<EMAIL>> (http://www.jivesoftware.com)
# <NAME> <<EMAIL>> (http://www.jivesoftware.com)
# <NAME> <<EMAIL>> (http://sharepointexperience.com)
## Prevent the bot sending the jira ticket details too often in any channel
## Store when a ticket was reported to a channel
# Key: <KEY>
# Value: timestamp
#
LastHeard = {}
RecordLastHeard = (robot,channel,ticket) ->
ts = new Date()
key = <KEY>
LastHeard[key] = ts
CheckLastHeard = (robot,channel,ticket) ->
now = new Date()
key = <KEY>
last = LastHeard[key] || 0
timeout = process.env.HUBOT_JIRA_LOOKUP_TIMEOUT || 15
limit = (1000 * 60 * timeout)
diff = now - last
robot.logger.debug "Check: #{key} #{diff} #{limit}"
if diff < limit
return yes
no
StylePrefStore = {}
SetRoomStylePref = (robot, msg, pref) ->
room = msg.message.user.reply_to || msg.message.user.room
StylePrefStore[room] = pref
storePrefToBrain robot, room, pref
msg.send "Jira Lookup Style Set To #{pref} For #{room}"
GetRoomStylePref = (robot, msg) ->
room = msg.message.user.reply_to || msg.message.user.room
def_style = process.env.HUBOT_JIRA_LOOKUP_STYLE || "long"
rm_style = StylePrefStore[room]
if rm_style
return rm_style
def_style
storePrefToBrain = (robot, room, pref) ->
robot.brain.data.jiralookupprefs[room] = pref
syncPrefs = (robot) ->
nonCachedPrefs = difference(robot.brain.data.jiralookupprefs, StylePrefStore)
for own room, pref of nonCachedPrefs
StylePrefStore[room] = pref
nonStoredPrefs = difference(StylePrefStore, robot.brain.data.jiralookupprefs)
for own room, pref of nonStoredPrefs
storePrefToBrain robot, room, pref
difference = (obj1, obj2) ->
diff = {}
for room, pref of obj1
diff[room] = pref if room !of obj2
return diff
module.exports = (robot) ->
robot.brain.data.jiralookupprefs or= {}
robot.brain.on 'loaded', =>
syncPrefs robot
ignored_users = process.env.HUBOT_JIRA_LOOKUP_IGNORE_USERS
if ignored_users == undefined
ignored_users = "jira|github"
console.log "Ignore Users: #{ignored_users}"
robot.respond /set jira_lookup_style (long|short)/, (msg) ->
SetRoomStylePref robot, msg, msg.match[1]
robot.hear /\b[a-zA-Z]{2,12}-[0-9]{1,10}\b/g, (msg) ->
return if msg.message.user.name.match(new RegExp(ignored_users, "gi"))
robot.logger.debug "Matched: "+msg.match.join(',')
reportIssue robot, msg, issue for issue in msg.match
reportIssue = (robot, msg, issue) ->
room = msg.message.user.reply_to || msg.message.user.room
robot.logger.debug "Issue: #{issue} in channel #{room}"
return if CheckLastHeard(robot, room, issue)
RecordLastHeard robot, room, issue
if process.env.HUBOT_JIRA_LOOKUP_SIMPLE is "true"
msg.send "Issue: #{issue} - #{process.env.HUBOT_JIRA_LOOKUP_URL}/browse/#{issue}"
else
user = process.env.HUBOT_JIRA_LOOKUP_USERNAME
pass = process.env.HUBOT_JIRA_LOOKUP_PASSWORD
url = process.env.HUBOT_JIRA_LOOKUP_URL
inc_desc = process.env.HUBOT_JIRA_LOOKUP_INC_DESC
if inc_desc == undefined
inc_desc = "Y"
max_len = process.env.HUBOT_JIRA_LOOKUP_MAX_DESC_LEN
auth = 'Basic ' + new Buffer(user + ':' + pass).toString('base64')
robot.http("#{url}/rest/api/latest/issue/#{issue}")
.headers(Authorization: auth, Accept: 'application/json')
.get() (err, res, body) ->
try
json = JSON.parse(body)
data = {
'key': {
key: 'Key'
value: issue
}
'summary': {
key: 'Summary'
value: json.fields.summary || null
}
'link': {
key: 'Link'
value: "#{process.env.HUBOT_JIRA_LOOKUP_URL}/browse/#{json.key}"
}
'description': {
key: 'Description',
value: json.fields.description || null
}
'assignee': {
key: 'Assignee',
value: (json.fields.assignee && json.fields.assignee.displayName) || 'Unassigned'
}
'reporter': {
key: 'Reporter',
value: (json.fields.reporter && json.fields.reporter.displayName) || null
}
'created': {
key: 'Created',
value: json.fields.created && (new Date(json.fields.created)).toLocaleString() || null
}
'status': {
key: 'Status',
value: (json.fields.status && json.fields.status.name) || null
}
}
style = GetRoomStylePref robot, msg
if style is "long"
fallback = "Issue:\t #{data.key.value}: #{data.summary.value}\n"
if data.description.value? and inc_desc.toUpperCase() is "Y"
if max_len and data.description.value?.length > max_len
fallback += "Description:\t #{data.description.value.substring(0,max_len)} ...\n"
else
fallback += "Description:\t #{data.description.value}\n"
fallback += "Assignee:\t #{data.assignee.value}\nStatus:\t #{data.status.value}\nLink:\t #{data.link.value}\n"
else
fallback = "#{data.key.value}: #{data.summary.value} [status #{data.status.value}; assigned to #{data.assignee.value} ] #{data.link.value}"
if process.env.HUBOT_SLACK_INCOMING_WEBHOOK?
if style is "long"
robot.emit 'slack.attachment',
message: msg.message
content:
fallback: fallback
title: "#{data.key.value}: #{data.summary.value}"
title_link: data.link.value
text: data.description.value
fields: [
{
title: data.reporter.key
value: data.reporter.value
short: true
}
{
title: data.assignee.key
value: data.assignee.value
short: true
}
{
title: data.status.key
value: data.status.value
short: true
}
{
title: data.created.key
value: data.created.value
short: true
}
]
else
robot.emit 'slack.attachment',
message: msg.message
content:
fallback: fallback
title: "#{data.key.value}: #{data.summary.value}"
title_link: data.link.value
text: "Status: #{data.status.value}; Assigned: #{data.assignee.value}"
else
msg.send fallback
catch error
console.log error
| true | # Description:
# Jira lookup when issues are heard
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_JIRA_LOOKUP_USERNAME
# HUBOT_JIRA_LOOKUP_PASSWORD
# HUBOT_JIRA_LOOKUP_URL
# HUBOT_JIRA_LOOKUP_IGNORE_USERS (optional, format: "user1|user2", default is "jira|github")
# HUBOT_JIRA_LOOKUP_INC_DESC
# HUBOT_JIRA_LOOKUP_MAX_DESC_LEN
# HUBOT_JIRA_LOOKUP_SIMPLE
# HUBOI_JIRA_LOOKUP_TIMEOUT
#
# Commands:
# hubot set jira_lookup_style [long|short]
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (http://www.jivesoftware.com)
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (http://www.jivesoftware.com)
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (http://sharepointexperience.com)
## Prevent the bot sending the jira ticket details too often in any channel
## Store when a ticket was reported to a channel
# Key: PI:KEY:<KEY>END_PI
# Value: timestamp
#
LastHeard = {}
RecordLastHeard = (robot,channel,ticket) ->
ts = new Date()
key = PI:KEY:<KEY>END_PI
LastHeard[key] = ts
CheckLastHeard = (robot,channel,ticket) ->
now = new Date()
key = PI:KEY:<KEY>END_PI
last = LastHeard[key] || 0
timeout = process.env.HUBOT_JIRA_LOOKUP_TIMEOUT || 15
limit = (1000 * 60 * timeout)
diff = now - last
robot.logger.debug "Check: #{key} #{diff} #{limit}"
if diff < limit
return yes
no
StylePrefStore = {}
SetRoomStylePref = (robot, msg, pref) ->
room = msg.message.user.reply_to || msg.message.user.room
StylePrefStore[room] = pref
storePrefToBrain robot, room, pref
msg.send "Jira Lookup Style Set To #{pref} For #{room}"
GetRoomStylePref = (robot, msg) ->
room = msg.message.user.reply_to || msg.message.user.room
def_style = process.env.HUBOT_JIRA_LOOKUP_STYLE || "long"
rm_style = StylePrefStore[room]
if rm_style
return rm_style
def_style
storePrefToBrain = (robot, room, pref) ->
robot.brain.data.jiralookupprefs[room] = pref
syncPrefs = (robot) ->
nonCachedPrefs = difference(robot.brain.data.jiralookupprefs, StylePrefStore)
for own room, pref of nonCachedPrefs
StylePrefStore[room] = pref
nonStoredPrefs = difference(StylePrefStore, robot.brain.data.jiralookupprefs)
for own room, pref of nonStoredPrefs
storePrefToBrain robot, room, pref
difference = (obj1, obj2) ->
diff = {}
for room, pref of obj1
diff[room] = pref if room !of obj2
return diff
module.exports = (robot) ->
robot.brain.data.jiralookupprefs or= {}
robot.brain.on 'loaded', =>
syncPrefs robot
ignored_users = process.env.HUBOT_JIRA_LOOKUP_IGNORE_USERS
if ignored_users == undefined
ignored_users = "jira|github"
console.log "Ignore Users: #{ignored_users}"
robot.respond /set jira_lookup_style (long|short)/, (msg) ->
SetRoomStylePref robot, msg, msg.match[1]
robot.hear /\b[a-zA-Z]{2,12}-[0-9]{1,10}\b/g, (msg) ->
return if msg.message.user.name.match(new RegExp(ignored_users, "gi"))
robot.logger.debug "Matched: "+msg.match.join(',')
reportIssue robot, msg, issue for issue in msg.match
reportIssue = (robot, msg, issue) ->
room = msg.message.user.reply_to || msg.message.user.room
robot.logger.debug "Issue: #{issue} in channel #{room}"
return if CheckLastHeard(robot, room, issue)
RecordLastHeard robot, room, issue
if process.env.HUBOT_JIRA_LOOKUP_SIMPLE is "true"
msg.send "Issue: #{issue} - #{process.env.HUBOT_JIRA_LOOKUP_URL}/browse/#{issue}"
else
user = process.env.HUBOT_JIRA_LOOKUP_USERNAME
pass = process.env.HUBOT_JIRA_LOOKUP_PASSWORD
url = process.env.HUBOT_JIRA_LOOKUP_URL
inc_desc = process.env.HUBOT_JIRA_LOOKUP_INC_DESC
if inc_desc == undefined
inc_desc = "Y"
max_len = process.env.HUBOT_JIRA_LOOKUP_MAX_DESC_LEN
auth = 'Basic ' + new Buffer(user + ':' + pass).toString('base64')
robot.http("#{url}/rest/api/latest/issue/#{issue}")
.headers(Authorization: auth, Accept: 'application/json')
.get() (err, res, body) ->
try
json = JSON.parse(body)
data = {
'key': {
key: 'Key'
value: issue
}
'summary': {
key: 'Summary'
value: json.fields.summary || null
}
'link': {
key: 'Link'
value: "#{process.env.HUBOT_JIRA_LOOKUP_URL}/browse/#{json.key}"
}
'description': {
key: 'Description',
value: json.fields.description || null
}
'assignee': {
key: 'Assignee',
value: (json.fields.assignee && json.fields.assignee.displayName) || 'Unassigned'
}
'reporter': {
key: 'Reporter',
value: (json.fields.reporter && json.fields.reporter.displayName) || null
}
'created': {
key: 'Created',
value: json.fields.created && (new Date(json.fields.created)).toLocaleString() || null
}
'status': {
key: 'Status',
value: (json.fields.status && json.fields.status.name) || null
}
}
style = GetRoomStylePref robot, msg
if style is "long"
fallback = "Issue:\t #{data.key.value}: #{data.summary.value}\n"
if data.description.value? and inc_desc.toUpperCase() is "Y"
if max_len and data.description.value?.length > max_len
fallback += "Description:\t #{data.description.value.substring(0,max_len)} ...\n"
else
fallback += "Description:\t #{data.description.value}\n"
fallback += "Assignee:\t #{data.assignee.value}\nStatus:\t #{data.status.value}\nLink:\t #{data.link.value}\n"
else
fallback = "#{data.key.value}: #{data.summary.value} [status #{data.status.value}; assigned to #{data.assignee.value} ] #{data.link.value}"
if process.env.HUBOT_SLACK_INCOMING_WEBHOOK?
if style is "long"
robot.emit 'slack.attachment',
message: msg.message
content:
fallback: fallback
title: "#{data.key.value}: #{data.summary.value}"
title_link: data.link.value
text: data.description.value
fields: [
{
title: data.reporter.key
value: data.reporter.value
short: true
}
{
title: data.assignee.key
value: data.assignee.value
short: true
}
{
title: data.status.key
value: data.status.value
short: true
}
{
title: data.created.key
value: data.created.value
short: true
}
]
else
robot.emit 'slack.attachment',
message: msg.message
content:
fallback: fallback
title: "#{data.key.value}: #{data.summary.value}"
title_link: data.link.value
text: "Status: #{data.status.value}; Assigned: #{data.assignee.value}"
else
msg.send fallback
catch error
console.log error
|
[
{
"context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistri",
"end": 42,
"score": 0.9998421669006348,
"start": 24,
"tag": "NAME",
"value": "Alexander Cherniuk"
},
{
"context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmai... | library/membrane/embed.coffee | ts33kr/granite | 6 | ###
Copyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
bower = require "bower"
asciify = require "asciify"
connect = require "connect"
logger = require "winston"
events = require "eventemitter2"
assert = require "assert"
colors = require "colors"
crypto = require "crypto"
nconf = require "nconf"
https = require "https"
path = require "path"
http = require "http"
util = require "util"
{Barebones} = require "./skeleton"
{Screenplay} = require "./visual"
{Preflight} = require "./preflight"
{Zombie} = require "../nucleus/zombie"
{Extending} = require "../nucleus/extends"
{Composition} = require "../nucleus/compose"
{Archetype} = require "../nucleus/arche"
{BowerToolkit} = require "../applied/bower"
{remote, external} = require "./remote"
{TransferToolkit} = require "./transfer"
{TransitToolkit} = require "./transit"
{EventsToolkit} = require "./events"
{LinksToolkit} = require "./linkage"
# This abstract base class service is a combination of `Screenplay`
# and `Zombie` for the further environment initialization and seting
# up. These preparations will be nececessary no matter what sort of
# `Screenplay` functionality you are going to implement. Currently the
# purpose of preflight is drawing in the remotes and Bower packages.
# It is intended for the embeddable services, such as auxilliaries.
module.exports.Embedded = class Embedded extends Zombie
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# These declarations below are implantations of the abstracted
# components by the means of the dynamic recomposition system.
# Please take a look at the `Composition` class implementation
# for all sorts of information on the composition system itself.
# Each of these will be dynamicall integrated in class hierarchy.
@implanting Preflight
# This is a functional hook that is automatically wired into the
# composition system. It gets invoked once a composition system
# has completed implanting a foreign component into this class,
# which is on the receiving side. This implementation ensures
# that after the composition is done, the service is still be
# considered a `Zombie` service with all attributes pertained.
this.implanted = this.ensureZombie = (compound) ->
i = "no compound class supplied to the hook"
assert _.isObject(comp = compound or null), i
assert sident = try this.identify().underline
assert fident = try comp.identify().underline
assert @derives(Zombie), "not a zombie anymore"
message = "The %s damaged %s zombie, fixing it"
warning = "Checking %s for validitity after %s"
try logger.silly warning.grey, sident, fident
process = try this::process is Zombie::process
matches = try this::matches is Zombie::matches
m = malformed = (not process) or (not matches)
logger.silly message.red, fident, sident if m
return unless malformed # nothing is damaged
assert this::process = Zombie::process or 0
assert this::matches = Zombie::matches or 0
| 117279 | ###
Copyright (c) 2013, <NAME> <<EMAIL>>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
bower = require "bower"
asciify = require "asciify"
connect = require "connect"
logger = require "winston"
events = require "eventemitter2"
assert = require "assert"
colors = require "colors"
crypto = require "crypto"
nconf = require "nconf"
https = require "https"
path = require "path"
http = require "http"
util = require "util"
{Barebones} = require "./skeleton"
{Screenplay} = require "./visual"
{Preflight} = require "./preflight"
{Zombie} = require "../nucleus/zombie"
{Extending} = require "../nucleus/extends"
{Composition} = require "../nucleus/compose"
{Archetype} = require "../nucleus/arche"
{BowerToolkit} = require "../applied/bower"
{remote, external} = require "./remote"
{TransferToolkit} = require "./transfer"
{TransitToolkit} = require "./transit"
{EventsToolkit} = require "./events"
{LinksToolkit} = require "./linkage"
# This abstract base class service is a combination of `Screenplay`
# and `Zombie` for the further environment initialization and seting
# up. These preparations will be nececessary no matter what sort of
# `Screenplay` functionality you are going to implement. Currently the
# purpose of preflight is drawing in the remotes and Bower packages.
# It is intended for the embeddable services, such as auxilliaries.
module.exports.Embedded = class Embedded extends Zombie
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# These declarations below are implantations of the abstracted
# components by the means of the dynamic recomposition system.
# Please take a look at the `Composition` class implementation
# for all sorts of information on the composition system itself.
# Each of these will be dynamicall integrated in class hierarchy.
@implanting Preflight
# This is a functional hook that is automatically wired into the
# composition system. It gets invoked once a composition system
# has completed implanting a foreign component into this class,
# which is on the receiving side. This implementation ensures
# that after the composition is done, the service is still be
# considered a `Zombie` service with all attributes pertained.
this.implanted = this.ensureZombie = (compound) ->
i = "no compound class supplied to the hook"
assert _.isObject(comp = compound or null), i
assert sident = try this.identify().underline
assert fident = try comp.identify().underline
assert @derives(Zombie), "not a zombie anymore"
message = "The %s damaged %s zombie, fixing it"
warning = "Checking %s for validitity after %s"
try logger.silly warning.grey, sident, fident
process = try this::process is Zombie::process
matches = try this::matches is Zombie::matches
m = malformed = (not process) or (not matches)
logger.silly message.red, fident, sident if m
return unless malformed # nothing is damaged
assert this::process = Zombie::process or 0
assert this::matches = Zombie::matches or 0
| true | ###
Copyright (c) 2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
bower = require "bower"
asciify = require "asciify"
connect = require "connect"
logger = require "winston"
events = require "eventemitter2"
assert = require "assert"
colors = require "colors"
crypto = require "crypto"
nconf = require "nconf"
https = require "https"
path = require "path"
http = require "http"
util = require "util"
{Barebones} = require "./skeleton"
{Screenplay} = require "./visual"
{Preflight} = require "./preflight"
{Zombie} = require "../nucleus/zombie"
{Extending} = require "../nucleus/extends"
{Composition} = require "../nucleus/compose"
{Archetype} = require "../nucleus/arche"
{BowerToolkit} = require "../applied/bower"
{remote, external} = require "./remote"
{TransferToolkit} = require "./transfer"
{TransitToolkit} = require "./transit"
{EventsToolkit} = require "./events"
{LinksToolkit} = require "./linkage"
# This abstract base class service is a combination of `Screenplay`
# and `Zombie` for the further environment initialization and seting
# up. These preparations will be nececessary no matter what sort of
# `Screenplay` functionality you are going to implement. Currently the
# purpose of preflight is drawing in the remotes and Bower packages.
# It is intended for the embeddable services, such as auxilliaries.
module.exports.Embedded = class Embedded extends Zombie
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# These declarations below are implantations of the abstracted
# components by the means of the dynamic recomposition system.
# Please take a look at the `Composition` class implementation
# for all sorts of information on the composition system itself.
# Each of these will be dynamicall integrated in class hierarchy.
@implanting Preflight
# This is a functional hook that is automatically wired into the
# composition system. It gets invoked once a composition system
# has completed implanting a foreign component into this class,
# which is on the receiving side. This implementation ensures
# that after the composition is done, the service is still be
# considered a `Zombie` service with all attributes pertained.
this.implanted = this.ensureZombie = (compound) ->
i = "no compound class supplied to the hook"
assert _.isObject(comp = compound or null), i
assert sident = try this.identify().underline
assert fident = try comp.identify().underline
assert @derives(Zombie), "not a zombie anymore"
message = "The %s damaged %s zombie, fixing it"
warning = "Checking %s for validitity after %s"
try logger.silly warning.grey, sident, fident
process = try this::process is Zombie::process
matches = try this::matches is Zombie::matches
m = malformed = (not process) or (not matches)
logger.silly message.red, fident, sident if m
return unless malformed # nothing is damaged
assert this::process = Zombie::process or 0
assert this::matches = Zombie::matches or 0
|
[
{
"context": " [iOrder](http://neocotic.com/iOrder) \n# (c) 2013 Alasdair Mercer \n# Freely distributable under the MIT license. ",
"end": 67,
"score": 0.999873161315918,
"start": 52,
"tag": "NAME",
"value": "Alasdair Mercer"
}
] | chrome/src/lib/utils.coffee | neocotic/iOrder | 0 | # [iOrder](http://neocotic.com/iOrder)
# (c) 2013 Alasdair Mercer
# Freely distributable under the MIT license.
# For all details and documentation:
# <http://neocotic.com/iOrder>
# 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 = {}
# Map of class names to understable types.
typeMap = {}
# Populate the type map for all classes.
[
'Boolean'
'Number'
'String'
'Function'
'Array'
'Date'
'RegExp'
'Object'
].forEach (name) ->
typeMap["[object #{name}]"] = name.toLowerCase()
# Utilities setup
# ---------------
utils = window.utils = new class Utils extends Class
# Public functions
# ----------------
# Create a clone of an object.
clone: (obj, deep) ->
return obj unless @isObject obj
return obj.slice() if @isArray obj
copy = {}
for own key, value of obj
copy[key] = if deep then @clone value, yes else value
copy
# Indicate whether an object is an array.
isArray: Array.isArray or (obj) -> 'array' is @type obj
# Indicate whether an object is an object.
isObject: (obj) -> obj is Object obj
# 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()
# Convenient shorthand for the different types of `onMessage` methods available in the chrome
# API.
# This also supports the old `onRequest` variations for backwards compatibility.
onMessage: (type = 'extension', external, args...) ->
base = chrome[type]
base = chrome.extension if not base and type is 'runtime'
base = if external
base.onMessageExternal or base.onRequestExternal
else
base.onMessage or base.onRequest
base.addListener args...
# 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? then 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
# Convenient shorthand for the different types of `sendMessage` methods available in the chrome
# API.
# This also supports the old `sendRequest` variations for backwards compatibility.
sendMessage: (type = 'extension', args...) ->
base = chrome[type]
base = chrome.extension if not base and type is 'runtime'
(base.sendMessage or base.sendRequest).apply base, args
# 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
# Retrieve the understable type name for an object.
type: (obj) ->
if obj? then typeMap[Object::toString.call obj] or 'object' else String obj
# 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 | 212268 | # [iOrder](http://neocotic.com/iOrder)
# (c) 2013 <NAME>
# Freely distributable under the MIT license.
# For all details and documentation:
# <http://neocotic.com/iOrder>
# 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 = {}
# Map of class names to understable types.
typeMap = {}
# Populate the type map for all classes.
[
'Boolean'
'Number'
'String'
'Function'
'Array'
'Date'
'RegExp'
'Object'
].forEach (name) ->
typeMap["[object #{name}]"] = name.toLowerCase()
# Utilities setup
# ---------------
utils = window.utils = new class Utils extends Class
# Public functions
# ----------------
# Create a clone of an object.
clone: (obj, deep) ->
return obj unless @isObject obj
return obj.slice() if @isArray obj
copy = {}
for own key, value of obj
copy[key] = if deep then @clone value, yes else value
copy
# Indicate whether an object is an array.
isArray: Array.isArray or (obj) -> 'array' is @type obj
# Indicate whether an object is an object.
isObject: (obj) -> obj is Object obj
# 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()
# Convenient shorthand for the different types of `onMessage` methods available in the chrome
# API.
# This also supports the old `onRequest` variations for backwards compatibility.
onMessage: (type = 'extension', external, args...) ->
base = chrome[type]
base = chrome.extension if not base and type is 'runtime'
base = if external
base.onMessageExternal or base.onRequestExternal
else
base.onMessage or base.onRequest
base.addListener args...
# 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? then 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
# Convenient shorthand for the different types of `sendMessage` methods available in the chrome
# API.
# This also supports the old `sendRequest` variations for backwards compatibility.
sendMessage: (type = 'extension', args...) ->
base = chrome[type]
base = chrome.extension if not base and type is 'runtime'
(base.sendMessage or base.sendRequest).apply base, args
# 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
# Retrieve the understable type name for an object.
type: (obj) ->
if obj? then typeMap[Object::toString.call obj] or 'object' else String obj
# 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 | true | # [iOrder](http://neocotic.com/iOrder)
# (c) 2013 PI:NAME:<NAME>END_PI
# Freely distributable under the MIT license.
# For all details and documentation:
# <http://neocotic.com/iOrder>
# 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 = {}
# Map of class names to understable types.
typeMap = {}
# Populate the type map for all classes.
[
'Boolean'
'Number'
'String'
'Function'
'Array'
'Date'
'RegExp'
'Object'
].forEach (name) ->
typeMap["[object #{name}]"] = name.toLowerCase()
# Utilities setup
# ---------------
utils = window.utils = new class Utils extends Class
# Public functions
# ----------------
# Create a clone of an object.
clone: (obj, deep) ->
return obj unless @isObject obj
return obj.slice() if @isArray obj
copy = {}
for own key, value of obj
copy[key] = if deep then @clone value, yes else value
copy
# Indicate whether an object is an array.
isArray: Array.isArray or (obj) -> 'array' is @type obj
# Indicate whether an object is an object.
isObject: (obj) -> obj is Object obj
# 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()
# Convenient shorthand for the different types of `onMessage` methods available in the chrome
# API.
# This also supports the old `onRequest` variations for backwards compatibility.
onMessage: (type = 'extension', external, args...) ->
base = chrome[type]
base = chrome.extension if not base and type is 'runtime'
base = if external
base.onMessageExternal or base.onRequestExternal
else
base.onMessage or base.onRequest
base.addListener args...
# 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? then 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
# Convenient shorthand for the different types of `sendMessage` methods available in the chrome
# API.
# This also supports the old `sendRequest` variations for backwards compatibility.
sendMessage: (type = 'extension', args...) ->
base = chrome[type]
base = chrome.extension if not base and type is 'runtime'
(base.sendMessage or base.sendRequest).apply base, args
# 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
# Retrieve the understable type name for an object.
type: (obj) ->
if obj? then typeMap[Object::toString.call obj] or 'object' else String obj
# 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 |
[
{
"context": "###\n(c) 2011 Jan Monschke\nv1.1\nbackbone-couchdb.js is licensed under the MI",
"end": 25,
"score": 0.9997682571411133,
"start": 13,
"tag": "NAME",
"value": "Jan Monschke"
}
] | _attachments/js-libraries/backbone-couchdb.coffee | chrisekelley/coconut-kiwi-demo | 2 | ###
(c) 2011 Jan Monschke
v1.1
backbone-couchdb.js is licensed under the MIT license.
###
Backbone.couch_connector = con =
# some default config values for the database connections
config :
db_name : "backbone_connect"
ddoc_name : "backbone_example"
view_name : "byCollection"
list_name : null
# if true, all Collections will have the _changes feed enabled
global_changes : false
# change the databse base_url to be able to fetch from a remote couchdb
base_url : null
# some helper methods for the connector
helpers :
# returns a string representing the collection (needed for the "collection"-field)
extract_collection_name : (model) ->
throw new Error("No model has been passed") unless model?
return "" unless ((model.collection? and model.collection.url?) or model.url?)
if model.url?
_name = if _.isFunction(model.url) then model.url() else model.url
else
_name = if _.isFunction(model.collection.url) then model.collection.url() else model.collection.url
# remove the / at the beginning
_name = _name.slice(1, _name.length) if _name[0] == "/"
# jquery.couch.js adds the id itself, so we delete the id if it is in the url.
# "collection/:id" -> "collection"
_splitted = _name.split "/"
_name = if _splitted.length > 0 then _splitted[0] else _name
_name = _name.replace "/", ""
_name
# creates a database instance from the
make_db : ->
db = $.couch.db con.config.db_name
if con.config.base_url?
db.uri = "#{con.config.base_url}/#{con.config.db_name}/";
db
# calls either the read method for collecions or models
read : (model, opts) ->
if model.models
con.read_collection model, opts
else
con.read_model model, opts
# Reads all docs of a collection based on the byCollection view or a custom view specified by the collection
read_collection : (coll, opts) ->
_view = @config.view_name
_ddoc = @config.ddoc_name
_list = @config.list_name
keys = [@helpers.extract_collection_name coll]
if coll.db?
coll.listen_to_changes() if coll.db.changes or @config.global_changes
if coll.db.view?
_view = coll.db.view
if coll.db.ddoc?
_ddoc = coll.db.ddoc
if coll.db.keys?
keys = coll.db.keys
if coll.db.list?
_list = coll.db.list
_opts =
keys : keys
success : (data) =>
_temp = []
for doc in data.rows
if doc.value then _temp.push doc.value else _temp.push doc.doc
opts.success _temp
opts.complete()
error : (status, error, reason) ->
res =
status: status
error: error
reason: reason
opts.error res
opts.complete res
# support view querying opts http://wiki.apache.org/couchdb/HTTP_view_API
view_options = [
"key"
"keys"
"startkey"
"startkey_docid"
"endkey"
"endkey_docid"
"limit"
"stale"
"descending"
"skip"
"group"
"group_level"
"reduce"
"include_docs"
"inclusive_end"
"update_seq"
]
for option in view_options
if opts[option]?
_opts[option] = opts[option]
# delete keys if a custom view is requested but no custom keys
if coll.db? and coll.db.view? and not coll.db.keys?
delete _opts.keys
if _list
@helpers.make_db().list "#{_ddoc}/#{_list}", "#{_view}", _opts
else
@helpers.make_db().view "#{_ddoc}/#{_view}", _opts
# Reads a model from the couchdb by it's ID
read_model : (model, opts) ->
throw new Error("The model has no id property, so it can't get fetched from the database") unless model.id
@helpers.make_db().openDoc model.id,
success : (doc) ->
opts.success(doc)
opts.complete()
error : (status, error, reason) ->
res =
status: status
error: error
reason: reason
opts.error res
opts.complete res
# Creates a model in the db
create : (model, opts) ->
vals = model.toJSON()
coll = @helpers.extract_collection_name model
vals.collection = coll if coll.length > 0
@helpers.make_db().saveDoc vals,
success : (doc) ->
opts.success
_id : doc.id
_rev : doc.rev
opts.complete()
error : (status, error, reason) ->
res =
status: status
error: error
reason: reason
opts.error res
opts.complete res
# jquery.couch.js uses the same method for updating as it uses for creating a document, so we can use the `create` method here. ###
update : (model, opts) ->
@create(model, opts)
# Deletes a model from the db
del : (model, opts) ->
@helpers.make_db().removeDoc model.toJSON(),
success : ->
opts.success()
error : (nr, req, e) ->
if e == "deleted"
# The doc does no longer exist on the server
opts.success()
opts.complete()
else
res =
status: status
error: error
reason: reason
opts.error res
opts.complete res
# Overriding the sync method here to make the connector work ###
Backbone.sync = (method, model, opts) ->
opts.success ?= ->
opts.error ?= ->
opts.complete ?= ->
switch method
when "read" then con.read model, opts
when "create" then con.create model, opts
when "update" then con.update model, opts
when "delete" then con.del model, opts
class Backbone.Model extends Backbone.Model
# change the idAttribute since CouchDB uses _id
idAttribute : "_id"
clone : ->
new_model = new @constructor(@)
# remove _id and _rev attributes on the cloned model object to have a **really** new, unsaved model object.
# _id and _rev only exist on objects that have been saved, so check for existence is needed.
delete new_model.attributes._id if new_model.attributes._id
delete new_model.attributes._rev if new_model.attributes._rev
new_model
# Adds some more methods to Collections that are needed for the connector ###
class Backbone.Collection extends Backbone.Collection
model : Backbone.Model
initialize : ->
@listen_to_changes() if !@_db_changes_enabled && ((@db and @db.changes) or con.config.global_changes)
# Manually start listening to real time updates
listen_to_changes : ->
# don't enable changes feed a second time
unless @_db_changes_enabled
@_db_changes_enabled = true
@_db_inst = con.helpers.make_db() unless @_db_inst
@_db_inst.info
"success" : @_db_prepared_for_changes
# Stop listening to real time updates
stop_changes : ->
@_db_changes_enabled = false
if @_db_changes_handler?
@_db_changes_handler.stop()
@_db_changes_handler = null
_db_prepared_for_changes : (data) =>
@_db_update_seq = data.update_seq || 0
opts =
include_docs : true
collection : con.helpers.extract_collection_name(@)
filter : "#{con.config.ddoc_name}/by_collection"
_.extend opts, @db
_.defer =>
@_db_changes_handler = @_db_inst.changes(@_db_update_seq, opts)
@_db_changes_handler.onChange @._db_on_change
_db_on_change : (changes) =>
for _doc in changes.results
obj = @get _doc.id
# test if collection contains the doc, if not, we add it to the collection
if obj?
# remove from collection if doc has been deleted on the server
if _doc.deleted
@remove obj
else
# set new values if _revs are not the same
obj.set _doc.doc unless obj.get("_rev") == _doc.doc._rev
else
@add _doc.doc if !_doc.deleted
| 84569 | ###
(c) 2011 <NAME>
v1.1
backbone-couchdb.js is licensed under the MIT license.
###
Backbone.couch_connector = con =
# some default config values for the database connections
config :
db_name : "backbone_connect"
ddoc_name : "backbone_example"
view_name : "byCollection"
list_name : null
# if true, all Collections will have the _changes feed enabled
global_changes : false
# change the databse base_url to be able to fetch from a remote couchdb
base_url : null
# some helper methods for the connector
helpers :
# returns a string representing the collection (needed for the "collection"-field)
extract_collection_name : (model) ->
throw new Error("No model has been passed") unless model?
return "" unless ((model.collection? and model.collection.url?) or model.url?)
if model.url?
_name = if _.isFunction(model.url) then model.url() else model.url
else
_name = if _.isFunction(model.collection.url) then model.collection.url() else model.collection.url
# remove the / at the beginning
_name = _name.slice(1, _name.length) if _name[0] == "/"
# jquery.couch.js adds the id itself, so we delete the id if it is in the url.
# "collection/:id" -> "collection"
_splitted = _name.split "/"
_name = if _splitted.length > 0 then _splitted[0] else _name
_name = _name.replace "/", ""
_name
# creates a database instance from the
make_db : ->
db = $.couch.db con.config.db_name
if con.config.base_url?
db.uri = "#{con.config.base_url}/#{con.config.db_name}/";
db
# calls either the read method for collecions or models
read : (model, opts) ->
if model.models
con.read_collection model, opts
else
con.read_model model, opts
# Reads all docs of a collection based on the byCollection view or a custom view specified by the collection
read_collection : (coll, opts) ->
_view = @config.view_name
_ddoc = @config.ddoc_name
_list = @config.list_name
keys = [@helpers.extract_collection_name coll]
if coll.db?
coll.listen_to_changes() if coll.db.changes or @config.global_changes
if coll.db.view?
_view = coll.db.view
if coll.db.ddoc?
_ddoc = coll.db.ddoc
if coll.db.keys?
keys = coll.db.keys
if coll.db.list?
_list = coll.db.list
_opts =
keys : keys
success : (data) =>
_temp = []
for doc in data.rows
if doc.value then _temp.push doc.value else _temp.push doc.doc
opts.success _temp
opts.complete()
error : (status, error, reason) ->
res =
status: status
error: error
reason: reason
opts.error res
opts.complete res
# support view querying opts http://wiki.apache.org/couchdb/HTTP_view_API
view_options = [
"key"
"keys"
"startkey"
"startkey_docid"
"endkey"
"endkey_docid"
"limit"
"stale"
"descending"
"skip"
"group"
"group_level"
"reduce"
"include_docs"
"inclusive_end"
"update_seq"
]
for option in view_options
if opts[option]?
_opts[option] = opts[option]
# delete keys if a custom view is requested but no custom keys
if coll.db? and coll.db.view? and not coll.db.keys?
delete _opts.keys
if _list
@helpers.make_db().list "#{_ddoc}/#{_list}", "#{_view}", _opts
else
@helpers.make_db().view "#{_ddoc}/#{_view}", _opts
# Reads a model from the couchdb by it's ID
read_model : (model, opts) ->
throw new Error("The model has no id property, so it can't get fetched from the database") unless model.id
@helpers.make_db().openDoc model.id,
success : (doc) ->
opts.success(doc)
opts.complete()
error : (status, error, reason) ->
res =
status: status
error: error
reason: reason
opts.error res
opts.complete res
# Creates a model in the db
create : (model, opts) ->
vals = model.toJSON()
coll = @helpers.extract_collection_name model
vals.collection = coll if coll.length > 0
@helpers.make_db().saveDoc vals,
success : (doc) ->
opts.success
_id : doc.id
_rev : doc.rev
opts.complete()
error : (status, error, reason) ->
res =
status: status
error: error
reason: reason
opts.error res
opts.complete res
# jquery.couch.js uses the same method for updating as it uses for creating a document, so we can use the `create` method here. ###
update : (model, opts) ->
@create(model, opts)
# Deletes a model from the db
del : (model, opts) ->
@helpers.make_db().removeDoc model.toJSON(),
success : ->
opts.success()
error : (nr, req, e) ->
if e == "deleted"
# The doc does no longer exist on the server
opts.success()
opts.complete()
else
res =
status: status
error: error
reason: reason
opts.error res
opts.complete res
# Overriding the sync method here to make the connector work ###
Backbone.sync = (method, model, opts) ->
opts.success ?= ->
opts.error ?= ->
opts.complete ?= ->
switch method
when "read" then con.read model, opts
when "create" then con.create model, opts
when "update" then con.update model, opts
when "delete" then con.del model, opts
class Backbone.Model extends Backbone.Model
# change the idAttribute since CouchDB uses _id
idAttribute : "_id"
clone : ->
new_model = new @constructor(@)
# remove _id and _rev attributes on the cloned model object to have a **really** new, unsaved model object.
# _id and _rev only exist on objects that have been saved, so check for existence is needed.
delete new_model.attributes._id if new_model.attributes._id
delete new_model.attributes._rev if new_model.attributes._rev
new_model
# Adds some more methods to Collections that are needed for the connector ###
class Backbone.Collection extends Backbone.Collection
model : Backbone.Model
initialize : ->
@listen_to_changes() if !@_db_changes_enabled && ((@db and @db.changes) or con.config.global_changes)
# Manually start listening to real time updates
listen_to_changes : ->
# don't enable changes feed a second time
unless @_db_changes_enabled
@_db_changes_enabled = true
@_db_inst = con.helpers.make_db() unless @_db_inst
@_db_inst.info
"success" : @_db_prepared_for_changes
# Stop listening to real time updates
stop_changes : ->
@_db_changes_enabled = false
if @_db_changes_handler?
@_db_changes_handler.stop()
@_db_changes_handler = null
_db_prepared_for_changes : (data) =>
@_db_update_seq = data.update_seq || 0
opts =
include_docs : true
collection : con.helpers.extract_collection_name(@)
filter : "#{con.config.ddoc_name}/by_collection"
_.extend opts, @db
_.defer =>
@_db_changes_handler = @_db_inst.changes(@_db_update_seq, opts)
@_db_changes_handler.onChange @._db_on_change
_db_on_change : (changes) =>
for _doc in changes.results
obj = @get _doc.id
# test if collection contains the doc, if not, we add it to the collection
if obj?
# remove from collection if doc has been deleted on the server
if _doc.deleted
@remove obj
else
# set new values if _revs are not the same
obj.set _doc.doc unless obj.get("_rev") == _doc.doc._rev
else
@add _doc.doc if !_doc.deleted
| true | ###
(c) 2011 PI:NAME:<NAME>END_PI
v1.1
backbone-couchdb.js is licensed under the MIT license.
###
Backbone.couch_connector = con =
# some default config values for the database connections
config :
db_name : "backbone_connect"
ddoc_name : "backbone_example"
view_name : "byCollection"
list_name : null
# if true, all Collections will have the _changes feed enabled
global_changes : false
# change the databse base_url to be able to fetch from a remote couchdb
base_url : null
# some helper methods for the connector
helpers :
# returns a string representing the collection (needed for the "collection"-field)
extract_collection_name : (model) ->
throw new Error("No model has been passed") unless model?
return "" unless ((model.collection? and model.collection.url?) or model.url?)
if model.url?
_name = if _.isFunction(model.url) then model.url() else model.url
else
_name = if _.isFunction(model.collection.url) then model.collection.url() else model.collection.url
# remove the / at the beginning
_name = _name.slice(1, _name.length) if _name[0] == "/"
# jquery.couch.js adds the id itself, so we delete the id if it is in the url.
# "collection/:id" -> "collection"
_splitted = _name.split "/"
_name = if _splitted.length > 0 then _splitted[0] else _name
_name = _name.replace "/", ""
_name
# creates a database instance from the
make_db : ->
db = $.couch.db con.config.db_name
if con.config.base_url?
db.uri = "#{con.config.base_url}/#{con.config.db_name}/";
db
# calls either the read method for collecions or models
read : (model, opts) ->
if model.models
con.read_collection model, opts
else
con.read_model model, opts
# Reads all docs of a collection based on the byCollection view or a custom view specified by the collection
read_collection : (coll, opts) ->
_view = @config.view_name
_ddoc = @config.ddoc_name
_list = @config.list_name
keys = [@helpers.extract_collection_name coll]
if coll.db?
coll.listen_to_changes() if coll.db.changes or @config.global_changes
if coll.db.view?
_view = coll.db.view
if coll.db.ddoc?
_ddoc = coll.db.ddoc
if coll.db.keys?
keys = coll.db.keys
if coll.db.list?
_list = coll.db.list
_opts =
keys : keys
success : (data) =>
_temp = []
for doc in data.rows
if doc.value then _temp.push doc.value else _temp.push doc.doc
opts.success _temp
opts.complete()
error : (status, error, reason) ->
res =
status: status
error: error
reason: reason
opts.error res
opts.complete res
# support view querying opts http://wiki.apache.org/couchdb/HTTP_view_API
view_options = [
"key"
"keys"
"startkey"
"startkey_docid"
"endkey"
"endkey_docid"
"limit"
"stale"
"descending"
"skip"
"group"
"group_level"
"reduce"
"include_docs"
"inclusive_end"
"update_seq"
]
for option in view_options
if opts[option]?
_opts[option] = opts[option]
# delete keys if a custom view is requested but no custom keys
if coll.db? and coll.db.view? and not coll.db.keys?
delete _opts.keys
if _list
@helpers.make_db().list "#{_ddoc}/#{_list}", "#{_view}", _opts
else
@helpers.make_db().view "#{_ddoc}/#{_view}", _opts
# Reads a model from the couchdb by it's ID
read_model : (model, opts) ->
throw new Error("The model has no id property, so it can't get fetched from the database") unless model.id
@helpers.make_db().openDoc model.id,
success : (doc) ->
opts.success(doc)
opts.complete()
error : (status, error, reason) ->
res =
status: status
error: error
reason: reason
opts.error res
opts.complete res
# Creates a model in the db
create : (model, opts) ->
vals = model.toJSON()
coll = @helpers.extract_collection_name model
vals.collection = coll if coll.length > 0
@helpers.make_db().saveDoc vals,
success : (doc) ->
opts.success
_id : doc.id
_rev : doc.rev
opts.complete()
error : (status, error, reason) ->
res =
status: status
error: error
reason: reason
opts.error res
opts.complete res
# jquery.couch.js uses the same method for updating as it uses for creating a document, so we can use the `create` method here. ###
update : (model, opts) ->
@create(model, opts)
# Deletes a model from the db
del : (model, opts) ->
@helpers.make_db().removeDoc model.toJSON(),
success : ->
opts.success()
error : (nr, req, e) ->
if e == "deleted"
# The doc does no longer exist on the server
opts.success()
opts.complete()
else
res =
status: status
error: error
reason: reason
opts.error res
opts.complete res
# Overriding the sync method here to make the connector work ###
Backbone.sync = (method, model, opts) ->
opts.success ?= ->
opts.error ?= ->
opts.complete ?= ->
switch method
when "read" then con.read model, opts
when "create" then con.create model, opts
when "update" then con.update model, opts
when "delete" then con.del model, opts
class Backbone.Model extends Backbone.Model
# change the idAttribute since CouchDB uses _id
idAttribute : "_id"
clone : ->
new_model = new @constructor(@)
# remove _id and _rev attributes on the cloned model object to have a **really** new, unsaved model object.
# _id and _rev only exist on objects that have been saved, so check for existence is needed.
delete new_model.attributes._id if new_model.attributes._id
delete new_model.attributes._rev if new_model.attributes._rev
new_model
# Adds some more methods to Collections that are needed for the connector ###
class Backbone.Collection extends Backbone.Collection
model : Backbone.Model
initialize : ->
@listen_to_changes() if !@_db_changes_enabled && ((@db and @db.changes) or con.config.global_changes)
# Manually start listening to real time updates
listen_to_changes : ->
# don't enable changes feed a second time
unless @_db_changes_enabled
@_db_changes_enabled = true
@_db_inst = con.helpers.make_db() unless @_db_inst
@_db_inst.info
"success" : @_db_prepared_for_changes
# Stop listening to real time updates
stop_changes : ->
@_db_changes_enabled = false
if @_db_changes_handler?
@_db_changes_handler.stop()
@_db_changes_handler = null
_db_prepared_for_changes : (data) =>
@_db_update_seq = data.update_seq || 0
opts =
include_docs : true
collection : con.helpers.extract_collection_name(@)
filter : "#{con.config.ddoc_name}/by_collection"
_.extend opts, @db
_.defer =>
@_db_changes_handler = @_db_inst.changes(@_db_update_seq, opts)
@_db_changes_handler.onChange @._db_on_change
_db_on_change : (changes) =>
for _doc in changes.results
obj = @get _doc.id
# test if collection contains the doc, if not, we add it to the collection
if obj?
# remove from collection if doc has been deleted on the server
if _doc.deleted
@remove obj
else
# set new values if _revs are not the same
obj.set _doc.doc unless obj.get("_rev") == _doc.doc._rev
else
@add _doc.doc if !_doc.deleted
|
[
{
"context": "oGLib\n# Module | Stat Methods\n# Author | Sherif Emabrak\n# Description | The complete method returns the s",
"end": 163,
"score": 0.999874472618103,
"start": 149,
"tag": "NAME",
"value": "Sherif Emabrak"
}
] | src/lib/statistics/link/complete.coffee | Sherif-Embarak/gp-test | 0 | # ------------------------------------------------------------------------------
# Project | GoGLib
# Module | Stat Methods
# Author | Sherif Emabrak
# Description | The complete method returns the set of edges in a complete graph for a set of nodes.
# ------------------------------------------------------------------------------
complete = () -> | 178239 | # ------------------------------------------------------------------------------
# Project | GoGLib
# Module | Stat Methods
# Author | <NAME>
# Description | The complete method returns the set of edges in a complete graph for a set of nodes.
# ------------------------------------------------------------------------------
complete = () -> | true | # ------------------------------------------------------------------------------
# Project | GoGLib
# Module | Stat Methods
# Author | PI:NAME:<NAME>END_PI
# Description | The complete method returns the set of edges in a complete graph for a set of nodes.
# ------------------------------------------------------------------------------
complete = () -> |
[
{
"context": "esting: process.env.TESTING || false\n secret: '8rC4HA3Zi9SVKazl98Z3RyrWuAKykgb5RNuOKbg3PtL'\n email: 'YOUR@EMAIL.COM' # Admin Email Addres",
"end": 427,
"score": 0.9977811574935913,
"start": 384,
"tag": "KEY",
"value": "8rC4HA3Zi9SVKazl98Z3RyrWuAKykgb5RNuOKbg3PtL"
},
... | lib-coffee/config/app.coffee | chrisspiegl/DigitalOceanStreak | 0 | ###
|------------------------------------------------------------------------------
| App Defaults
|------------------------------------------------------------------------------
###
module.exports =
name: 'DigitalOceanStreak'
version: require('../../package.json').version
frontEndVersion: '0.0.0'
apiVersion: 0
testing: process.env.TESTING || false
secret: '8rC4HA3Zi9SVKazl98Z3RyrWuAKykgb5RNuOKbg3PtL'
email: 'YOUR@EMAIL.COM' # Admin Email Address
DOSURL: 'https://www.digitaloceanstatus.com/history'
userAgent: 'DigitalOceanStreak Analyzer (Site: http://dos.chrissp.com) (Contact: chris@chrissp.com)'
| 154735 | ###
|------------------------------------------------------------------------------
| App Defaults
|------------------------------------------------------------------------------
###
module.exports =
name: 'DigitalOceanStreak'
version: require('../../package.json').version
frontEndVersion: '0.0.0'
apiVersion: 0
testing: process.env.TESTING || false
secret: '<KEY>'
email: '<EMAIL>' # Admin Email Address
DOSURL: 'https://www.digitaloceanstatus.com/history'
userAgent: 'DigitalOceanStreak Analyzer (Site: http://dos.chrissp.com) (Contact: <EMAIL>)'
| true | ###
|------------------------------------------------------------------------------
| App Defaults
|------------------------------------------------------------------------------
###
module.exports =
name: 'DigitalOceanStreak'
version: require('../../package.json').version
frontEndVersion: '0.0.0'
apiVersion: 0
testing: process.env.TESTING || false
secret: 'PI:KEY:<KEY>END_PI'
email: 'PI:EMAIL:<EMAIL>END_PI' # Admin Email Address
DOSURL: 'https://www.digitaloceanstatus.com/history'
userAgent: 'DigitalOceanStreak Analyzer (Site: http://dos.chrissp.com) (Contact: PI:EMAIL:<EMAIL>END_PI)'
|
[
{
"context": "b0403cdc842f4c60f8d000\"\n personalAccessToken: \"50ed2b8528cdca8c48567d3df07c19a3dd173bfd\"\n \"terminal-plus\":\n core:\n autoRunComman",
"end": 2545,
"score": 0.9356907606124878,
"start": 2505,
"tag": "KEY",
"value": "50ed2b8528cdca8c48567d3df07c19a3dd173bfd"
}... | apps/atom/config.cson | huynle/dotfiles | 1 | "*":
"atom-beautify":
general:
_analyticsUserId: "85846eb4-8d05-434e-b61f-f27a476282ca"
"autocomplete-python": {}
"autohide-tree-view":
showDelay: 100
triggerAreaSize: 1
build:
saveOnBuild: true
scrollOnError: true
core:
audioBeep: false
autoHideMenuBar: true
disabledPackages: [
"styleguide"
"language-gfm"
"open-on-github"
"timecop"
"package-generator"
"terminal-plus"
"highlight-selected"
"linter"
"minimap"
"minimap-autohide"
"markdown-preview-plus"
"sync-settings"
]
ignoredNames: [
".git"
".hg"
".svn"
".DS_Store"
"._*"
"Thumbs.db"
".pioenvs"
".piolibdeps"
".clang_complete"
".gcc-flags.json"
]
openEmptyEditorOnStart: false
packagesWithKeymapsDisabled: [
"tab-switcher"
]
projectHome: "C:\\Users\\hle\\Documents\\Projects"
telemetryConsent: "no"
themes: [
"one-dark-ui"
"base16-tomorrow-dark-theme"
]
editor:
preferredLineLength: 100
showIndentGuide: true
softTabs: false
softWrap: true
softWrapAtPreferredLineLength: true
tabType: "soft"
"exception-reporting":
userId: "827766e1-025a-8847-3bff-62a6efc42286"
"file-icons":
coloured: false
"git-plus":
general:
_analyticsUserId: "9ba89964-ea86-4aa3-8cf1-255e2919bfd2"
linter: {}
"linter-markdown":
detectIgnore: false
"linter-ui-default":
useBusySignal: false
"markdown-preview-plus": {}
"markdown-writer":
fileExtension: ".md"
minimap:
plugins:
"minimap-autohide": true
"minimap-autohideDecorationsZIndex": 0
"one-o-eight-syntax":
backgroundVariant: "Dark"
"platformio-ide":
advanced:
showPlatformIOFiles: true
showHomeScreen: false
"platformio-ide-terminal":
core: {}
toggles:
autoClose: true
"project-manager":
alwaysOpenInSameWindow: true
includeGitRepositories: true
prettifyTitle: false
savePathsRelativeToHome: true
sortBy: "last modified"
"python-debugger": {}
"spell-check":
grammars: [
"source.asciidoc"
"source.gfm"
"text.git-commit"
"text.plain"
"text.plain.null-grammar"
"text.md"
]
"sync-settings":
_analyticsUserId: "e8ab0496-ed5d-40df-91bf-48926be1aa7a"
_lastBackupHash: "477d8db31b28f25f8eb26584e930988ac60a166a"
gistId: "177b31109db0403cdc842f4c60f8d000"
personalAccessToken: "50ed2b8528cdca8c48567d3df07c19a3dd173bfd"
"terminal-plus":
core:
autoRunCommand: "source ~/.bashrc"
"tool-bar":
fullWidth: false
iconSize: "16px"
position: "Left"
"tree-view": {}
welcome:
showOnStartup: false
| 188576 | "*":
"atom-beautify":
general:
_analyticsUserId: "85846eb4-8d05-434e-b61f-f27a476282ca"
"autocomplete-python": {}
"autohide-tree-view":
showDelay: 100
triggerAreaSize: 1
build:
saveOnBuild: true
scrollOnError: true
core:
audioBeep: false
autoHideMenuBar: true
disabledPackages: [
"styleguide"
"language-gfm"
"open-on-github"
"timecop"
"package-generator"
"terminal-plus"
"highlight-selected"
"linter"
"minimap"
"minimap-autohide"
"markdown-preview-plus"
"sync-settings"
]
ignoredNames: [
".git"
".hg"
".svn"
".DS_Store"
"._*"
"Thumbs.db"
".pioenvs"
".piolibdeps"
".clang_complete"
".gcc-flags.json"
]
openEmptyEditorOnStart: false
packagesWithKeymapsDisabled: [
"tab-switcher"
]
projectHome: "C:\\Users\\hle\\Documents\\Projects"
telemetryConsent: "no"
themes: [
"one-dark-ui"
"base16-tomorrow-dark-theme"
]
editor:
preferredLineLength: 100
showIndentGuide: true
softTabs: false
softWrap: true
softWrapAtPreferredLineLength: true
tabType: "soft"
"exception-reporting":
userId: "827766e1-025a-8847-3bff-62a6efc42286"
"file-icons":
coloured: false
"git-plus":
general:
_analyticsUserId: "9ba89964-ea86-4aa3-8cf1-255e2919bfd2"
linter: {}
"linter-markdown":
detectIgnore: false
"linter-ui-default":
useBusySignal: false
"markdown-preview-plus": {}
"markdown-writer":
fileExtension: ".md"
minimap:
plugins:
"minimap-autohide": true
"minimap-autohideDecorationsZIndex": 0
"one-o-eight-syntax":
backgroundVariant: "Dark"
"platformio-ide":
advanced:
showPlatformIOFiles: true
showHomeScreen: false
"platformio-ide-terminal":
core: {}
toggles:
autoClose: true
"project-manager":
alwaysOpenInSameWindow: true
includeGitRepositories: true
prettifyTitle: false
savePathsRelativeToHome: true
sortBy: "last modified"
"python-debugger": {}
"spell-check":
grammars: [
"source.asciidoc"
"source.gfm"
"text.git-commit"
"text.plain"
"text.plain.null-grammar"
"text.md"
]
"sync-settings":
_analyticsUserId: "e8ab0496-ed5d-40df-91bf-48926be1aa7a"
_lastBackupHash: "477d8db31b28f25f8eb26584e930988ac60a166a"
gistId: "177b31109db0403cdc842f4c60f8d000"
personalAccessToken: "<KEY>"
"terminal-plus":
core:
autoRunCommand: "source ~/.bashrc"
"tool-bar":
fullWidth: false
iconSize: "16px"
position: "Left"
"tree-view": {}
welcome:
showOnStartup: false
| true | "*":
"atom-beautify":
general:
_analyticsUserId: "85846eb4-8d05-434e-b61f-f27a476282ca"
"autocomplete-python": {}
"autohide-tree-view":
showDelay: 100
triggerAreaSize: 1
build:
saveOnBuild: true
scrollOnError: true
core:
audioBeep: false
autoHideMenuBar: true
disabledPackages: [
"styleguide"
"language-gfm"
"open-on-github"
"timecop"
"package-generator"
"terminal-plus"
"highlight-selected"
"linter"
"minimap"
"minimap-autohide"
"markdown-preview-plus"
"sync-settings"
]
ignoredNames: [
".git"
".hg"
".svn"
".DS_Store"
"._*"
"Thumbs.db"
".pioenvs"
".piolibdeps"
".clang_complete"
".gcc-flags.json"
]
openEmptyEditorOnStart: false
packagesWithKeymapsDisabled: [
"tab-switcher"
]
projectHome: "C:\\Users\\hle\\Documents\\Projects"
telemetryConsent: "no"
themes: [
"one-dark-ui"
"base16-tomorrow-dark-theme"
]
editor:
preferredLineLength: 100
showIndentGuide: true
softTabs: false
softWrap: true
softWrapAtPreferredLineLength: true
tabType: "soft"
"exception-reporting":
userId: "827766e1-025a-8847-3bff-62a6efc42286"
"file-icons":
coloured: false
"git-plus":
general:
_analyticsUserId: "9ba89964-ea86-4aa3-8cf1-255e2919bfd2"
linter: {}
"linter-markdown":
detectIgnore: false
"linter-ui-default":
useBusySignal: false
"markdown-preview-plus": {}
"markdown-writer":
fileExtension: ".md"
minimap:
plugins:
"minimap-autohide": true
"minimap-autohideDecorationsZIndex": 0
"one-o-eight-syntax":
backgroundVariant: "Dark"
"platformio-ide":
advanced:
showPlatformIOFiles: true
showHomeScreen: false
"platformio-ide-terminal":
core: {}
toggles:
autoClose: true
"project-manager":
alwaysOpenInSameWindow: true
includeGitRepositories: true
prettifyTitle: false
savePathsRelativeToHome: true
sortBy: "last modified"
"python-debugger": {}
"spell-check":
grammars: [
"source.asciidoc"
"source.gfm"
"text.git-commit"
"text.plain"
"text.plain.null-grammar"
"text.md"
]
"sync-settings":
_analyticsUserId: "e8ab0496-ed5d-40df-91bf-48926be1aa7a"
_lastBackupHash: "477d8db31b28f25f8eb26584e930988ac60a166a"
gistId: "177b31109db0403cdc842f4c60f8d000"
personalAccessToken: "PI:KEY:<KEY>END_PI"
"terminal-plus":
core:
autoRunCommand: "source ~/.bashrc"
"tool-bar":
fullWidth: false
iconSize: "16px"
position: "Left"
"tree-view": {}
welcome:
showOnStartup: false
|
[
{
"context": ":\n\t\t\t\t\toperand: \"eq\"\n\t\t\t\t\tvalue: 23\n\n\t\t, { name: \"user\" } )\n\n\t\tuserNullValidator = new Schema(\n\t\t\t\"flagA",
"end": 2247,
"score": 0.8386573791503906,
"start": 2243,
"tag": "USERNAME",
"value": "user"
},
{
"context": "\n\t\tit \"success\", ( d... | _src/test/main.coffee | mpneuried/obj-schema | 4 | should = require('should')
_map = require('lodash/map')
_difference = require('lodash/difference')
Schema = require( "../." )
userValidator = null
userNullValidator = null
settingsValidator = new Schema(
"a":
type: "string"
required: true
"b":
type: "number"
"c":
foreignReq: ["b"]
type: "boolean"
, { name: "settings" } )
describe "OBJ-SCHEMA -", ->
before ( done )->
settingsValidatorArr = new Schema([
key: "a",
type: "string"
required: true
,
key: "b",
type: "number"
], { name: "settings-list" } )
userValidator = new Schema(
"name":
type: "string"
required: true
trim: true
sanitize: true
striphtml: true
check:
operand: ">="
value: 4
"nickname":
type: "string"
check:
operand: "<"
value: 10
"nicknameb":
type: "string"
check:
operand: "<="
value: 10
"type":
type: "string"
check:
operand: "eq"
value: 2
"sex":
type: "string"
regexp: /^(m|w)$/gi
"email":
type: "email"
"age":
type: "number"
default: 42
check:
operand: ">"
value: 0
"money":
type: "number"
check:
operand: "btw"
value: [1000,5000]
"comment":
type: "string"
striphtml: [ "b" ]
"tag":
type: "enum"
values: [ "A", "B", "C" ]
"list":
type: "array"
check:
operand: "btw"
value: [2,4]
"timezone":
type: "timezone"
"settings":
type: "schema"
schema: settingsValidator
"settings_list":
type: "schema"
schema: [
key: "a",
type: "string"
required: true
,
key: "b",
type: "number"
,
key: "sub",
type: "schema"
schema:
sub_a:
type: "string"
required: true
sub_b:
type: "boolean"
required: true
]
"props":
type: "object"
"active":
type: "boolean"
default: true
"flagA":
type: "boolean"
nullAllowed: true
"flagB":
type: "boolean"
"checkA":
type: "number"
nullAllowed: true
check:
operand: "neq"
value: 23
"checkB":
type: "number"
check:
operand: "eq"
value: 23
, { name: "user" } )
userNullValidator = new Schema(
"flagA":
required: true
type: "boolean"
nullAllowed: true
"flagB":
required: true
type: "boolean"
"checkA":
required: true
type: "number"
nullAllowed: true
check:
operand: "neq"
value: 23
"checkB":
required: true
type: "number"
check:
operand: "eq"
value: 23
"settings_list":
required: true
nullAllowed: true
type: "schema"
schema: [
key: "a",
type: "string"
required: true
,
key: "b",
type: "number"
,
key: "sub",
type: "schema"
schema:
sub_a:
type: "string"
required: true
sub_b:
type: "boolean"
required: true
]
, { name: "user-null" } )
done()
return
after ( done )->
# TODO teardown
done()
return
describe 'Main -', ->
it "success", ( done )->
_data =
name: "John"
nickname: "johndoe"
nicknameb: "johndoe"
type: "ab"
email: "john@do.com"
sex: "M"
tag: "A"
list: [1,2,3]
age: 23
timezone: "CET"
settings: { a: "foo", b: 123, c: true }
props: { foo: "bar" }
active: false
money: 1001
checkA: 42
checkB: 23
flagA: false
flagB: true
comment: "a <b>html</b> <i>test</i>"
err = userValidator.validate( _data )
should.not.exist( err )
should.exist( _data.age )
_data.age.should.eql( 23 )
should.exist( _data.active )
_data.active.should.eql( false )
_data.flagA.should.eql( false )
_data.flagB.should.eql( true )
should.exist( _data.comment )
_data.comment.should.eql( "a <b>html</b> test" )
done()
return
it "success cb", ( done )->
_data =
name: "John"
nickname: "johndoe"
nicknameb: "johndoe"
type: "ab"
email: "john@do.com"
sex: "M"
tag: "A"
list: [1,2,3]
age: 23
timezone: "CET"
settings: { a: "foo", b: 123, c: true }
props: { foo: "bar" }
active: false
money: 1001
checkA: 42
checkB: 23
flagA: false
flagB: true
comment: "a <b>html</b> <i>test</i>"
userValidator.validateCb _data, ( err )->
should.not.exist( err )
should.exist( _data.age )
_data.age.should.eql( 23 )
should.exist( _data.active )
_data.active.should.eql( false )
_data.flagA.should.eql( false )
_data.flagB.should.eql( true )
should.exist( _data.comment )
_data.comment.should.eql( "a <b>html</b> test" )
done()
return
return
it "success", ( done )->
_data =
name: "John"
nickname: "johndoe"
nicknameb: "johndoe"
type: "ab"
email: "john@do.com"
sex: "M"
tag: "A"
list: [1,2,3]
age: 23
timezone: "CET"
settings: { a: "foo", b: 123, c: true }
props: { foo: "bar" }
active: false
money: 1001
checkA: 42
checkB: 23
flagA: false
flagB: true
comment: "a <b>html</b> <i>test</i>"
err = userValidator.validateMulti( _data )
should.not.exist( err )
should.exist( _data.age )
_data.age.should.eql( 23 )
should.exist( _data.active )
_data.active.should.eql( false )
_data.flagA.should.eql( false )
_data.flagB.should.eql( true )
should.exist( _data.comment )
_data.comment.should.eql( "a <b>html</b> test" )
done()
return
it "success min", ( done )->
_data = { name: "John" }
err = userValidator.validate( _data )
should.not.exist( err )
should.exist( _data.age )
_data.age.should.eql( 42 )
should.exist( _data.active )
_data.active.should.eql( true )
done()
return
it "missing required", ( done )->
err = userValidator.validate( { email: "john@do.com", age: "23" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_REQUIRED_NAME" )
err.field.should.eql( "name" )
err.type.should.eql( "required" )
err.statusCode.should.eql( 406 )
err.customError.should.eql( true )
err.should.instanceof( Error )
should.exist( err.def )
done()
return
it "invalid type", ( done )->
[ err ] = userValidator.validateMulti( [ { name: "John", email: "john@do.com", age: "23" } ] )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_OBJECT" )
done()
return
it "invalid type", ( done )->
err = userValidator.validate( { name: "John", email: "john@do.com", age: "23" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_NUMBER_AGE" )
err.field.should.eql( "age" )
err.type.should.eql( "number" )
done()
return
it "invalid type cb=true", ( done )->
err = userValidator.validateCb( { name: "John", email: "john@do.com", age: "23" }, true )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_NUMBER_AGE" )
err.field.should.eql( "age" )
err.type.should.eql( "number" )
done()
return
it "invalid type cb=null", ( done )->
return should.throws( ->
userValidator.validateCb( { name: "John", email: "john@do.com", age: "23" }, null )
, ( err )->
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_NUMBER_AGE" )
err.field.should.eql( "age" )
err.type.should.eql( "number" )
done()
return
)
it "invalid email", ( done )->
err = userValidator.validate( { name: "John", email: "johndocom", age: 23 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_EMAIL_EMAIL" )
err.field.should.eql( "email" )
err.type.should.eql( "email" )
done()
return
it "invalid enum", ( done )->
err = userValidator.validate( { name: "John", email: "john@do.com", age: 23, tag: "X" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_ENUM_TAG" )
done()
return
it "invalid timezone", ( done )->
err = userValidator.validate( { name: "John", email: "john@do.com", timezone: "X" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_TIMEZONE_TIMEZONE" )
done()
return
it "invalid timezone", ( done )->
err = userValidator.validate( { name: "John", email: "john@do.com", timezone: "X" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_TIMEZONE_TIMEZONE" )
done()
return
it "invalid subschema type", ( done )->
err = userValidator.validate( { name: "John", email: "john@do.com", settings: { a: "a", b: "b" } } )
should.exist( err )
err.name.should.eql( "EVALIDATION_SETTINGS_NUMBER_B" )
done()
return
it "invalid subschema required", ( done )->
err = userValidator.validate( { name: "John", email: "john@do.com", settings: { b: "b" } } )
should.exist( err )
err.name.should.eql( "EVALIDATION_SETTINGS_REQUIRED_A" )
done()
return
it "invalid subschema required foreignReq", ( done )->
err = userValidator.validate( { name: "John", email: "john@do.com", settings: { a: "x", c: true } } )
should.exist( err )
err.name.should.eql( "EVALIDATION_SETTINGS_REQUIRED_B" )
done()
return
it "invalid object", ( done )->
err = userValidator.validate( { name: "John", email: "john@do.com", props: "foo:bar" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_OBJECT_PROPS" )
done()
return
it "invalid object as array", ( done )->
err = userValidator.validate( { name: "John", email: "john@do.com", props: [ "foo", "bar" ] } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_OBJECT_PROPS" )
done()
return
it "invalid boolean", ( done )->
err = userValidator.validate( { name: "John", email: "john@do.com", active: "NO" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_BOOLEAN_ACTIVE" )
done()
return
it "failing number check", ( done )->
err = userValidator.validate( { name: "John", email: "john@do.com", age: 0 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_CHECK_AGE" )
done()
return
it "failing number check eq", ( done )->
err = userValidator.validate( { name: "John", email: "john@do.com", checkA: 23 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_CHECK_CHECKA" )
done()
return
it "failing number check neq", ( done )->
err = userValidator.validate( { name: "John", email: "john@do.com", checkB: 42 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_CHECK_CHECKB" )
done()
return
it "failing number regex", ( done )->
err = userValidator.validate( { name: "John", sex: "X" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_REGEXP_SEX" )
done()
return
it "failing string length too low", ( done )->
err = userValidator.validate( { name: "Jo", email: "john@do.com", age: 0 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_LENGTH_NAME" )
done()
return
it "failing string length too high (lt)", ( done )->
err = userValidator.validate( { name: "John", nickname: "johntheipsumdo", age: 23 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_LENGTH_NICKNAME" )
err.should.have.property( "def" )
.and.have.property( "check" )
.and.have.property( "value" )
.and.eql( 10 )
done()
return
it "failing string length too high (lte)", ( done )->
err = userValidator.validate( { name: "John", nicknameb: "johntheipsu", age: 23 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_LENGTH_NICKNAMEB" )
err.should.have.property( "def" )
.and.have.property( "check" )
.and.have.property( "value" )
.and.eql( 10 )
done()
return
it "cheching trim and sanitize", ( done )->
data = { name: " John <script>alert(234)</script><b>Doe</b> ", age: 23 }
err = userValidator.validate( data )
should.not.exist( err )
data.name.should.equal( "John Doe" )
done()
return
it "failing string length neq - low", ( done )->
err = userValidator.validate( { name: "John", type: "x", age: 0 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_LENGTH_TYPE" )
done()
return
it "failing string length neq - high", ( done )->
err = userValidator.validate( { name: "John", type: "abc", age: 0 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_LENGTH_TYPE" )
err.type.should.eql( "length" )
done()
return
it "failing with callback", ( done )->
err = userValidator.validateCb { name: "John", type: "abc", age: 0 }, ( err )->
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_LENGTH_TYPE" )
err.type.should.eql( "length" )
done()
return
return
it "failing string", ( done )->
errors = userValidator.validateMulti( { name: "x", type: "x", age: 0 } )
should.exist( errors )
errors.should.have.length( 3 )
_map( errors, "field" ).should.containDeep(["name", "type", "age"])
_map( errors, "name" ).should.containDeep(["EVALIDATION_USER_LENGTH_NAME", "EVALIDATION_USER_LENGTH_TYPE", "EVALIDATION_USER_CHECK_AGE"])
done()
return
it "failing between too low", ( done )->
err = userValidator.validate( { name: "John", type: "ab", money: 666 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_CHECK_MONEY" )
err.type.should.eql( "check" )
done()
return
it "failing between too high", ( done )->
err = userValidator.validate( { name: "John", type: "ab", money: 6666 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_CHECK_MONEY" )
err.type.should.eql( "check" )
done()
return
it "between bottom boundary", ( done )->
err = userValidator.validate( { name: "John", type: "ab", money: 1000 } )
should.not.exist( err )
done()
return
it "between bottom boundary", ( done )->
err = userValidator.validate( { name: "John", type: "ab", money: 5000 } )
should.not.exist( err )
done()
return
it "array: wrong type", ( done )->
err = userValidator.validate( { name: "John", list: 123 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_ARRAY_LIST" )
err.type.should.eql( "array" )
done()
return
it "array: between length too low", ( done )->
err = userValidator.validate( { name: "John", list: [1], money: 5000 } )
err.name.should.eql( "EVALIDATION_USER_LENGTH_LIST" )
err.type.should.eql( "length" )
done()
return
it "array: between length top boundary", ( done )->
err = userValidator.validate( { name: "John", list: [1,2], money: 5000 } )
should.not.exist( err )
done()
return
it "array: between length top boundary", ( done )->
err = userValidator.validate( { name: "John", list: [1,2,3,4], money: 5000 } )
should.not.exist( err )
done()
return
it "array: between length too high", ( done )->
err = userValidator.validate( { name: "John", list: [1,2,3,4,5], money: 5000 } )
err.name.should.eql( "EVALIDATION_USER_LENGTH_LIST" )
err.type.should.eql( "length" )
done()
return
it "schema: test sub schemas", ( done )->
err = userValidator.validate( { name: "John", settings: { a: "abc", b: 23 }, settings_list: ["abc",23 ] } )
should.not.exist( err )
done()
return
it "schema: test sub-sub schemas", ( done )->
err = userValidator.validate( { name: "John", settings: { a: "abc", b: 23 }, settings_list: ["abc",23, { sub_a: "test", sub_b: 123 } ] } )
err.name.should.eql( "EVALIDATION_USER-SETTINGS_LIST-SUB_BOOLEAN_SUB_B" )
err.type.should.eql( "boolean" )
err.path.should.eql( "settings_list/sub/sub_b" )
done()
return
it "schema: use a wrong type for sub-schema", ( done )->
err = userValidator.validate( { name: "John", settings: "abc" } )
err.name.should.eql( "EVALIDATION_USER_SCHEMA_SETTINGS" )
err.type.should.eql( "schema" )
err.message.should.containEql( "object" )
done()
return
it "schema: use a wrong type for sub-schema", ( done )->
err = userValidator.validate( { name: "John", settings: ["foo", 42] } )
err.name.should.eql( "EVALIDATION_USER_SCHEMA_SETTINGS" )
err.type.should.eql( "schema" )
err.message.should.containEql( "object" )
done()
return
it "schema: use a wrong content both", ( done )->
err = userValidator.validate( { name: "John", settings: { a: 23, b: "foo" } } )
err.name.should.eql( "EVALIDATION_SETTINGS_STRING_A" )
err.type.should.eql( "string" )
done()
return
it "schema: use a wrong content only b", ( done )->
err = userValidator.validate( { name: "John", settings: { a: "foo", b: "bar" } } )
err.name.should.eql( "EVALIDATION_SETTINGS_NUMBER_B" )
err.type.should.eql( "number" )
done()
return
it "schema-array: use a wrong type for sub-schema", ( done )->
err = userValidator.validate( { name: "John", settings_list: "abc" } )
err.name.should.eql( "EVALIDATION_USER_SCHEMA_SETTINGS_LIST" )
err.type.should.eql( "schema" )
err.message.should.containEql( "array" )
done()
return
it "schema-array: use a wrong type for sub-schema", ( done )->
err = userValidator.validate( { name: "John", settings_list: { a: "foo", b : 42 } } )
err.name.should.eql( "EVALIDATION_USER_SCHEMA_SETTINGS_LIST" )
err.type.should.eql( "schema" )
err.message.should.containEql( "array" )
done()
return
it "schema-array: use a wrong content for 1st", ( done )->
err = userValidator.validate( { name: "John", settings_list: [13, 42] } )
err.name.should.eql( "EVALIDATION_USER-SETTINGS_LIST_STRING_A" )
err.type.should.eql( "string" )
done()
return
it "schema-array: use a wrong content for 2nd", ( done )->
err = userValidator.validate( { name: "John", settings_list: ["foo", "bar"] } )
err.name.should.eql( "EVALIDATION_USER-SETTINGS_LIST_NUMBER_B" )
err.type.should.eql( "number" )
done()
return
it "input invalid data formats as base: `null`", ( done )->
err = userValidator.validate( null )
err.name.should.eql( "EVALIDATION_USER_OBJECT" )
err.type.should.eql( "object" )
done()
return
it "input invalid data formats as base: `boolean`", ( done )->
err = userValidator.validate( true )
err.name.should.eql( "EVALIDATION_USER_OBJECT" )
err.type.should.eql( "object" )
done()
return
it "input invalid data formats as base: `array`", ( done )->
err = userValidator.validate( [ "John" ] )
err.name.should.eql( "EVALIDATION_USER_OBJECT" )
err.type.should.eql( "object" )
done()
return
it "check for `null` if `nullAllowed`", ( done )->
_data =
checkA: null
checkB: 23
flagA: null
flagB: true
settings_list: null
err = userNullValidator.validate( _data )
should.not.exist( err )
done()
return
it "check for `null` if not `nullAllowed`", ( done )->
_data =
checkA: 42
checkB: null
flagA: false
flagB: null
settings_list: [ "abc",23 ]
err = userNullValidator.validate( _data )
err.name.should.eql( "EVALIDATION_USER-NULL_REQUIRED_FLAGB" )
err.type.should.eql( "required" )
done()
return
describe 'Single Key -', ->
it "successfull validate a single key", ( done )->
res = userValidator.validateKey( "name", "John" )
should.exist( res )
res.should.not.instanceof( Error )
res.should.eql( "John" )
done()
return
it "failing validate a single key", ( done )->
res = userValidator.validateKey( "name", "J." )
should.exist( res )
res.should.instanceof( Error )
res.name.should.eql( "EVALIDATION_USER_LENGTH_NAME" )
res.type.should.eql( "length" )
done()
return
it "validate a unkown key", ( done )->
res = userValidator.validateKey( "wat", "J." )
should.not.exist( res )
done()
return
it "generate default", ( done )->
res = userValidator.validateKey( "age", null )
should.exist( res )
res.should.not.instanceof( Error )
res.should.eql( 42 )
done()
return
it "strip html", ( done )->
res = userValidator.validateKey( "comment", "<b>abc</b><div class=\"test\">XYZ</div>" )
should.exist( res )
res.should.not.instanceof( Error )
res.should.eql( "<b>abc</b>XYZ" )
done()
return
return
describe 'Check Array content -', ->
userValidatorArray = new Schema([
key: "id",
required: true,
type: "number"
,
key: "name",
type: "string"
check:
operand: "btw"
value: [4,20]
,
key: "email",
type: "email"
,
key: "age"
,
key: "foo"
type: "number"
default: 42
,
key: "settings"
type: "schema"
schema: settingsValidator
,
key: "settings_list"
type: "schema"
required: true
schema: [
key: "a",
type: "string"
required: true
,
key: "b",
type: "number"
]
])
it "successfull validate", ( done )->
_data = [ 123, "John", "john@do.com", 23, undefined, null, [ "a", 42 ] ]
err = userValidatorArray.validate( _data, { type: "create" } )
should.not.exist( err )
should.exist( _data[3] )
_data[3].should.eql( 23 )
_data[4].should.eql( 42 )
should.not.exist( _data[5] )
done()
return
it "as object", ( done )->
_data = { id: null, name: "John", email: "john@do.com", age: 23 }
err = userValidatorArray.validate( _data, { type: "create" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_DATA_ARRAY" )
done()
return
it "validate a single index", ( done )->
_data = [ null, "Jo", "john@do.com", 23 ]
idx = 1
err = userValidatorArray.validateKey( idx, _data[ idx ], { type: "create" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_DATA_LENGTH_NAME" )
err.def.idx.should.eql( idx )
done()
return
it "missing id", ( done )->
_data = [ null, "John", "john@do.com", 23 ]
err = userValidatorArray.validate( _data, { type: "create" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_DATA_REQUIRED_ID" )
err.def.idx.should.eql( 0 )
done()
return
it "invalid name", ( done )->
_data = [ 45, "Doe", "john@do.com", 23 ]
err = userValidatorArray.validate( _data, { type: "create" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_DATA_LENGTH_NAME" )
err.def.idx.should.eql( 1 )
done()
return
it "invalid name multi", ( done )->
_data = [ 45, "Doe", "johndo.com", 23 ]
err = userValidatorArray.validateMulti( _data, { type: "create" } )
should.exist( err )
for _e in err
switch _e.type
when "length"
_e.name.should.eql( "EVALIDATION_DATA_LENGTH_NAME" )
_e.def.idx.should.eql( 1 )
when "email"
_e.name.should.eql( "EVALIDATION_DATA_EMAIL_EMAIL" )
_e.def.idx.should.eql( 2 )
done()
return
it "input invalid data formats as base: `null`", ( done )->
[ err ] = userValidatorArray.validateMulti( null )
err.name.should.eql( "EVALIDATION_DATA_ARRAY" )
err.type.should.eql( "array" )
done()
return
it "input invalid data formats as base: `boolean`", ( done )->
err = userValidatorArray.validate( true )
err.name.should.eql( "EVALIDATION_DATA_ARRAY" )
err.type.should.eql( "array" )
done()
return
it "input invalid data formats as base: `object`", ( done )->
err = userValidatorArray.validate( { name: "John" } )
err.name.should.eql( "EVALIDATION_DATA_ARRAY" )
err.type.should.eql( "array" )
done()
return
it "successfull validate", ( done )->
_data = [ 123, "John", "john@do.com", 23, null, { a: "foo", c: false }, [ "a", 42 ] ]
err = userValidatorArray.validate( _data, { type: "create" } )
err.name.should.eql( "EVALIDATION_SETTINGS_REQUIRED_B" )
err.type.should.eql( "required" )
done()
return
it "successfull validate", ( done )->
_data = [ 123, "John", "john@do.com", 23, null, null, [ "a", "b" ] ]
err = userValidatorArray.validate( _data, { type: "create" } )
err.name.should.eql( "EVALIDATION_DATA-SETTINGS_LIST_NUMBER_B" )
err.type.should.eql( "number" )
done()
return
return
describe 'Custom functions -', ->
fnSkipId = ( key, val, data, options )->
return options.type isnt "create"
fnDefaultAge = ( key, val, data, options )->
return data.name.length * ( options.factor or 13 )
fnDefaultName = ( key, val, data, options )->
return "autogen-" + data.id
class ObjSchemaTestError extends Error
statusCode: 406
customError: true
testError: true
constructor: ( @nane = @constructor.name, @message = "-" )->
@stack = (new Error).stack
return
fnCustomError = ( errtype, key, def, opt, cnf )->
if key in [ "id", "name" ]
_err = new ObjSchemaTestError()
_err.name = "Error.Custom.#{key}.#{errtype}"
return _err
return Schema::error.apply( @, arguments )
userValidatorFn = new Schema({
id:
required: true,
type: "number",
fnSkip: fnSkipId
name:
type: "string",
default: fnDefaultName
email:
type: "email"
age:
default: fnDefaultAge
settings:
type: "schema"
schema: [
key: "a"
type: "number"
,
key: "sub"
type: "schema"
schema:
c:
type: "boolean"
]
}, { name: "user_custom", customerror: fnCustomError })
it "successfull validate with fnSkip", ( done )->
_data = { id: 123, name: "John", email: "john@do.com", age: 23 }
err = userValidatorFn.validate( _data, { type: "create" } )
should.not.exist( err )
should.exist( _data.age )
_data.age.should.eql( 23 )
done()
return
it "failing validate with fnSkip", ( done )->
_data = { name: "John", email: "john@do.com" }
err = userValidatorFn.validate( _data, { type: "create" } )
should.exist( err )
err.name.should.eql( "Error.Custom.id.required" )
should.exist( err.testError )
done()
return
it "failing because wrong name type", ( done )->
_data = { id: 123, name: 123, email: "john@do.com" }
err = userValidatorFn.validate( _data, { type: "create" } )
should.exist( err )
err.name.should.eql( "Error.Custom.name.string" )
should.exist( err.testError )
done()
return
it "failing because wrong email type", ( done )->
_data = { id: 123, name: "John", email: [ "john@do.com", "jim@do.com" ] }
err = userValidatorFn.validate( _data, { type: "create" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_CUSTOM_EMAIL_EMAIL" )
should.not.exist( err.testError )
done()
return
it "success validate with fnSkip with differnt type", ( done )->
_data = { name: "John", email: "john@do.com" }
err = userValidatorFn.validate( _data, { type: "update" } )
should.not.exist( err )
should.exist( _data.age )
_data.age.should.eql( 52 )
done()
return
it "success modify age default", ( done )->
_data = { name: "John", email: "john@do.com" }
err = userValidatorFn.validate( _data, { type: "update", factor: 23 } )
should.not.exist( err )
should.exist( _data.age )
_data.age.should.eql( 92 )
done()
return
it "success modify name default", ( done )->
_data = { id: 123, email: "john@do.com" }
err = userValidatorFn.validate( _data, { type: "create" } )
should.not.exist( err )
_expName = "autogen-123"
_data.should.have.property( "age" )
.and.eql( _expName.length * 13 )
_data.should.have.property( "name" )
.and.eql( _expName )
done()
return
return
describe 'Helper Methods -', ->
it "keys method", ( done )->
_keys = userValidator.keys()
_exp = "name,nickname,nicknameb,type,email,sex,tag,list,age,timezone,settings,props,active,money,checkA,checkB,flagA,flagB,comment,settings_list".split( "," )
_difference( _keys, _exp ).should.length( 0 )
_difference( _exp, _keys ).should.length( 0 )
done()
return
it "trim method", ( done )->
userValidator.trim( " a b e t " ).should.equal( "a b e t" )
done()
return
return
return
| 130353 | should = require('should')
_map = require('lodash/map')
_difference = require('lodash/difference')
Schema = require( "../." )
userValidator = null
userNullValidator = null
settingsValidator = new Schema(
"a":
type: "string"
required: true
"b":
type: "number"
"c":
foreignReq: ["b"]
type: "boolean"
, { name: "settings" } )
describe "OBJ-SCHEMA -", ->
before ( done )->
settingsValidatorArr = new Schema([
key: "a",
type: "string"
required: true
,
key: "b",
type: "number"
], { name: "settings-list" } )
userValidator = new Schema(
"name":
type: "string"
required: true
trim: true
sanitize: true
striphtml: true
check:
operand: ">="
value: 4
"nickname":
type: "string"
check:
operand: "<"
value: 10
"nicknameb":
type: "string"
check:
operand: "<="
value: 10
"type":
type: "string"
check:
operand: "eq"
value: 2
"sex":
type: "string"
regexp: /^(m|w)$/gi
"email":
type: "email"
"age":
type: "number"
default: 42
check:
operand: ">"
value: 0
"money":
type: "number"
check:
operand: "btw"
value: [1000,5000]
"comment":
type: "string"
striphtml: [ "b" ]
"tag":
type: "enum"
values: [ "A", "B", "C" ]
"list":
type: "array"
check:
operand: "btw"
value: [2,4]
"timezone":
type: "timezone"
"settings":
type: "schema"
schema: settingsValidator
"settings_list":
type: "schema"
schema: [
key: "a",
type: "string"
required: true
,
key: "b",
type: "number"
,
key: "sub",
type: "schema"
schema:
sub_a:
type: "string"
required: true
sub_b:
type: "boolean"
required: true
]
"props":
type: "object"
"active":
type: "boolean"
default: true
"flagA":
type: "boolean"
nullAllowed: true
"flagB":
type: "boolean"
"checkA":
type: "number"
nullAllowed: true
check:
operand: "neq"
value: 23
"checkB":
type: "number"
check:
operand: "eq"
value: 23
, { name: "user" } )
userNullValidator = new Schema(
"flagA":
required: true
type: "boolean"
nullAllowed: true
"flagB":
required: true
type: "boolean"
"checkA":
required: true
type: "number"
nullAllowed: true
check:
operand: "neq"
value: 23
"checkB":
required: true
type: "number"
check:
operand: "eq"
value: 23
"settings_list":
required: true
nullAllowed: true
type: "schema"
schema: [
key: "a",
type: "string"
required: true
,
key: "b",
type: "number"
,
key: "sub",
type: "schema"
schema:
sub_a:
type: "string"
required: true
sub_b:
type: "boolean"
required: true
]
, { name: "user-null" } )
done()
return
after ( done )->
# TODO teardown
done()
return
describe 'Main -', ->
it "success", ( done )->
_data =
name: "<NAME>"
nickname: "johndoe"
nicknameb: "johndoe"
type: "ab"
email: "<EMAIL>"
sex: "M"
tag: "A"
list: [1,2,3]
age: 23
timezone: "CET"
settings: { a: "foo", b: 123, c: true }
props: { foo: "bar" }
active: false
money: 1001
checkA: 42
checkB: 23
flagA: false
flagB: true
comment: "a <b>html</b> <i>test</i>"
err = userValidator.validate( _data )
should.not.exist( err )
should.exist( _data.age )
_data.age.should.eql( 23 )
should.exist( _data.active )
_data.active.should.eql( false )
_data.flagA.should.eql( false )
_data.flagB.should.eql( true )
should.exist( _data.comment )
_data.comment.should.eql( "a <b>html</b> test" )
done()
return
it "success cb", ( done )->
_data =
name: "<NAME>"
nickname: "johndoe"
nicknameb: "johndoe"
type: "ab"
email: "<EMAIL>"
sex: "M"
tag: "A"
list: [1,2,3]
age: 23
timezone: "CET"
settings: { a: "foo", b: 123, c: true }
props: { foo: "bar" }
active: false
money: 1001
checkA: 42
checkB: 23
flagA: false
flagB: true
comment: "a <b>html</b> <i>test</i>"
userValidator.validateCb _data, ( err )->
should.not.exist( err )
should.exist( _data.age )
_data.age.should.eql( 23 )
should.exist( _data.active )
_data.active.should.eql( false )
_data.flagA.should.eql( false )
_data.flagB.should.eql( true )
should.exist( _data.comment )
_data.comment.should.eql( "a <b>html</b> test" )
done()
return
return
it "success", ( done )->
_data =
name: "<NAME>"
nickname: "johndoe"
nicknameb: "johndoe"
type: "ab"
email: "<EMAIL>"
sex: "M"
tag: "A"
list: [1,2,3]
age: 23
timezone: "CET"
settings: { a: "foo", b: 123, c: true }
props: { foo: "bar" }
active: false
money: 1001
checkA: 42
checkB: 23
flagA: false
flagB: true
comment: "a <b>html</b> <i>test</i>"
err = userValidator.validateMulti( _data )
should.not.exist( err )
should.exist( _data.age )
_data.age.should.eql( 23 )
should.exist( _data.active )
_data.active.should.eql( false )
_data.flagA.should.eql( false )
_data.flagB.should.eql( true )
should.exist( _data.comment )
_data.comment.should.eql( "a <b>html</b> test" )
done()
return
it "success min", ( done )->
_data = { name: "<NAME>" }
err = userValidator.validate( _data )
should.not.exist( err )
should.exist( _data.age )
_data.age.should.eql( 42 )
should.exist( _data.active )
_data.active.should.eql( true )
done()
return
it "missing required", ( done )->
err = userValidator.validate( { email: "<EMAIL>", age: "23" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_REQUIRED_NAME" )
err.field.should.eql( "name" )
err.type.should.eql( "required" )
err.statusCode.should.eql( 406 )
err.customError.should.eql( true )
err.should.instanceof( Error )
should.exist( err.def )
done()
return
it "invalid type", ( done )->
[ err ] = userValidator.validateMulti( [ { name: "<NAME>", email: "<EMAIL>", age: "23" } ] )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_OBJECT" )
done()
return
it "invalid type", ( done )->
err = userValidator.validate( { name: "<NAME>", email: "<EMAIL>", age: "23" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_NUMBER_AGE" )
err.field.should.eql( "age" )
err.type.should.eql( "number" )
done()
return
it "invalid type cb=true", ( done )->
err = userValidator.validateCb( { name: "<NAME>", email: "<EMAIL>", age: "23" }, true )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_NUMBER_AGE" )
err.field.should.eql( "age" )
err.type.should.eql( "number" )
done()
return
it "invalid type cb=null", ( done )->
return should.throws( ->
userValidator.validateCb( { name: "<NAME>", email: "<EMAIL>", age: "23" }, null )
, ( err )->
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_NUMBER_AGE" )
err.field.should.eql( "age" )
err.type.should.eql( "number" )
done()
return
)
it "invalid email", ( done )->
err = userValidator.validate( { name: "<NAME>", email: "johndocom", age: 23 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_EMAIL_EMAIL" )
err.field.should.eql( "email" )
err.type.should.eql( "email" )
done()
return
it "invalid enum", ( done )->
err = userValidator.validate( { name: "<NAME>", email: "<EMAIL>", age: 23, tag: "X" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_ENUM_TAG" )
done()
return
it "invalid timezone", ( done )->
err = userValidator.validate( { name: "<NAME>", email: "<EMAIL>", timezone: "X" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_TIMEZONE_TIMEZONE" )
done()
return
it "invalid timezone", ( done )->
err = userValidator.validate( { name: "<NAME>", email: "<EMAIL>", timezone: "X" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_TIMEZONE_TIMEZONE" )
done()
return
it "invalid subschema type", ( done )->
err = userValidator.validate( { name: "<NAME>", email: "<EMAIL>", settings: { a: "a", b: "b" } } )
should.exist( err )
err.name.should.eql( "EVALIDATION_SETTINGS_NUMBER_B" )
done()
return
it "invalid subschema required", ( done )->
err = userValidator.validate( { name: "<NAME>", email: "<EMAIL>", settings: { b: "b" } } )
should.exist( err )
err.name.should.eql( "EVALIDATION_SETTINGS_REQUIRED_A" )
done()
return
it "invalid subschema required foreignReq", ( done )->
err = userValidator.validate( { name: "<NAME>", email: "<EMAIL>", settings: { a: "x", c: true } } )
should.exist( err )
err.name.should.eql( "EVALIDATION_SETTINGS_REQUIRED_B" )
done()
return
it "invalid object", ( done )->
err = userValidator.validate( { name: "<NAME>", email: "<EMAIL>", props: "foo:bar" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_OBJECT_PROPS" )
done()
return
it "invalid object as array", ( done )->
err = userValidator.validate( { name: "<NAME>", email: "<EMAIL>", props: [ "foo", "bar" ] } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_OBJECT_PROPS" )
done()
return
it "invalid boolean", ( done )->
err = userValidator.validate( { name: "<NAME>", email: "<EMAIL>", active: "NO" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_BOOLEAN_ACTIVE" )
done()
return
it "failing number check", ( done )->
err = userValidator.validate( { name: "<NAME>", email: "<EMAIL>", age: 0 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_CHECK_AGE" )
done()
return
it "failing number check eq", ( done )->
err = userValidator.validate( { name: "<NAME>", email: "<EMAIL>", checkA: 23 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_CHECK_CHECKA" )
done()
return
it "failing number check neq", ( done )->
err = userValidator.validate( { name: "<NAME>", email: "<EMAIL>", checkB: 42 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_CHECK_CHECKB" )
done()
return
it "failing number regex", ( done )->
err = userValidator.validate( { name: "<NAME>", sex: "X" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_REGEXP_SEX" )
done()
return
it "failing string length too low", ( done )->
err = userValidator.validate( { name: "<NAME>", email: "<EMAIL>", age: 0 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_LENGTH_NAME" )
done()
return
it "failing string length too high (lt)", ( done )->
err = userValidator.validate( { name: "<NAME>", nickname: "johntheipsumdo", age: 23 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_LENGTH_NICKNAME" )
err.should.have.property( "def" )
.and.have.property( "check" )
.and.have.property( "value" )
.and.eql( 10 )
done()
return
it "failing string length too high (lte)", ( done )->
err = userValidator.validate( { name: "<NAME>", nicknameb: "johntheipsu", age: 23 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_LENGTH_NICKNAMEB" )
err.should.have.property( "def" )
.and.have.property( "check" )
.and.have.property( "value" )
.and.eql( 10 )
done()
return
it "cheching trim and sanitize", ( done )->
data = { name: " <NAME> <script>alert(234)</script><b><NAME></b> ", age: 23 }
err = userValidator.validate( data )
should.not.exist( err )
data.name.should.equal( "<NAME>" )
done()
return
it "failing string length neq - low", ( done )->
err = userValidator.validate( { name: "<NAME>", type: "x", age: 0 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_LENGTH_TYPE" )
done()
return
it "failing string length neq - high", ( done )->
err = userValidator.validate( { name: "<NAME>", type: "abc", age: 0 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_LENGTH_TYPE" )
err.type.should.eql( "length" )
done()
return
it "failing with callback", ( done )->
err = userValidator.validateCb { name: "<NAME>", type: "abc", age: 0 }, ( err )->
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_LENGTH_TYPE" )
err.type.should.eql( "length" )
done()
return
return
it "failing string", ( done )->
errors = userValidator.validateMulti( { name: "x", type: "x", age: 0 } )
should.exist( errors )
errors.should.have.length( 3 )
_map( errors, "field" ).should.containDeep(["name", "type", "age"])
_map( errors, "name" ).should.containDeep(["EVALIDATION_USER_LENGTH_NAME", "EVALIDATION_USER_LENGTH_TYPE", "EVALIDATION_USER_CHECK_AGE"])
done()
return
it "failing between too low", ( done )->
err = userValidator.validate( { name: "<NAME>", type: "ab", money: 666 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_CHECK_MONEY" )
err.type.should.eql( "check" )
done()
return
it "failing between too high", ( done )->
err = userValidator.validate( { name: "<NAME>", type: "ab", money: 6666 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_CHECK_MONEY" )
err.type.should.eql( "check" )
done()
return
it "between bottom boundary", ( done )->
err = userValidator.validate( { name: "<NAME>", type: "ab", money: 1000 } )
should.not.exist( err )
done()
return
it "between bottom boundary", ( done )->
err = userValidator.validate( { name: "<NAME>", type: "ab", money: 5000 } )
should.not.exist( err )
done()
return
it "array: wrong type", ( done )->
err = userValidator.validate( { name: "<NAME>", list: 123 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_ARRAY_LIST" )
err.type.should.eql( "array" )
done()
return
it "array: between length too low", ( done )->
err = userValidator.validate( { name: "<NAME>", list: [1], money: 5000 } )
err.name.should.eql( "EVALIDATION_USER_LENGTH_LIST" )
err.type.should.eql( "length" )
done()
return
it "array: between length top boundary", ( done )->
err = userValidator.validate( { name: "<NAME>", list: [1,2], money: 5000 } )
should.not.exist( err )
done()
return
it "array: between length top boundary", ( done )->
err = userValidator.validate( { name: "<NAME>", list: [1,2,3,4], money: 5000 } )
should.not.exist( err )
done()
return
it "array: between length too high", ( done )->
err = userValidator.validate( { name: "<NAME>", list: [1,2,3,4,5], money: 5000 } )
err.name.should.eql( "EVALIDATION_USER_LENGTH_LIST" )
err.type.should.eql( "length" )
done()
return
it "schema: test sub schemas", ( done )->
err = userValidator.validate( { name: "<NAME>", settings: { a: "abc", b: 23 }, settings_list: ["abc",23 ] } )
should.not.exist( err )
done()
return
it "schema: test sub-sub schemas", ( done )->
err = userValidator.validate( { name: "<NAME>", settings: { a: "abc", b: 23 }, settings_list: ["abc",23, { sub_a: "test", sub_b: 123 } ] } )
err.name.should.eql( "EVALIDATION_USER-SETTINGS_LIST-SUB_BOOLEAN_SUB_B" )
err.type.should.eql( "boolean" )
err.path.should.eql( "settings_list/sub/sub_b" )
done()
return
it "schema: use a wrong type for sub-schema", ( done )->
err = userValidator.validate( { name: "<NAME>", settings: "abc" } )
err.name.should.eql( "EVALIDATION_USER_SCHEMA_SETTINGS" )
err.type.should.eql( "schema" )
err.message.should.containEql( "object" )
done()
return
it "schema: use a wrong type for sub-schema", ( done )->
err = userValidator.validate( { name: "<NAME>", settings: ["foo", 42] } )
err.name.should.eql( "EVALIDATION_USER_SCHEMA_SETTINGS" )
err.type.should.eql( "schema" )
err.message.should.containEql( "object" )
done()
return
it "schema: use a wrong content both", ( done )->
err = userValidator.validate( { name: "<NAME>", settings: { a: 23, b: "foo" } } )
err.name.should.eql( "EVALIDATION_SETTINGS_STRING_A" )
err.type.should.eql( "string" )
done()
return
it "schema: use a wrong content only b", ( done )->
err = userValidator.validate( { name: "<NAME>", settings: { a: "foo", b: "bar" } } )
err.name.should.eql( "EVALIDATION_SETTINGS_NUMBER_B" )
err.type.should.eql( "number" )
done()
return
it "schema-array: use a wrong type for sub-schema", ( done )->
err = userValidator.validate( { name: "<NAME>", settings_list: "abc" } )
err.name.should.eql( "EVALIDATION_USER_SCHEMA_SETTINGS_LIST" )
err.type.should.eql( "schema" )
err.message.should.containEql( "array" )
done()
return
it "schema-array: use a wrong type for sub-schema", ( done )->
err = userValidator.validate( { name: "<NAME>", settings_list: { a: "foo", b : 42 } } )
err.name.should.eql( "EVALIDATION_USER_SCHEMA_SETTINGS_LIST" )
err.type.should.eql( "schema" )
err.message.should.containEql( "array" )
done()
return
it "schema-array: use a wrong content for 1st", ( done )->
err = userValidator.validate( { name: "<NAME>", settings_list: [13, 42] } )
err.name.should.eql( "EVALIDATION_USER-SETTINGS_LIST_STRING_A" )
err.type.should.eql( "string" )
done()
return
it "schema-array: use a wrong content for 2nd", ( done )->
err = userValidator.validate( { name: "<NAME>", settings_list: ["foo", "bar"] } )
err.name.should.eql( "EVALIDATION_USER-SETTINGS_LIST_NUMBER_B" )
err.type.should.eql( "number" )
done()
return
it "input invalid data formats as base: `null`", ( done )->
err = userValidator.validate( null )
err.name.should.eql( "EVALIDATION_USER_OBJECT" )
err.type.should.eql( "object" )
done()
return
it "input invalid data formats as base: `boolean`", ( done )->
err = userValidator.validate( true )
err.name.should.eql( "EVALIDATION_USER_OBJECT" )
err.type.should.eql( "object" )
done()
return
it "input invalid data formats as base: `array`", ( done )->
err = userValidator.validate( [ "<NAME>" ] )
err.name.should.eql( "EVALIDATION_USER_OBJECT" )
err.type.should.eql( "object" )
done()
return
it "check for `null` if `nullAllowed`", ( done )->
_data =
checkA: null
checkB: 23
flagA: null
flagB: true
settings_list: null
err = userNullValidator.validate( _data )
should.not.exist( err )
done()
return
it "check for `null` if not `nullAllowed`", ( done )->
_data =
checkA: 42
checkB: null
flagA: false
flagB: null
settings_list: [ "abc",23 ]
err = userNullValidator.validate( _data )
err.name.should.eql( "EVALIDATION_USER-NULL_REQUIRED_FLAGB" )
err.type.should.eql( "required" )
done()
return
describe 'Single Key -', ->
it "successfull validate a single key", ( done )->
res = userValidator.validateKey( "name", "<NAME>" )
should.exist( res )
res.should.not.instanceof( Error )
res.should.eql( "<NAME>" )
done()
return
it "failing validate a single key", ( done )->
res = userValidator.validateKey( "name", "J." )
should.exist( res )
res.should.instanceof( Error )
res.name.should.eql( "EVALIDATION_USER_LENGTH_NAME" )
res.type.should.eql( "length" )
done()
return
it "validate a unkown key", ( done )->
res = userValidator.validateKey( "wat", "J." )
should.not.exist( res )
done()
return
it "generate default", ( done )->
res = userValidator.validateKey( "age", null )
should.exist( res )
res.should.not.instanceof( Error )
res.should.eql( 42 )
done()
return
it "strip html", ( done )->
res = userValidator.validateKey( "comment", "<b>abc</b><div class=\"test\">XYZ</div>" )
should.exist( res )
res.should.not.instanceof( Error )
res.should.eql( "<b>abc</b>XYZ" )
done()
return
return
describe 'Check Array content -', ->
userValidatorArray = new Schema([
key: "id",
required: true,
type: "number"
,
key: "name",
type: "string"
check:
operand: "btw"
value: [4,20]
,
key: "email",
type: "email"
,
key: "age"
,
key: "foo"
type: "number"
default: 42
,
key: "settings"
type: "schema"
schema: settingsValidator
,
key: "settings_list"
type: "schema"
required: true
schema: [
key: "a",
type: "string"
required: true
,
key: "b",
type: "number"
]
])
it "successfull validate", ( done )->
_data = [ 123, "<NAME>", "<EMAIL>", 23, undefined, null, [ "a", 42 ] ]
err = userValidatorArray.validate( _data, { type: "create" } )
should.not.exist( err )
should.exist( _data[3] )
_data[3].should.eql( 23 )
_data[4].should.eql( 42 )
should.not.exist( _data[5] )
done()
return
it "as object", ( done )->
_data = { id: null, name: "<NAME>", email: "<EMAIL>", age: 23 }
err = userValidatorArray.validate( _data, { type: "create" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_DATA_ARRAY" )
done()
return
it "validate a single index", ( done )->
_data = [ null, "<NAME>", "<EMAIL>", 23 ]
idx = 1
err = userValidatorArray.validateKey( idx, _data[ idx ], { type: "create" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_DATA_LENGTH_NAME" )
err.def.idx.should.eql( idx )
done()
return
it "missing id", ( done )->
_data = [ null, "<NAME>", "<EMAIL>", 23 ]
err = userValidatorArray.validate( _data, { type: "create" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_DATA_REQUIRED_ID" )
err.def.idx.should.eql( 0 )
done()
return
it "invalid name", ( done )->
_data = [ 45, "<NAME>", "<EMAIL>", 23 ]
err = userValidatorArray.validate( _data, { type: "create" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_DATA_LENGTH_NAME" )
err.def.idx.should.eql( 1 )
done()
return
it "invalid name multi", ( done )->
_data = [ 45, "<NAME>", "<EMAIL>", 23 ]
err = userValidatorArray.validateMulti( _data, { type: "create" } )
should.exist( err )
for _e in err
switch _e.type
when "length"
_e.name.should.eql( "EVALIDATION_DATA_LENGTH_NAME" )
_e.def.idx.should.eql( 1 )
when "email"
_e.name.should.eql( "EVALIDATION_DATA_EMAIL_EMAIL" )
_e.def.idx.should.eql( 2 )
done()
return
it "input invalid data formats as base: `null`", ( done )->
[ err ] = userValidatorArray.validateMulti( null )
err.name.should.eql( "EVALIDATION_DATA_ARRAY" )
err.type.should.eql( "array" )
done()
return
it "input invalid data formats as base: `boolean`", ( done )->
err = userValidatorArray.validate( true )
err.name.should.eql( "EVALIDATION_DATA_ARRAY" )
err.type.should.eql( "array" )
done()
return
it "input invalid data formats as base: `object`", ( done )->
err = userValidatorArray.validate( { name: "<NAME>" } )
err.name.should.eql( "EVALIDATION_DATA_ARRAY" )
err.type.should.eql( "array" )
done()
return
it "successfull validate", ( done )->
_data = [ 123, "<NAME>", "<EMAIL>", 23, null, { a: "foo", c: false }, [ "a", 42 ] ]
err = userValidatorArray.validate( _data, { type: "create" } )
err.name.should.eql( "EVALIDATION_SETTINGS_REQUIRED_B" )
err.type.should.eql( "required" )
done()
return
it "successfull validate", ( done )->
_data = [ 123, "<NAME>", "<EMAIL>", 23, null, null, [ "a", "b" ] ]
err = userValidatorArray.validate( _data, { type: "create" } )
err.name.should.eql( "EVALIDATION_DATA-SETTINGS_LIST_NUMBER_B" )
err.type.should.eql( "number" )
done()
return
return
describe 'Custom functions -', ->
fnSkipId = ( key, val, data, options )->
return options.type isnt "create"
fnDefaultAge = ( key, val, data, options )->
return data.name.length * ( options.factor or 13 )
fnDefaultName = ( key, val, data, options )->
return "autogen-" + data.id
class ObjSchemaTestError extends Error
statusCode: 406
customError: true
testError: true
constructor: ( @nane = @constructor.name, @message = "-" )->
@stack = (new Error).stack
return
fnCustomError = ( errtype, key, def, opt, cnf )->
if key in [ "id", "name" ]
_err = new ObjSchemaTestError()
_err.name = "Error.Custom.#{key}.#{errtype}"
return _err
return Schema::error.apply( @, arguments )
userValidatorFn = new Schema({
id:
required: true,
type: "number",
fnSkip: fnSkipId
name:
type: "string",
default: fnDefaultName
email:
type: "email"
age:
default: fnDefaultAge
settings:
type: "schema"
schema: [
key: "a"
type: "number"
,
key: "sub"
type: "schema"
schema:
c:
type: "boolean"
]
}, { name: "user_custom", customerror: fnCustomError })
it "successfull validate with fnSkip", ( done )->
_data = { id: 123, name: "<NAME>", email: "<EMAIL>", age: 23 }
err = userValidatorFn.validate( _data, { type: "create" } )
should.not.exist( err )
should.exist( _data.age )
_data.age.should.eql( 23 )
done()
return
it "failing validate with fnSkip", ( done )->
_data = { name: "<NAME>", email: "<EMAIL>" }
err = userValidatorFn.validate( _data, { type: "create" } )
should.exist( err )
err.name.should.eql( "Error.Custom.id.required" )
should.exist( err.testError )
done()
return
it "failing because wrong name type", ( done )->
_data = { id: 123, name: 123, email: "<EMAIL>" }
err = userValidatorFn.validate( _data, { type: "create" } )
should.exist( err )
err.name.should.eql( "Error.Custom.name.string" )
should.exist( err.testError )
done()
return
it "failing because wrong email type", ( done )->
_data = { id: 123, name: "<NAME>", email: [ "<EMAIL>", "<EMAIL>" ] }
err = userValidatorFn.validate( _data, { type: "create" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_CUSTOM_EMAIL_EMAIL" )
should.not.exist( err.testError )
done()
return
it "success validate with fnSkip with differnt type", ( done )->
_data = { name: "<NAME>", email: "<EMAIL>" }
err = userValidatorFn.validate( _data, { type: "update" } )
should.not.exist( err )
should.exist( _data.age )
_data.age.should.eql( 52 )
done()
return
it "success modify age default", ( done )->
_data = { name: "<NAME>", email: "<EMAIL>" }
err = userValidatorFn.validate( _data, { type: "update", factor: 23 } )
should.not.exist( err )
should.exist( _data.age )
_data.age.should.eql( 92 )
done()
return
it "success modify name default", ( done )->
_data = { id: 123, email: "<EMAIL>" }
err = userValidatorFn.validate( _data, { type: "create" } )
should.not.exist( err )
_expName = "autogen-123"
_data.should.have.property( "age" )
.and.eql( _expName.length * 13 )
_data.should.have.property( "name" )
.and.eql( _expName )
done()
return
return
describe 'Helper Methods -', ->
it "keys method", ( done )->
_keys = userValidator.keys()
_exp = "name,nickname,nicknameb,type,email,sex,tag,list,age,timezone,settings,props,active,money,checkA,checkB,flagA,flagB,comment,settings_list".split( "," )
_difference( _keys, _exp ).should.length( 0 )
_difference( _exp, _keys ).should.length( 0 )
done()
return
it "trim method", ( done )->
userValidator.trim( " a b e t " ).should.equal( "a b e t" )
done()
return
return
return
| true | should = require('should')
_map = require('lodash/map')
_difference = require('lodash/difference')
Schema = require( "../." )
userValidator = null
userNullValidator = null
settingsValidator = new Schema(
"a":
type: "string"
required: true
"b":
type: "number"
"c":
foreignReq: ["b"]
type: "boolean"
, { name: "settings" } )
describe "OBJ-SCHEMA -", ->
before ( done )->
settingsValidatorArr = new Schema([
key: "a",
type: "string"
required: true
,
key: "b",
type: "number"
], { name: "settings-list" } )
userValidator = new Schema(
"name":
type: "string"
required: true
trim: true
sanitize: true
striphtml: true
check:
operand: ">="
value: 4
"nickname":
type: "string"
check:
operand: "<"
value: 10
"nicknameb":
type: "string"
check:
operand: "<="
value: 10
"type":
type: "string"
check:
operand: "eq"
value: 2
"sex":
type: "string"
regexp: /^(m|w)$/gi
"email":
type: "email"
"age":
type: "number"
default: 42
check:
operand: ">"
value: 0
"money":
type: "number"
check:
operand: "btw"
value: [1000,5000]
"comment":
type: "string"
striphtml: [ "b" ]
"tag":
type: "enum"
values: [ "A", "B", "C" ]
"list":
type: "array"
check:
operand: "btw"
value: [2,4]
"timezone":
type: "timezone"
"settings":
type: "schema"
schema: settingsValidator
"settings_list":
type: "schema"
schema: [
key: "a",
type: "string"
required: true
,
key: "b",
type: "number"
,
key: "sub",
type: "schema"
schema:
sub_a:
type: "string"
required: true
sub_b:
type: "boolean"
required: true
]
"props":
type: "object"
"active":
type: "boolean"
default: true
"flagA":
type: "boolean"
nullAllowed: true
"flagB":
type: "boolean"
"checkA":
type: "number"
nullAllowed: true
check:
operand: "neq"
value: 23
"checkB":
type: "number"
check:
operand: "eq"
value: 23
, { name: "user" } )
userNullValidator = new Schema(
"flagA":
required: true
type: "boolean"
nullAllowed: true
"flagB":
required: true
type: "boolean"
"checkA":
required: true
type: "number"
nullAllowed: true
check:
operand: "neq"
value: 23
"checkB":
required: true
type: "number"
check:
operand: "eq"
value: 23
"settings_list":
required: true
nullAllowed: true
type: "schema"
schema: [
key: "a",
type: "string"
required: true
,
key: "b",
type: "number"
,
key: "sub",
type: "schema"
schema:
sub_a:
type: "string"
required: true
sub_b:
type: "boolean"
required: true
]
, { name: "user-null" } )
done()
return
after ( done )->
# TODO teardown
done()
return
describe 'Main -', ->
it "success", ( done )->
_data =
name: "PI:NAME:<NAME>END_PI"
nickname: "johndoe"
nicknameb: "johndoe"
type: "ab"
email: "PI:EMAIL:<EMAIL>END_PI"
sex: "M"
tag: "A"
list: [1,2,3]
age: 23
timezone: "CET"
settings: { a: "foo", b: 123, c: true }
props: { foo: "bar" }
active: false
money: 1001
checkA: 42
checkB: 23
flagA: false
flagB: true
comment: "a <b>html</b> <i>test</i>"
err = userValidator.validate( _data )
should.not.exist( err )
should.exist( _data.age )
_data.age.should.eql( 23 )
should.exist( _data.active )
_data.active.should.eql( false )
_data.flagA.should.eql( false )
_data.flagB.should.eql( true )
should.exist( _data.comment )
_data.comment.should.eql( "a <b>html</b> test" )
done()
return
it "success cb", ( done )->
_data =
name: "PI:NAME:<NAME>END_PI"
nickname: "johndoe"
nicknameb: "johndoe"
type: "ab"
email: "PI:EMAIL:<EMAIL>END_PI"
sex: "M"
tag: "A"
list: [1,2,3]
age: 23
timezone: "CET"
settings: { a: "foo", b: 123, c: true }
props: { foo: "bar" }
active: false
money: 1001
checkA: 42
checkB: 23
flagA: false
flagB: true
comment: "a <b>html</b> <i>test</i>"
userValidator.validateCb _data, ( err )->
should.not.exist( err )
should.exist( _data.age )
_data.age.should.eql( 23 )
should.exist( _data.active )
_data.active.should.eql( false )
_data.flagA.should.eql( false )
_data.flagB.should.eql( true )
should.exist( _data.comment )
_data.comment.should.eql( "a <b>html</b> test" )
done()
return
return
it "success", ( done )->
_data =
name: "PI:NAME:<NAME>END_PI"
nickname: "johndoe"
nicknameb: "johndoe"
type: "ab"
email: "PI:EMAIL:<EMAIL>END_PI"
sex: "M"
tag: "A"
list: [1,2,3]
age: 23
timezone: "CET"
settings: { a: "foo", b: 123, c: true }
props: { foo: "bar" }
active: false
money: 1001
checkA: 42
checkB: 23
flagA: false
flagB: true
comment: "a <b>html</b> <i>test</i>"
err = userValidator.validateMulti( _data )
should.not.exist( err )
should.exist( _data.age )
_data.age.should.eql( 23 )
should.exist( _data.active )
_data.active.should.eql( false )
_data.flagA.should.eql( false )
_data.flagB.should.eql( true )
should.exist( _data.comment )
_data.comment.should.eql( "a <b>html</b> test" )
done()
return
it "success min", ( done )->
_data = { name: "PI:NAME:<NAME>END_PI" }
err = userValidator.validate( _data )
should.not.exist( err )
should.exist( _data.age )
_data.age.should.eql( 42 )
should.exist( _data.active )
_data.active.should.eql( true )
done()
return
it "missing required", ( done )->
err = userValidator.validate( { email: "PI:EMAIL:<EMAIL>END_PI", age: "23" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_REQUIRED_NAME" )
err.field.should.eql( "name" )
err.type.should.eql( "required" )
err.statusCode.should.eql( 406 )
err.customError.should.eql( true )
err.should.instanceof( Error )
should.exist( err.def )
done()
return
it "invalid type", ( done )->
[ err ] = userValidator.validateMulti( [ { name: "PI:NAME:<NAME>END_PI", email: "PI:EMAIL:<EMAIL>END_PI", age: "23" } ] )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_OBJECT" )
done()
return
it "invalid type", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", email: "PI:EMAIL:<EMAIL>END_PI", age: "23" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_NUMBER_AGE" )
err.field.should.eql( "age" )
err.type.should.eql( "number" )
done()
return
it "invalid type cb=true", ( done )->
err = userValidator.validateCb( { name: "PI:NAME:<NAME>END_PI", email: "PI:EMAIL:<EMAIL>END_PI", age: "23" }, true )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_NUMBER_AGE" )
err.field.should.eql( "age" )
err.type.should.eql( "number" )
done()
return
it "invalid type cb=null", ( done )->
return should.throws( ->
userValidator.validateCb( { name: "PI:NAME:<NAME>END_PI", email: "PI:EMAIL:<EMAIL>END_PI", age: "23" }, null )
, ( err )->
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_NUMBER_AGE" )
err.field.should.eql( "age" )
err.type.should.eql( "number" )
done()
return
)
it "invalid email", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", email: "johndocom", age: 23 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_EMAIL_EMAIL" )
err.field.should.eql( "email" )
err.type.should.eql( "email" )
done()
return
it "invalid enum", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", email: "PI:EMAIL:<EMAIL>END_PI", age: 23, tag: "X" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_ENUM_TAG" )
done()
return
it "invalid timezone", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", email: "PI:EMAIL:<EMAIL>END_PI", timezone: "X" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_TIMEZONE_TIMEZONE" )
done()
return
it "invalid timezone", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", email: "PI:EMAIL:<EMAIL>END_PI", timezone: "X" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_TIMEZONE_TIMEZONE" )
done()
return
it "invalid subschema type", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", email: "PI:EMAIL:<EMAIL>END_PI", settings: { a: "a", b: "b" } } )
should.exist( err )
err.name.should.eql( "EVALIDATION_SETTINGS_NUMBER_B" )
done()
return
it "invalid subschema required", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", email: "PI:EMAIL:<EMAIL>END_PI", settings: { b: "b" } } )
should.exist( err )
err.name.should.eql( "EVALIDATION_SETTINGS_REQUIRED_A" )
done()
return
it "invalid subschema required foreignReq", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", email: "PI:EMAIL:<EMAIL>END_PI", settings: { a: "x", c: true } } )
should.exist( err )
err.name.should.eql( "EVALIDATION_SETTINGS_REQUIRED_B" )
done()
return
it "invalid object", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", email: "PI:EMAIL:<EMAIL>END_PI", props: "foo:bar" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_OBJECT_PROPS" )
done()
return
it "invalid object as array", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", email: "PI:EMAIL:<EMAIL>END_PI", props: [ "foo", "bar" ] } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_OBJECT_PROPS" )
done()
return
it "invalid boolean", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", email: "PI:EMAIL:<EMAIL>END_PI", active: "NO" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_BOOLEAN_ACTIVE" )
done()
return
it "failing number check", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", email: "PI:EMAIL:<EMAIL>END_PI", age: 0 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_CHECK_AGE" )
done()
return
it "failing number check eq", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", email: "PI:EMAIL:<EMAIL>END_PI", checkA: 23 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_CHECK_CHECKA" )
done()
return
it "failing number check neq", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", email: "PI:EMAIL:<EMAIL>END_PI", checkB: 42 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_CHECK_CHECKB" )
done()
return
it "failing number regex", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", sex: "X" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_REGEXP_SEX" )
done()
return
it "failing string length too low", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", email: "PI:EMAIL:<EMAIL>END_PI", age: 0 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_LENGTH_NAME" )
done()
return
it "failing string length too high (lt)", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", nickname: "johntheipsumdo", age: 23 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_LENGTH_NICKNAME" )
err.should.have.property( "def" )
.and.have.property( "check" )
.and.have.property( "value" )
.and.eql( 10 )
done()
return
it "failing string length too high (lte)", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", nicknameb: "johntheipsu", age: 23 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_LENGTH_NICKNAMEB" )
err.should.have.property( "def" )
.and.have.property( "check" )
.and.have.property( "value" )
.and.eql( 10 )
done()
return
it "cheching trim and sanitize", ( done )->
data = { name: " PI:NAME:<NAME>END_PI <script>alert(234)</script><b>PI:NAME:<NAME>END_PI</b> ", age: 23 }
err = userValidator.validate( data )
should.not.exist( err )
data.name.should.equal( "PI:NAME:<NAME>END_PI" )
done()
return
it "failing string length neq - low", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", type: "x", age: 0 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_LENGTH_TYPE" )
done()
return
it "failing string length neq - high", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", type: "abc", age: 0 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_LENGTH_TYPE" )
err.type.should.eql( "length" )
done()
return
it "failing with callback", ( done )->
err = userValidator.validateCb { name: "PI:NAME:<NAME>END_PI", type: "abc", age: 0 }, ( err )->
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_LENGTH_TYPE" )
err.type.should.eql( "length" )
done()
return
return
it "failing string", ( done )->
errors = userValidator.validateMulti( { name: "x", type: "x", age: 0 } )
should.exist( errors )
errors.should.have.length( 3 )
_map( errors, "field" ).should.containDeep(["name", "type", "age"])
_map( errors, "name" ).should.containDeep(["EVALIDATION_USER_LENGTH_NAME", "EVALIDATION_USER_LENGTH_TYPE", "EVALIDATION_USER_CHECK_AGE"])
done()
return
it "failing between too low", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", type: "ab", money: 666 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_CHECK_MONEY" )
err.type.should.eql( "check" )
done()
return
it "failing between too high", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", type: "ab", money: 6666 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_CHECK_MONEY" )
err.type.should.eql( "check" )
done()
return
it "between bottom boundary", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", type: "ab", money: 1000 } )
should.not.exist( err )
done()
return
it "between bottom boundary", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", type: "ab", money: 5000 } )
should.not.exist( err )
done()
return
it "array: wrong type", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", list: 123 } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_ARRAY_LIST" )
err.type.should.eql( "array" )
done()
return
it "array: between length too low", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", list: [1], money: 5000 } )
err.name.should.eql( "EVALIDATION_USER_LENGTH_LIST" )
err.type.should.eql( "length" )
done()
return
it "array: between length top boundary", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", list: [1,2], money: 5000 } )
should.not.exist( err )
done()
return
it "array: between length top boundary", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", list: [1,2,3,4], money: 5000 } )
should.not.exist( err )
done()
return
it "array: between length too high", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", list: [1,2,3,4,5], money: 5000 } )
err.name.should.eql( "EVALIDATION_USER_LENGTH_LIST" )
err.type.should.eql( "length" )
done()
return
it "schema: test sub schemas", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", settings: { a: "abc", b: 23 }, settings_list: ["abc",23 ] } )
should.not.exist( err )
done()
return
it "schema: test sub-sub schemas", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", settings: { a: "abc", b: 23 }, settings_list: ["abc",23, { sub_a: "test", sub_b: 123 } ] } )
err.name.should.eql( "EVALIDATION_USER-SETTINGS_LIST-SUB_BOOLEAN_SUB_B" )
err.type.should.eql( "boolean" )
err.path.should.eql( "settings_list/sub/sub_b" )
done()
return
it "schema: use a wrong type for sub-schema", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", settings: "abc" } )
err.name.should.eql( "EVALIDATION_USER_SCHEMA_SETTINGS" )
err.type.should.eql( "schema" )
err.message.should.containEql( "object" )
done()
return
it "schema: use a wrong type for sub-schema", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", settings: ["foo", 42] } )
err.name.should.eql( "EVALIDATION_USER_SCHEMA_SETTINGS" )
err.type.should.eql( "schema" )
err.message.should.containEql( "object" )
done()
return
it "schema: use a wrong content both", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", settings: { a: 23, b: "foo" } } )
err.name.should.eql( "EVALIDATION_SETTINGS_STRING_A" )
err.type.should.eql( "string" )
done()
return
it "schema: use a wrong content only b", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", settings: { a: "foo", b: "bar" } } )
err.name.should.eql( "EVALIDATION_SETTINGS_NUMBER_B" )
err.type.should.eql( "number" )
done()
return
it "schema-array: use a wrong type for sub-schema", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", settings_list: "abc" } )
err.name.should.eql( "EVALIDATION_USER_SCHEMA_SETTINGS_LIST" )
err.type.should.eql( "schema" )
err.message.should.containEql( "array" )
done()
return
it "schema-array: use a wrong type for sub-schema", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", settings_list: { a: "foo", b : 42 } } )
err.name.should.eql( "EVALIDATION_USER_SCHEMA_SETTINGS_LIST" )
err.type.should.eql( "schema" )
err.message.should.containEql( "array" )
done()
return
it "schema-array: use a wrong content for 1st", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", settings_list: [13, 42] } )
err.name.should.eql( "EVALIDATION_USER-SETTINGS_LIST_STRING_A" )
err.type.should.eql( "string" )
done()
return
it "schema-array: use a wrong content for 2nd", ( done )->
err = userValidator.validate( { name: "PI:NAME:<NAME>END_PI", settings_list: ["foo", "bar"] } )
err.name.should.eql( "EVALIDATION_USER-SETTINGS_LIST_NUMBER_B" )
err.type.should.eql( "number" )
done()
return
it "input invalid data formats as base: `null`", ( done )->
err = userValidator.validate( null )
err.name.should.eql( "EVALIDATION_USER_OBJECT" )
err.type.should.eql( "object" )
done()
return
it "input invalid data formats as base: `boolean`", ( done )->
err = userValidator.validate( true )
err.name.should.eql( "EVALIDATION_USER_OBJECT" )
err.type.should.eql( "object" )
done()
return
it "input invalid data formats as base: `array`", ( done )->
err = userValidator.validate( [ "PI:NAME:<NAME>END_PI" ] )
err.name.should.eql( "EVALIDATION_USER_OBJECT" )
err.type.should.eql( "object" )
done()
return
it "check for `null` if `nullAllowed`", ( done )->
_data =
checkA: null
checkB: 23
flagA: null
flagB: true
settings_list: null
err = userNullValidator.validate( _data )
should.not.exist( err )
done()
return
it "check for `null` if not `nullAllowed`", ( done )->
_data =
checkA: 42
checkB: null
flagA: false
flagB: null
settings_list: [ "abc",23 ]
err = userNullValidator.validate( _data )
err.name.should.eql( "EVALIDATION_USER-NULL_REQUIRED_FLAGB" )
err.type.should.eql( "required" )
done()
return
describe 'Single Key -', ->
it "successfull validate a single key", ( done )->
res = userValidator.validateKey( "name", "PI:NAME:<NAME>END_PI" )
should.exist( res )
res.should.not.instanceof( Error )
res.should.eql( "PI:NAME:<NAME>END_PI" )
done()
return
it "failing validate a single key", ( done )->
res = userValidator.validateKey( "name", "J." )
should.exist( res )
res.should.instanceof( Error )
res.name.should.eql( "EVALIDATION_USER_LENGTH_NAME" )
res.type.should.eql( "length" )
done()
return
it "validate a unkown key", ( done )->
res = userValidator.validateKey( "wat", "J." )
should.not.exist( res )
done()
return
it "generate default", ( done )->
res = userValidator.validateKey( "age", null )
should.exist( res )
res.should.not.instanceof( Error )
res.should.eql( 42 )
done()
return
it "strip html", ( done )->
res = userValidator.validateKey( "comment", "<b>abc</b><div class=\"test\">XYZ</div>" )
should.exist( res )
res.should.not.instanceof( Error )
res.should.eql( "<b>abc</b>XYZ" )
done()
return
return
describe 'Check Array content -', ->
userValidatorArray = new Schema([
key: "id",
required: true,
type: "number"
,
key: "name",
type: "string"
check:
operand: "btw"
value: [4,20]
,
key: "email",
type: "email"
,
key: "age"
,
key: "foo"
type: "number"
default: 42
,
key: "settings"
type: "schema"
schema: settingsValidator
,
key: "settings_list"
type: "schema"
required: true
schema: [
key: "a",
type: "string"
required: true
,
key: "b",
type: "number"
]
])
it "successfull validate", ( done )->
_data = [ 123, "PI:NAME:<NAME>END_PI", "PI:EMAIL:<EMAIL>END_PI", 23, undefined, null, [ "a", 42 ] ]
err = userValidatorArray.validate( _data, { type: "create" } )
should.not.exist( err )
should.exist( _data[3] )
_data[3].should.eql( 23 )
_data[4].should.eql( 42 )
should.not.exist( _data[5] )
done()
return
it "as object", ( done )->
_data = { id: null, name: "PI:NAME:<NAME>END_PI", email: "PI:EMAIL:<EMAIL>END_PI", age: 23 }
err = userValidatorArray.validate( _data, { type: "create" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_DATA_ARRAY" )
done()
return
it "validate a single index", ( done )->
_data = [ null, "PI:NAME:<NAME>END_PI", "PI:EMAIL:<EMAIL>END_PI", 23 ]
idx = 1
err = userValidatorArray.validateKey( idx, _data[ idx ], { type: "create" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_DATA_LENGTH_NAME" )
err.def.idx.should.eql( idx )
done()
return
it "missing id", ( done )->
_data = [ null, "PI:NAME:<NAME>END_PI", "PI:EMAIL:<EMAIL>END_PI", 23 ]
err = userValidatorArray.validate( _data, { type: "create" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_DATA_REQUIRED_ID" )
err.def.idx.should.eql( 0 )
done()
return
it "invalid name", ( done )->
_data = [ 45, "PI:NAME:<NAME>END_PI", "PI:EMAIL:<EMAIL>END_PI", 23 ]
err = userValidatorArray.validate( _data, { type: "create" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_DATA_LENGTH_NAME" )
err.def.idx.should.eql( 1 )
done()
return
it "invalid name multi", ( done )->
_data = [ 45, "PI:NAME:<NAME>END_PI", "PI:EMAIL:<EMAIL>END_PI", 23 ]
err = userValidatorArray.validateMulti( _data, { type: "create" } )
should.exist( err )
for _e in err
switch _e.type
when "length"
_e.name.should.eql( "EVALIDATION_DATA_LENGTH_NAME" )
_e.def.idx.should.eql( 1 )
when "email"
_e.name.should.eql( "EVALIDATION_DATA_EMAIL_EMAIL" )
_e.def.idx.should.eql( 2 )
done()
return
it "input invalid data formats as base: `null`", ( done )->
[ err ] = userValidatorArray.validateMulti( null )
err.name.should.eql( "EVALIDATION_DATA_ARRAY" )
err.type.should.eql( "array" )
done()
return
it "input invalid data formats as base: `boolean`", ( done )->
err = userValidatorArray.validate( true )
err.name.should.eql( "EVALIDATION_DATA_ARRAY" )
err.type.should.eql( "array" )
done()
return
it "input invalid data formats as base: `object`", ( done )->
err = userValidatorArray.validate( { name: "PI:NAME:<NAME>END_PI" } )
err.name.should.eql( "EVALIDATION_DATA_ARRAY" )
err.type.should.eql( "array" )
done()
return
it "successfull validate", ( done )->
_data = [ 123, "PI:NAME:<NAME>END_PI", "PI:EMAIL:<EMAIL>END_PI", 23, null, { a: "foo", c: false }, [ "a", 42 ] ]
err = userValidatorArray.validate( _data, { type: "create" } )
err.name.should.eql( "EVALIDATION_SETTINGS_REQUIRED_B" )
err.type.should.eql( "required" )
done()
return
it "successfull validate", ( done )->
_data = [ 123, "PI:NAME:<NAME>END_PI", "PI:EMAIL:<EMAIL>END_PI", 23, null, null, [ "a", "b" ] ]
err = userValidatorArray.validate( _data, { type: "create" } )
err.name.should.eql( "EVALIDATION_DATA-SETTINGS_LIST_NUMBER_B" )
err.type.should.eql( "number" )
done()
return
return
describe 'Custom functions -', ->
fnSkipId = ( key, val, data, options )->
return options.type isnt "create"
fnDefaultAge = ( key, val, data, options )->
return data.name.length * ( options.factor or 13 )
fnDefaultName = ( key, val, data, options )->
return "autogen-" + data.id
class ObjSchemaTestError extends Error
statusCode: 406
customError: true
testError: true
constructor: ( @nane = @constructor.name, @message = "-" )->
@stack = (new Error).stack
return
fnCustomError = ( errtype, key, def, opt, cnf )->
if key in [ "id", "name" ]
_err = new ObjSchemaTestError()
_err.name = "Error.Custom.#{key}.#{errtype}"
return _err
return Schema::error.apply( @, arguments )
userValidatorFn = new Schema({
id:
required: true,
type: "number",
fnSkip: fnSkipId
name:
type: "string",
default: fnDefaultName
email:
type: "email"
age:
default: fnDefaultAge
settings:
type: "schema"
schema: [
key: "a"
type: "number"
,
key: "sub"
type: "schema"
schema:
c:
type: "boolean"
]
}, { name: "user_custom", customerror: fnCustomError })
it "successfull validate with fnSkip", ( done )->
_data = { id: 123, name: "PI:NAME:<NAME>END_PI", email: "PI:EMAIL:<EMAIL>END_PI", age: 23 }
err = userValidatorFn.validate( _data, { type: "create" } )
should.not.exist( err )
should.exist( _data.age )
_data.age.should.eql( 23 )
done()
return
it "failing validate with fnSkip", ( done )->
_data = { name: "PI:NAME:<NAME>END_PI", email: "PI:EMAIL:<EMAIL>END_PI" }
err = userValidatorFn.validate( _data, { type: "create" } )
should.exist( err )
err.name.should.eql( "Error.Custom.id.required" )
should.exist( err.testError )
done()
return
it "failing because wrong name type", ( done )->
_data = { id: 123, name: 123, email: "PI:EMAIL:<EMAIL>END_PI" }
err = userValidatorFn.validate( _data, { type: "create" } )
should.exist( err )
err.name.should.eql( "Error.Custom.name.string" )
should.exist( err.testError )
done()
return
it "failing because wrong email type", ( done )->
_data = { id: 123, name: "PI:NAME:<NAME>END_PI", email: [ "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI" ] }
err = userValidatorFn.validate( _data, { type: "create" } )
should.exist( err )
err.name.should.eql( "EVALIDATION_USER_CUSTOM_EMAIL_EMAIL" )
should.not.exist( err.testError )
done()
return
it "success validate with fnSkip with differnt type", ( done )->
_data = { name: "PI:NAME:<NAME>END_PI", email: "PI:EMAIL:<EMAIL>END_PI" }
err = userValidatorFn.validate( _data, { type: "update" } )
should.not.exist( err )
should.exist( _data.age )
_data.age.should.eql( 52 )
done()
return
it "success modify age default", ( done )->
_data = { name: "PI:NAME:<NAME>END_PI", email: "PI:EMAIL:<EMAIL>END_PI" }
err = userValidatorFn.validate( _data, { type: "update", factor: 23 } )
should.not.exist( err )
should.exist( _data.age )
_data.age.should.eql( 92 )
done()
return
it "success modify name default", ( done )->
_data = { id: 123, email: "PI:EMAIL:<EMAIL>END_PI" }
err = userValidatorFn.validate( _data, { type: "create" } )
should.not.exist( err )
_expName = "autogen-123"
_data.should.have.property( "age" )
.and.eql( _expName.length * 13 )
_data.should.have.property( "name" )
.and.eql( _expName )
done()
return
return
describe 'Helper Methods -', ->
it "keys method", ( done )->
_keys = userValidator.keys()
_exp = "name,nickname,nicknameb,type,email,sex,tag,list,age,timezone,settings,props,active,money,checkA,checkB,flagA,flagB,comment,settings_list".split( "," )
_difference( _keys, _exp ).should.length( 0 )
_difference( _exp, _keys ).should.length( 0 )
done()
return
it "trim method", ( done )->
userValidator.trim( " a b e t " ).should.equal( "a b e t" )
done()
return
return
return
|
[
{
"context": " email: $scope.creds.email\n password: $scope.creds.password\n\n promise.then success, ",
"end": 805,
"score": 0.6129288077354431,
"start": 805,
"tag": "PASSWORD",
"value": ""
},
{
"context": " email: $scope.creds.email\n password: $scope.cr... | src/coffee/directives/login_form.coffee | dadleyy/loftili.ui | 0 | dLoginForm = ($location, Auth, Api, Notifications, Lang, Analytics) ->
isFn = angular.isFunction
linkFn = ($scope, $element, $attrs) ->
$scope.creds = {}
$scope.errors = []
$scope.state = 0
$scope.signup = () ->
$location.url '/signup'
$scope.close() if $scope.close and angular.isFunction $scope.close
true
$scope.attempt = (event) ->
success = () ->
Analytics.event 'authentication', 'success', 'login_form'
$location.path('/dashboard')
fail = () ->
Analytics.event 'authentication', 'fail', 'login_form'
$scope.errors = [
'Invalid credentials.'
]
Analytics.event 'authentication', 'attempt', 'login_form'
promise = Auth.attempt
email: $scope.creds.email
password: $scope.creds.password
promise.then success, fail
if event
event.stopPropagation()
$scope.reset = () ->
success_lang = Lang('reset_password.success')
success = () ->
Notifications.flash success_lang, 'info'
Analytics.event 'authentication', 'password_reset:email_sent', $scope.creds.reset_email
$scope.state = 2
fail = () ->
Analytics.event 'authentication', 'password_reset:fail', $scope.creds.reset_email
$scope.errors = ['Hmm, try again']
finish = (user) ->
Analytics.event 'authentication', 'password_reset:finished', $scope.creds.reset_email
$scope.creds.email = user.email
$scope.creds.password = $scope.creds.new_password
$scope.attempt()
if $scope.state == 0
$scope.state = 1
else if $scope.state == 1
Analytics.event 'authentication', 'password_reset:start', $scope.creds.reset_email
reset = Api.PasswordReset.save
user: $scope.creds.reset_email
reset.$promise.then success, fail
else if $scope.state = 2
Analytics.event 'authentication', 'password_reset:update_with_token', $scope.creds.reset_email
reset = Api.User.update
id: 'reset'
password: $scope.creds.new_password
reset_token: $scope.creds.reset_token
reset.$promise.then finish, fail
$scope.cancel = () ->
if $scope.state > 0
$scope.state = 0
else
if $scope.close and isFn($scope.close)
$scope.close()
$scope.keywatch = (evt) ->
$scope.errors = []
if evt.keyCode == 13 and $scope.state == 0
$scope.attempt()
LoginForm =
replace: true
templateUrl: 'directives.login_form'
scope:
close: '='
link: linkFn
dLoginForm.$inject = [
'$location'
'Auth'
'Api'
'Notifications'
'Lang'
'Analytics'
]
lft.directive 'lfLoginForm', dLoginForm
| 133782 | dLoginForm = ($location, Auth, Api, Notifications, Lang, Analytics) ->
isFn = angular.isFunction
linkFn = ($scope, $element, $attrs) ->
$scope.creds = {}
$scope.errors = []
$scope.state = 0
$scope.signup = () ->
$location.url '/signup'
$scope.close() if $scope.close and angular.isFunction $scope.close
true
$scope.attempt = (event) ->
success = () ->
Analytics.event 'authentication', 'success', 'login_form'
$location.path('/dashboard')
fail = () ->
Analytics.event 'authentication', 'fail', 'login_form'
$scope.errors = [
'Invalid credentials.'
]
Analytics.event 'authentication', 'attempt', 'login_form'
promise = Auth.attempt
email: $scope.creds.email
password:<PASSWORD> $<PASSWORD>
promise.then success, fail
if event
event.stopPropagation()
$scope.reset = () ->
success_lang = Lang('reset_password.success')
success = () ->
Notifications.flash success_lang, 'info'
Analytics.event 'authentication', 'password_reset:email_sent', $scope.creds.reset_email
$scope.state = 2
fail = () ->
Analytics.event 'authentication', 'password_reset:fail', $scope.creds.reset_email
$scope.errors = ['Hmm, try again']
finish = (user) ->
Analytics.event 'authentication', 'password_reset:finished', $scope.creds.reset_email
$scope.creds.email = user.email
$scope.creds.password = <PASSWORD>
$scope.attempt()
if $scope.state == 0
$scope.state = 1
else if $scope.state == 1
Analytics.event 'authentication', 'password_reset:start', $scope.creds.reset_email
reset = Api.PasswordReset.save
user: $scope.creds.reset_email
reset.$promise.then success, fail
else if $scope.state = 2
Analytics.event 'authentication', 'password_reset:update_with_token', $scope.creds.reset_email
reset = Api.User.update
id: 'reset'
password: $<PASSWORD>
reset_token: $scope.creds.reset_token
reset.$promise.then finish, fail
$scope.cancel = () ->
if $scope.state > 0
$scope.state = 0
else
if $scope.close and isFn($scope.close)
$scope.close()
$scope.keywatch = (evt) ->
$scope.errors = []
if evt.keyCode == 13 and $scope.state == 0
$scope.attempt()
LoginForm =
replace: true
templateUrl: 'directives.login_form'
scope:
close: '='
link: linkFn
dLoginForm.$inject = [
'$location'
'Auth'
'Api'
'Notifications'
'Lang'
'Analytics'
]
lft.directive 'lfLoginForm', dLoginForm
| true | dLoginForm = ($location, Auth, Api, Notifications, Lang, Analytics) ->
isFn = angular.isFunction
linkFn = ($scope, $element, $attrs) ->
$scope.creds = {}
$scope.errors = []
$scope.state = 0
$scope.signup = () ->
$location.url '/signup'
$scope.close() if $scope.close and angular.isFunction $scope.close
true
$scope.attempt = (event) ->
success = () ->
Analytics.event 'authentication', 'success', 'login_form'
$location.path('/dashboard')
fail = () ->
Analytics.event 'authentication', 'fail', 'login_form'
$scope.errors = [
'Invalid credentials.'
]
Analytics.event 'authentication', 'attempt', 'login_form'
promise = Auth.attempt
email: $scope.creds.email
password:PI:PASSWORD:<PASSWORD>END_PI $PI:PASSWORD:<PASSWORD>END_PI
promise.then success, fail
if event
event.stopPropagation()
$scope.reset = () ->
success_lang = Lang('reset_password.success')
success = () ->
Notifications.flash success_lang, 'info'
Analytics.event 'authentication', 'password_reset:email_sent', $scope.creds.reset_email
$scope.state = 2
fail = () ->
Analytics.event 'authentication', 'password_reset:fail', $scope.creds.reset_email
$scope.errors = ['Hmm, try again']
finish = (user) ->
Analytics.event 'authentication', 'password_reset:finished', $scope.creds.reset_email
$scope.creds.email = user.email
$scope.creds.password = PI:PASSWORD:<PASSWORD>END_PI
$scope.attempt()
if $scope.state == 0
$scope.state = 1
else if $scope.state == 1
Analytics.event 'authentication', 'password_reset:start', $scope.creds.reset_email
reset = Api.PasswordReset.save
user: $scope.creds.reset_email
reset.$promise.then success, fail
else if $scope.state = 2
Analytics.event 'authentication', 'password_reset:update_with_token', $scope.creds.reset_email
reset = Api.User.update
id: 'reset'
password: $PI:PASSWORD:<PASSWORD>END_PI
reset_token: $scope.creds.reset_token
reset.$promise.then finish, fail
$scope.cancel = () ->
if $scope.state > 0
$scope.state = 0
else
if $scope.close and isFn($scope.close)
$scope.close()
$scope.keywatch = (evt) ->
$scope.errors = []
if evt.keyCode == 13 and $scope.state == 0
$scope.attempt()
LoginForm =
replace: true
templateUrl: 'directives.login_form'
scope:
close: '='
link: linkFn
dLoginForm.$inject = [
'$location'
'Auth'
'Api'
'Notifications'
'Lang'
'Analytics'
]
lft.directive 'lfLoginForm', dLoginForm
|
[
{
"context": "aSrc: 'users'\n }\n columns: [\n { data: 'first_name' },\n { data: 'last_name' },\n { data",
"end": 418,
"score": 0.7578414678573608,
"start": 412,
"tag": "NAME",
"value": "first_"
},
{
"context": "s: [\n { data: 'first_name' },\n { data: ... | app/assets/javascripts/user.coffee | sweetcolor/artistsoft-test-project | 0 | # Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/
$(document).ready(() ->
$('#main-table').DataTable({
serverSide: true,
processing: true,
ajax: {
url: '/api/load_users',
dataSrc: 'users'
}
columns: [
{ data: 'first_name' },
{ data: 'last_name' },
{ data: 'birthday' },
{ data: 'address' }
]
})
) | 83215 | # Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/
$(document).ready(() ->
$('#main-table').DataTable({
serverSide: true,
processing: true,
ajax: {
url: '/api/load_users',
dataSrc: 'users'
}
columns: [
{ data: '<NAME>name' },
{ data: '<NAME>' },
{ data: 'birthday' },
{ data: 'address' }
]
})
) | true | # Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/
$(document).ready(() ->
$('#main-table').DataTable({
serverSide: true,
processing: true,
ajax: {
url: '/api/load_users',
dataSrc: 'users'
}
columns: [
{ data: 'PI:NAME:<NAME>END_PIname' },
{ data: 'PI:NAME:<NAME>END_PI' },
{ data: 'birthday' },
{ data: 'address' }
]
})
) |
[
{
"context": "r(app)\n\n live = false\n server.listen 3000, '127.0.0.1', ->\n atomHome = temp.mkdirSync('apm-home-di",
"end": 356,
"score": 0.9997561573982239,
"start": 347,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "('apm-test-package-')\n metadata =\n ... | spec/publish-spec.coffee | jhutchings1/apm | 1,247 | path = require 'path'
fs = require 'fs-plus'
temp = require 'temp'
express = require 'express'
http = require 'http'
apm = require '../lib/apm-cli'
describe 'apm publish', ->
[server] = []
beforeEach ->
spyOnToken()
silenceOutput()
app = express()
server = http.createServer(app)
live = false
server.listen 3000, '127.0.0.1', ->
atomHome = temp.mkdirSync('apm-home-dir-')
process.env.ATOM_HOME = atomHome
process.env.ATOM_API_URL = "http://localhost:3000/api"
process.env.ATOM_RESOURCE_PATH = temp.mkdirSync('atom-resource-path-')
live = true
waitsFor -> live
afterEach ->
done = false
server.close -> done = true
waitsFor -> done
it "validates the package's package.json file", ->
packageToPublish = temp.mkdirSync('apm-test-package-')
fs.writeFileSync(path.join(packageToPublish, 'package.json'), '}{')
process.chdir(packageToPublish)
callback = jasmine.createSpy('callback')
apm.run(['publish'], callback)
waitsFor 'waiting for publish to complete', 600000, ->
callback.callCount is 1
runs ->
expect(callback.mostRecentCall.args[0].message).toBe 'Error parsing package.json file: Unexpected token } in JSON at position 0'
it "validates the package is in a Git repository", ->
packageToPublish = temp.mkdirSync('apm-test-package-')
metadata =
name: 'test'
version: '1.0.0'
fs.writeFileSync(path.join(packageToPublish, 'package.json'), JSON.stringify(metadata))
process.chdir(packageToPublish)
callback = jasmine.createSpy('callback')
apm.run(['publish'], callback)
waitsFor 'waiting for publish to complete', 600000, ->
callback.callCount is 1
runs ->
expect(callback.mostRecentCall.args[0].message).toBe 'Package must be in a Git repository before publishing: https://help.github.com/articles/create-a-repo'
it "validates the engines.atom range in the package.json file", ->
packageToPublish = temp.mkdirSync('apm-test-package-')
metadata =
name: 'test'
version: '1.0.0'
engines:
atom: '><>'
fs.writeFileSync(path.join(packageToPublish, 'package.json'), JSON.stringify(metadata))
process.chdir(packageToPublish)
callback = jasmine.createSpy('callback')
apm.run(['publish'], callback)
waitsFor 'waiting for publish to complete', 600000, ->
callback.callCount is 1
runs ->
expect(callback.mostRecentCall.args[0].message).toBe 'The Atom engine range in the package.json file is invalid: ><>'
it "validates the dependency semver ranges in the package.json file", ->
packageToPublish = temp.mkdirSync('apm-test-package-')
metadata =
name: 'test'
version: '1.0.0'
engines:
atom: '1'
dependencies:
abc: 'git://github.com/user/project.git'
abcd: 'latest'
foo: '^^'
fs.writeFileSync(path.join(packageToPublish, 'package.json'), JSON.stringify(metadata))
process.chdir(packageToPublish)
callback = jasmine.createSpy('callback')
apm.run(['publish'], callback)
waitsFor 'waiting for publish to complete', 600000, ->
callback.callCount is 1
runs ->
expect(callback.mostRecentCall.args[0].message).toBe 'The foo dependency range in the package.json file is invalid: ^^'
it "validates the dev dependency semver ranges in the package.json file", ->
packageToPublish = temp.mkdirSync('apm-test-package-')
metadata =
name: 'test'
version: '1.0.0'
engines:
atom: '1'
dependencies:
foo: '^5'
devDependencies:
abc: 'git://github.com/user/project.git'
abcd: 'latest'
bar: '1,3'
fs.writeFileSync(path.join(packageToPublish, 'package.json'), JSON.stringify(metadata))
process.chdir(packageToPublish)
callback = jasmine.createSpy('callback')
apm.run(['publish'], callback)
waitsFor 'waiting for publish to complete', 600000, ->
callback.callCount is 1
runs ->
expect(callback.mostRecentCall.args[0].message).toBe 'The bar dev dependency range in the package.json file is invalid: 1,3'
| 73740 | path = require 'path'
fs = require 'fs-plus'
temp = require 'temp'
express = require 'express'
http = require 'http'
apm = require '../lib/apm-cli'
describe 'apm publish', ->
[server] = []
beforeEach ->
spyOnToken()
silenceOutput()
app = express()
server = http.createServer(app)
live = false
server.listen 3000, '127.0.0.1', ->
atomHome = temp.mkdirSync('apm-home-dir-')
process.env.ATOM_HOME = atomHome
process.env.ATOM_API_URL = "http://localhost:3000/api"
process.env.ATOM_RESOURCE_PATH = temp.mkdirSync('atom-resource-path-')
live = true
waitsFor -> live
afterEach ->
done = false
server.close -> done = true
waitsFor -> done
it "validates the package's package.json file", ->
packageToPublish = temp.mkdirSync('apm-test-package-')
fs.writeFileSync(path.join(packageToPublish, 'package.json'), '}{')
process.chdir(packageToPublish)
callback = jasmine.createSpy('callback')
apm.run(['publish'], callback)
waitsFor 'waiting for publish to complete', 600000, ->
callback.callCount is 1
runs ->
expect(callback.mostRecentCall.args[0].message).toBe 'Error parsing package.json file: Unexpected token } in JSON at position 0'
it "validates the package is in a Git repository", ->
packageToPublish = temp.mkdirSync('apm-test-package-')
metadata =
name: 'test'
version: '1.0.0'
fs.writeFileSync(path.join(packageToPublish, 'package.json'), JSON.stringify(metadata))
process.chdir(packageToPublish)
callback = jasmine.createSpy('callback')
apm.run(['publish'], callback)
waitsFor 'waiting for publish to complete', 600000, ->
callback.callCount is 1
runs ->
expect(callback.mostRecentCall.args[0].message).toBe 'Package must be in a Git repository before publishing: https://help.github.com/articles/create-a-repo'
it "validates the engines.atom range in the package.json file", ->
packageToPublish = temp.mkdirSync('apm-test-package-')
metadata =
name: '<NAME>'
version: '1.0.0'
engines:
atom: '><>'
fs.writeFileSync(path.join(packageToPublish, 'package.json'), JSON.stringify(metadata))
process.chdir(packageToPublish)
callback = jasmine.createSpy('callback')
apm.run(['publish'], callback)
waitsFor 'waiting for publish to complete', 600000, ->
callback.callCount is 1
runs ->
expect(callback.mostRecentCall.args[0].message).toBe 'The Atom engine range in the package.json file is invalid: ><>'
it "validates the dependency semver ranges in the package.json file", ->
packageToPublish = temp.mkdirSync('apm-test-package-')
metadata =
name: '<NAME>'
version: '1.0.0'
engines:
atom: '1'
dependencies:
abc: 'git://github.com/user/project.git'
abcd: 'latest'
foo: '^^'
fs.writeFileSync(path.join(packageToPublish, 'package.json'), JSON.stringify(metadata))
process.chdir(packageToPublish)
callback = jasmine.createSpy('callback')
apm.run(['publish'], callback)
waitsFor 'waiting for publish to complete', 600000, ->
callback.callCount is 1
runs ->
expect(callback.mostRecentCall.args[0].message).toBe 'The foo dependency range in the package.json file is invalid: ^^'
it "validates the dev dependency semver ranges in the package.json file", ->
packageToPublish = temp.mkdirSync('apm-test-package-')
metadata =
name: '<NAME>'
version: '1.0.0'
engines:
atom: '1'
dependencies:
foo: '^5'
devDependencies:
abc: 'git://github.com/user/project.git'
abcd: 'latest'
bar: '1,3'
fs.writeFileSync(path.join(packageToPublish, 'package.json'), JSON.stringify(metadata))
process.chdir(packageToPublish)
callback = jasmine.createSpy('callback')
apm.run(['publish'], callback)
waitsFor 'waiting for publish to complete', 600000, ->
callback.callCount is 1
runs ->
expect(callback.mostRecentCall.args[0].message).toBe 'The bar dev dependency range in the package.json file is invalid: 1,3'
| true | path = require 'path'
fs = require 'fs-plus'
temp = require 'temp'
express = require 'express'
http = require 'http'
apm = require '../lib/apm-cli'
describe 'apm publish', ->
[server] = []
beforeEach ->
spyOnToken()
silenceOutput()
app = express()
server = http.createServer(app)
live = false
server.listen 3000, '127.0.0.1', ->
atomHome = temp.mkdirSync('apm-home-dir-')
process.env.ATOM_HOME = atomHome
process.env.ATOM_API_URL = "http://localhost:3000/api"
process.env.ATOM_RESOURCE_PATH = temp.mkdirSync('atom-resource-path-')
live = true
waitsFor -> live
afterEach ->
done = false
server.close -> done = true
waitsFor -> done
it "validates the package's package.json file", ->
packageToPublish = temp.mkdirSync('apm-test-package-')
fs.writeFileSync(path.join(packageToPublish, 'package.json'), '}{')
process.chdir(packageToPublish)
callback = jasmine.createSpy('callback')
apm.run(['publish'], callback)
waitsFor 'waiting for publish to complete', 600000, ->
callback.callCount is 1
runs ->
expect(callback.mostRecentCall.args[0].message).toBe 'Error parsing package.json file: Unexpected token } in JSON at position 0'
it "validates the package is in a Git repository", ->
packageToPublish = temp.mkdirSync('apm-test-package-')
metadata =
name: 'test'
version: '1.0.0'
fs.writeFileSync(path.join(packageToPublish, 'package.json'), JSON.stringify(metadata))
process.chdir(packageToPublish)
callback = jasmine.createSpy('callback')
apm.run(['publish'], callback)
waitsFor 'waiting for publish to complete', 600000, ->
callback.callCount is 1
runs ->
expect(callback.mostRecentCall.args[0].message).toBe 'Package must be in a Git repository before publishing: https://help.github.com/articles/create-a-repo'
it "validates the engines.atom range in the package.json file", ->
packageToPublish = temp.mkdirSync('apm-test-package-')
metadata =
name: 'PI:NAME:<NAME>END_PI'
version: '1.0.0'
engines:
atom: '><>'
fs.writeFileSync(path.join(packageToPublish, 'package.json'), JSON.stringify(metadata))
process.chdir(packageToPublish)
callback = jasmine.createSpy('callback')
apm.run(['publish'], callback)
waitsFor 'waiting for publish to complete', 600000, ->
callback.callCount is 1
runs ->
expect(callback.mostRecentCall.args[0].message).toBe 'The Atom engine range in the package.json file is invalid: ><>'
it "validates the dependency semver ranges in the package.json file", ->
packageToPublish = temp.mkdirSync('apm-test-package-')
metadata =
name: 'PI:NAME:<NAME>END_PI'
version: '1.0.0'
engines:
atom: '1'
dependencies:
abc: 'git://github.com/user/project.git'
abcd: 'latest'
foo: '^^'
fs.writeFileSync(path.join(packageToPublish, 'package.json'), JSON.stringify(metadata))
process.chdir(packageToPublish)
callback = jasmine.createSpy('callback')
apm.run(['publish'], callback)
waitsFor 'waiting for publish to complete', 600000, ->
callback.callCount is 1
runs ->
expect(callback.mostRecentCall.args[0].message).toBe 'The foo dependency range in the package.json file is invalid: ^^'
it "validates the dev dependency semver ranges in the package.json file", ->
packageToPublish = temp.mkdirSync('apm-test-package-')
metadata =
name: 'PI:NAME:<NAME>END_PI'
version: '1.0.0'
engines:
atom: '1'
dependencies:
foo: '^5'
devDependencies:
abc: 'git://github.com/user/project.git'
abcd: 'latest'
bar: '1,3'
fs.writeFileSync(path.join(packageToPublish, 'package.json'), JSON.stringify(metadata))
process.chdir(packageToPublish)
callback = jasmine.createSpy('callback')
apm.run(['publish'], callback)
waitsFor 'waiting for publish to complete', 600000, ->
callback.callCount is 1
runs ->
expect(callback.mostRecentCall.args[0].message).toBe 'The bar dev dependency range in the package.json file is invalid: 1,3'
|
[
{
"context": "#\n# Keeps track of a step model\n#\n# @author Torstein Thune\n# @copyright 2016 Microbrew.it\nangular.module('Mi",
"end": 58,
"score": 0.9998700022697449,
"start": 44,
"tag": "NAME",
"value": "Torstein Thune"
}
] | app/step/StepDirective.coffee | Microbrewit/microbrewit-recipe-calculator | 0 | #
# Keeps track of a step model
#
# @author Torstein Thune
# @copyright 2016 Microbrew.it
angular.module('Microbrewit').directive('mbStep', [
() ->
link = (scope, element, attrs, controller, transcludeFn) ->
# Set the type of the step
# @param [String] type Type of step, valid values are ['mash', 'boil', 'sparge', 'fermentation']
scope.setStepType = (type) ->
switch type
when 'mash'
step = scope.step
step.type = 'mash'
step.volume = scope.recipe.mashVolume
step.length = 0
step.temperature = 55
when 'boil'
step = scope.step
step.type = 'boil'
step.volume = scope.recipe.preBoilVolume
step.length = 0
when 'sparge'
step = scope.step
step.type = 'sparge'
step.amount = 0
step.temperature = 55
when 'fermentation'
step = scope.step
step.type = 'fermentation'
step.volume = scope.recipe.volume
step.length = 14
step.temperature = 20
# Add an ingredient to the step
scope.addIngredient = ->
scope.step.ingredients ?= []
scope.step.ingredients.push({})
# Remove an ingredient from the step
# @param [IngredientObject] ingredient
scope.removeIngredient = (ingredient) ->
index = scope.step.ingredients.indexOf(ingredient)
if index isnt -1
scope.step.ingredients.splice(index, 1)
return {
scope:
'step': '='
'remove': '='
'recipe': '='
'refresh': '='
'settings': '='
replace: true
templateUrl: 'recipe/build/step/step.html'
link: link
}
])
| 223638 | #
# Keeps track of a step model
#
# @author <NAME>
# @copyright 2016 Microbrew.it
angular.module('Microbrewit').directive('mbStep', [
() ->
link = (scope, element, attrs, controller, transcludeFn) ->
# Set the type of the step
# @param [String] type Type of step, valid values are ['mash', 'boil', 'sparge', 'fermentation']
scope.setStepType = (type) ->
switch type
when 'mash'
step = scope.step
step.type = 'mash'
step.volume = scope.recipe.mashVolume
step.length = 0
step.temperature = 55
when 'boil'
step = scope.step
step.type = 'boil'
step.volume = scope.recipe.preBoilVolume
step.length = 0
when 'sparge'
step = scope.step
step.type = 'sparge'
step.amount = 0
step.temperature = 55
when 'fermentation'
step = scope.step
step.type = 'fermentation'
step.volume = scope.recipe.volume
step.length = 14
step.temperature = 20
# Add an ingredient to the step
scope.addIngredient = ->
scope.step.ingredients ?= []
scope.step.ingredients.push({})
# Remove an ingredient from the step
# @param [IngredientObject] ingredient
scope.removeIngredient = (ingredient) ->
index = scope.step.ingredients.indexOf(ingredient)
if index isnt -1
scope.step.ingredients.splice(index, 1)
return {
scope:
'step': '='
'remove': '='
'recipe': '='
'refresh': '='
'settings': '='
replace: true
templateUrl: 'recipe/build/step/step.html'
link: link
}
])
| true | #
# Keeps track of a step model
#
# @author PI:NAME:<NAME>END_PI
# @copyright 2016 Microbrew.it
angular.module('Microbrewit').directive('mbStep', [
() ->
link = (scope, element, attrs, controller, transcludeFn) ->
# Set the type of the step
# @param [String] type Type of step, valid values are ['mash', 'boil', 'sparge', 'fermentation']
scope.setStepType = (type) ->
switch type
when 'mash'
step = scope.step
step.type = 'mash'
step.volume = scope.recipe.mashVolume
step.length = 0
step.temperature = 55
when 'boil'
step = scope.step
step.type = 'boil'
step.volume = scope.recipe.preBoilVolume
step.length = 0
when 'sparge'
step = scope.step
step.type = 'sparge'
step.amount = 0
step.temperature = 55
when 'fermentation'
step = scope.step
step.type = 'fermentation'
step.volume = scope.recipe.volume
step.length = 14
step.temperature = 20
# Add an ingredient to the step
scope.addIngredient = ->
scope.step.ingredients ?= []
scope.step.ingredients.push({})
# Remove an ingredient from the step
# @param [IngredientObject] ingredient
scope.removeIngredient = (ingredient) ->
index = scope.step.ingredients.indexOf(ingredient)
if index isnt -1
scope.step.ingredients.splice(index, 1)
return {
scope:
'step': '='
'remove': '='
'recipe': '='
'refresh': '='
'settings': '='
replace: true
templateUrl: 'recipe/build/step/step.html'
link: link
}
])
|
[
{
"context": "hanged = (selectionInfo)->\n\n\t\t\tdxOptions.keyExpr = \"_id\"\n\t\t\tdxOptions.parentIdExpr = \"parent\"\n\t\t\tdxOption",
"end": 8700,
"score": 0.7394411563873291,
"start": 8696,
"tag": "KEY",
"value": "\"_id"
}
] | creator/packages/steedos-workflow/client/views/workflow_tree_menu.coffee | baozhoutao/steedos-platform | 10 | getInboxCategory = (category_id)->
inboxInstancesFlow = []
category = db.categories.findOne({_id: category_id})
if category_id && category_id != '-1'
category_forms = db.forms.find({category: category_id}, {fields: {_id:1}}).fetch();
else
category_forms = db.forms.find({category: {
$in: [null, ""]
}}, {fields: {_id:1}}).fetch();
category_flows = db.flows.find({form: {$in: category_forms.getProperty("_id")}})
category_inbox_count = 0
flow_instances = db.flow_instances.findOne(Steedos.getSpaceId())
category_flows.forEach (flow)->
flow_instance = _.find(flow_instances?.flows, (_f)->
return _f._id == flow._id
)
flow.inbox_count = flow_instance?.count || 0
if flow.inbox_count > 0
category_inbox_count = category_inbox_count + flow.inbox_count
inboxInstancesFlow.push(flow)
return {_id: category_id, name: category?.name, inbox_count: category_inbox_count, inboxInstancesFlow: inboxInstancesFlow}
getDraftCount = ()->
spaceId = Steedos.spaceId()
userId = Meteor.userId()
return db.instances.find({state:"draft",space:spaceId,submitter:userId,$or:[{inbox_users: {$exists:false}}, {inbox_users: []}]}).count()
getInboxBadge = ()->
# spaceId = Steedos.getSpaceId()
appId = Session.get("app_id")
return Steedos.getWorkflowBadge(appId);
getSpaceName = (_id)->
return db.spaces.findOne({_id: _id})?.name
getIsShowMonitorBox = ()->
if Meteor.settings.public?.workflow?.onlyFlowAdminsShowMonitorBox
space = db.spaces.findOne(Session.get("spaceId"))
if !space
return false
if space.admins?.includes(Meteor.userId())
return true
else
flow_ids = WorkflowManager.getMyAdminOrMonitorFlows()
if _.isEmpty(flow_ids)
return false
else
return true
return true
getInboxSpaces = ()->
return db.steedos_keyvalues.find({key: "badge"}).fetch().filter (_item)->
if _item?.value["workflow"] > 0 && _item.space && _item.space != Session.get("spaceId")
if db.spaces.findOne({_id: _item.space})
return _item
getBoxs = ()->
spaceId = Steedos.getSpaceId()
boxs = [
{
_id: "inbox"
name: t("inbox")
url: "/workflow/space/#{spaceId}/inbox/"
}
{
_id: "outbox"
name: t("outbox")
url: "/workflow/space/#{spaceId}/outbox/"
}
{
_id: "mybox"
name: t("my_instances")
}
{
_id: "draft"
name: t("draft")
url: "/workflow/space/#{spaceId}/draft/"
parent: "mybox"
}
{
_id: "pending"
name: t("pending")
url: "/workflow/space/#{spaceId}/pending/"
parent: "mybox"
}
{
_id: "completed"
name: t("completed")
url: "/workflow/space/#{spaceId}/completed/"
parent: "mybox"
}
]
if getIsShowMonitorBox()
# 把监控箱插入到已审批后面
boxs.splice 2, 0,
_id: "monitor"
name: t("monitor")
url: "/workflow/space/#{spaceId}/monitor/"
otherInboxs = getInboxSpaces()
otherInboxs.forEach (n, i)->
spaceName = getSpaceName(n.space)
count = Steedos.getBadge "workflow", n.space
otherItem =
_id: n._id
name: spaceName
url: "/workflow/space/#{n.space}/inbox/"
inbox_count: count
isOtherInbox: true
if i == 0
otherItem.isFirstOtherInbox = true
boxs.push otherItem
return boxs
getCategories = ()->
categories = WorkflowManager.getSpaceCategories(Session.get("spaceId"), Session.get("workflow_categories"))
categories.push({ _id: "-1", name: TAPi18n.__("workflow_no_category"), space: Session.get('spaceId') })
return categories
getStoreItems = ()->
boxs = getBoxs()
categories = getCategories()
flows = []
spaceId = Steedos.getSpaceId()
if boxs and categories
if _.isArray(boxs) and boxs.length
selectedItem = Tracker.nonreactive ()->
return Session.get("box")
unless selectedItem
# 默认选中第一个菜单,即Inbox
selectedItem = "inbox"
boxs.forEach (item)->
item.isRoot = true
switch item._id
when "inbox"
item.icon = 'ion ion-archive'
when "outbox"
item.icon = 'ion ion-android-done-all'
when "mybox"
item.icon = 'ion ion-android-person'
when "draft"
item.icon = 'ion ion-compose'
when "pending"
item.icon = 'ion ion-ios-loop'
when "completed"
item.icon = 'ion ion-android-checkbox-outline'
when "monitor"
item.icon = 'ion ion-eye'
else
item.icon = 'ion ion-archive'
item.hasItems = item._id == "inbox" && !!categories.length
if item._id == "mybox"
item.hasItems = true
item.expanded = item.hasItems
if item._id == "draft"
item.draft_count = getDraftCount()
else if item._id == "inbox"
item.inbox_count = getInboxBadge()
if item._id == selectedItem
item.selected = true
selectedItem = Tracker.nonreactive ()->
return Session.get("workflowCategory")
categories.forEach (item)->
item.parent = "inbox"
item.isCategory = true
item.url = "/workflow/space/#{spaceId}/inbox/"
categoryItemData = getInboxCategory item._id
item.inbox_count = categoryItemData?.inbox_count
item.hasItems = item.inbox_count > 0
if item._id == selectedItem
item.selected = true
parentBox = boxs.find((n)-> return n._id == item.parent)
if parentBox
parentBox.expanded = true
parentBox.selected = false
selectedItem = Tracker.nonreactive ()->
return Session.get("flowId")
categoryItemData?.inboxInstancesFlow?.forEach (flow)->
flow.parent = item._id
flow.isFlow = true
flow.url = "/workflow/space/#{spaceId}/inbox/"
flow.hasItems = false
if flow._id == selectedItem
flow.selected = true
parentCategory = categories.find((n)-> return n._id == flow.parent)
if parentCategory
parentCategory.expanded = true
parentCategory.selected = false
flows.push flow
categories = categories.filter (n)-> return n.hasItems
return _.union boxs, categories, flows
selectMenu = (_id)->
# 选中dxTreeView中某项
this.dxTreeViewInstance?.selectItem(this.$(".dx-treeview-node[data-item-id=#{_id}]"))
Template.workflowTreeMenu.onCreated ->
Template.workflowTreeMenu.onRendered ->
self = this
self.autorun (c)->
spaceId = Steedos.spaceId()
userId = Meteor.userId()
loginToken = Accounts._storedLoginToken()
if spaceId and userId
self.dxTreeViewInstance?.dispose()
storeItems = getStoreItems()
console.log "Reloading instance dxTreeViewInstance"
if !storeItems
return;
dxOptions =
searchEnabled: false
dataSource:
store: storeItems
itemTemplate: (itemData, itemIndex, itemElement)->
itemElement.attr("title", itemData.name)
if itemData.icon
itemElement.append("<i class=\"dx-icon #{itemData.icon}\"></i>");
itemElement.append("<span>" + itemData.name + "</span>");
count = if itemData.draft_count then itemData.draft_count else itemData.inbox_count
if count
if itemData._id == "draft" or itemData.isFlow
bg = "bg-special"
else if itemData.isRoot
bg = "bg-red"
else
bg = "bg-gray"
htmlText = """
<span class="pull-right-container">
<span class="label pull-right #{bg}">#{count}</span>
</span>
"""
itemElement.append(htmlText)
if itemData.isFirstOtherInbox
Meteor.defer ()->
itemElement.closest(".dx-treeview-node").addClass("other-inbox-node").addClass("first-other-inbox-node")
else if itemData.isOtherInbox
Meteor.defer ()->
itemElement.closest(".dx-treeview-node").addClass("other-inbox-node")
sidebar_multiple = false
dxOptions.selectNodesRecursive = false
dxOptions.selectByClick = true
dxOptions.selectionMode = if sidebar_multiple then "multiple" else "single"
dxOptions.showCheckBoxesMode = if sidebar_multiple then "normal" else "none"
dxOptions.onItemClick = (selectionInfo)->
if selectionInfo.itemData._id == "mybox"
# 我的文件菜单不需要选中
selectionInfo.event.preventDefault()
if selectionInfo.node.selected
# 如果选项已经选中则不需要变更状态,即不可以把已经选中的状态变更为未选中
selectionInfo.event.preventDefault()
else
if selectionInfo.itemData.isRoot
# 切换箱子的时候清空搜索条件
$("#instance_search_tip_close_btn").click()
url = selectionInfo.itemData.url
if url
Session.set("workflowCategory", undefined)
FlowRouter.go url
else if selectionInfo.itemData.isCategory
url = selectionInfo.itemData.url
if url
Session.set("flowId", false)
Session.set("workflowCategory",selectionInfo.itemData._id || "-1")
FlowRouter.go url
else if selectionInfo.itemData.isFlow
url = selectionInfo.itemData.url
if url
Session.set("workflowCategory",selectionInfo.itemData.parent || "-1")
Session.set("flowId", selectionInfo.itemData._id);
FlowRouter.go url
dxOptions.onItemSelectionChanged = (selectionInfo)->
dxOptions.keyExpr = "_id"
dxOptions.parentIdExpr = "parent"
dxOptions.displayExpr = "name"
dxOptions.hasItemsExpr = "hasItems"
dxOptions.rootValue = null
dxOptions.dataStructure = "plain"
dxOptions.virtualModeEnabled = true
# dxOptions.onItemExpanded = ()->
# dxOptions.onContentReady = ()->
self.dxTreeViewInstance = self.$(".gridSidebarContainer").dxTreeView(dxOptions).dxTreeView('instance')
selectMenu = selectMenu.bind(self)
self.autorun (c)->
Meteor.defer ()->
selectMenu Session.get("box")
| 28598 | getInboxCategory = (category_id)->
inboxInstancesFlow = []
category = db.categories.findOne({_id: category_id})
if category_id && category_id != '-1'
category_forms = db.forms.find({category: category_id}, {fields: {_id:1}}).fetch();
else
category_forms = db.forms.find({category: {
$in: [null, ""]
}}, {fields: {_id:1}}).fetch();
category_flows = db.flows.find({form: {$in: category_forms.getProperty("_id")}})
category_inbox_count = 0
flow_instances = db.flow_instances.findOne(Steedos.getSpaceId())
category_flows.forEach (flow)->
flow_instance = _.find(flow_instances?.flows, (_f)->
return _f._id == flow._id
)
flow.inbox_count = flow_instance?.count || 0
if flow.inbox_count > 0
category_inbox_count = category_inbox_count + flow.inbox_count
inboxInstancesFlow.push(flow)
return {_id: category_id, name: category?.name, inbox_count: category_inbox_count, inboxInstancesFlow: inboxInstancesFlow}
getDraftCount = ()->
spaceId = Steedos.spaceId()
userId = Meteor.userId()
return db.instances.find({state:"draft",space:spaceId,submitter:userId,$or:[{inbox_users: {$exists:false}}, {inbox_users: []}]}).count()
getInboxBadge = ()->
# spaceId = Steedos.getSpaceId()
appId = Session.get("app_id")
return Steedos.getWorkflowBadge(appId);
getSpaceName = (_id)->
return db.spaces.findOne({_id: _id})?.name
getIsShowMonitorBox = ()->
if Meteor.settings.public?.workflow?.onlyFlowAdminsShowMonitorBox
space = db.spaces.findOne(Session.get("spaceId"))
if !space
return false
if space.admins?.includes(Meteor.userId())
return true
else
flow_ids = WorkflowManager.getMyAdminOrMonitorFlows()
if _.isEmpty(flow_ids)
return false
else
return true
return true
getInboxSpaces = ()->
return db.steedos_keyvalues.find({key: "badge"}).fetch().filter (_item)->
if _item?.value["workflow"] > 0 && _item.space && _item.space != Session.get("spaceId")
if db.spaces.findOne({_id: _item.space})
return _item
getBoxs = ()->
spaceId = Steedos.getSpaceId()
boxs = [
{
_id: "inbox"
name: t("inbox")
url: "/workflow/space/#{spaceId}/inbox/"
}
{
_id: "outbox"
name: t("outbox")
url: "/workflow/space/#{spaceId}/outbox/"
}
{
_id: "mybox"
name: t("my_instances")
}
{
_id: "draft"
name: t("draft")
url: "/workflow/space/#{spaceId}/draft/"
parent: "mybox"
}
{
_id: "pending"
name: t("pending")
url: "/workflow/space/#{spaceId}/pending/"
parent: "mybox"
}
{
_id: "completed"
name: t("completed")
url: "/workflow/space/#{spaceId}/completed/"
parent: "mybox"
}
]
if getIsShowMonitorBox()
# 把监控箱插入到已审批后面
boxs.splice 2, 0,
_id: "monitor"
name: t("monitor")
url: "/workflow/space/#{spaceId}/monitor/"
otherInboxs = getInboxSpaces()
otherInboxs.forEach (n, i)->
spaceName = getSpaceName(n.space)
count = Steedos.getBadge "workflow", n.space
otherItem =
_id: n._id
name: spaceName
url: "/workflow/space/#{n.space}/inbox/"
inbox_count: count
isOtherInbox: true
if i == 0
otherItem.isFirstOtherInbox = true
boxs.push otherItem
return boxs
getCategories = ()->
categories = WorkflowManager.getSpaceCategories(Session.get("spaceId"), Session.get("workflow_categories"))
categories.push({ _id: "-1", name: TAPi18n.__("workflow_no_category"), space: Session.get('spaceId') })
return categories
getStoreItems = ()->
boxs = getBoxs()
categories = getCategories()
flows = []
spaceId = Steedos.getSpaceId()
if boxs and categories
if _.isArray(boxs) and boxs.length
selectedItem = Tracker.nonreactive ()->
return Session.get("box")
unless selectedItem
# 默认选中第一个菜单,即Inbox
selectedItem = "inbox"
boxs.forEach (item)->
item.isRoot = true
switch item._id
when "inbox"
item.icon = 'ion ion-archive'
when "outbox"
item.icon = 'ion ion-android-done-all'
when "mybox"
item.icon = 'ion ion-android-person'
when "draft"
item.icon = 'ion ion-compose'
when "pending"
item.icon = 'ion ion-ios-loop'
when "completed"
item.icon = 'ion ion-android-checkbox-outline'
when "monitor"
item.icon = 'ion ion-eye'
else
item.icon = 'ion ion-archive'
item.hasItems = item._id == "inbox" && !!categories.length
if item._id == "mybox"
item.hasItems = true
item.expanded = item.hasItems
if item._id == "draft"
item.draft_count = getDraftCount()
else if item._id == "inbox"
item.inbox_count = getInboxBadge()
if item._id == selectedItem
item.selected = true
selectedItem = Tracker.nonreactive ()->
return Session.get("workflowCategory")
categories.forEach (item)->
item.parent = "inbox"
item.isCategory = true
item.url = "/workflow/space/#{spaceId}/inbox/"
categoryItemData = getInboxCategory item._id
item.inbox_count = categoryItemData?.inbox_count
item.hasItems = item.inbox_count > 0
if item._id == selectedItem
item.selected = true
parentBox = boxs.find((n)-> return n._id == item.parent)
if parentBox
parentBox.expanded = true
parentBox.selected = false
selectedItem = Tracker.nonreactive ()->
return Session.get("flowId")
categoryItemData?.inboxInstancesFlow?.forEach (flow)->
flow.parent = item._id
flow.isFlow = true
flow.url = "/workflow/space/#{spaceId}/inbox/"
flow.hasItems = false
if flow._id == selectedItem
flow.selected = true
parentCategory = categories.find((n)-> return n._id == flow.parent)
if parentCategory
parentCategory.expanded = true
parentCategory.selected = false
flows.push flow
categories = categories.filter (n)-> return n.hasItems
return _.union boxs, categories, flows
selectMenu = (_id)->
# 选中dxTreeView中某项
this.dxTreeViewInstance?.selectItem(this.$(".dx-treeview-node[data-item-id=#{_id}]"))
Template.workflowTreeMenu.onCreated ->
Template.workflowTreeMenu.onRendered ->
self = this
self.autorun (c)->
spaceId = Steedos.spaceId()
userId = Meteor.userId()
loginToken = Accounts._storedLoginToken()
if spaceId and userId
self.dxTreeViewInstance?.dispose()
storeItems = getStoreItems()
console.log "Reloading instance dxTreeViewInstance"
if !storeItems
return;
dxOptions =
searchEnabled: false
dataSource:
store: storeItems
itemTemplate: (itemData, itemIndex, itemElement)->
itemElement.attr("title", itemData.name)
if itemData.icon
itemElement.append("<i class=\"dx-icon #{itemData.icon}\"></i>");
itemElement.append("<span>" + itemData.name + "</span>");
count = if itemData.draft_count then itemData.draft_count else itemData.inbox_count
if count
if itemData._id == "draft" or itemData.isFlow
bg = "bg-special"
else if itemData.isRoot
bg = "bg-red"
else
bg = "bg-gray"
htmlText = """
<span class="pull-right-container">
<span class="label pull-right #{bg}">#{count}</span>
</span>
"""
itemElement.append(htmlText)
if itemData.isFirstOtherInbox
Meteor.defer ()->
itemElement.closest(".dx-treeview-node").addClass("other-inbox-node").addClass("first-other-inbox-node")
else if itemData.isOtherInbox
Meteor.defer ()->
itemElement.closest(".dx-treeview-node").addClass("other-inbox-node")
sidebar_multiple = false
dxOptions.selectNodesRecursive = false
dxOptions.selectByClick = true
dxOptions.selectionMode = if sidebar_multiple then "multiple" else "single"
dxOptions.showCheckBoxesMode = if sidebar_multiple then "normal" else "none"
dxOptions.onItemClick = (selectionInfo)->
if selectionInfo.itemData._id == "mybox"
# 我的文件菜单不需要选中
selectionInfo.event.preventDefault()
if selectionInfo.node.selected
# 如果选项已经选中则不需要变更状态,即不可以把已经选中的状态变更为未选中
selectionInfo.event.preventDefault()
else
if selectionInfo.itemData.isRoot
# 切换箱子的时候清空搜索条件
$("#instance_search_tip_close_btn").click()
url = selectionInfo.itemData.url
if url
Session.set("workflowCategory", undefined)
FlowRouter.go url
else if selectionInfo.itemData.isCategory
url = selectionInfo.itemData.url
if url
Session.set("flowId", false)
Session.set("workflowCategory",selectionInfo.itemData._id || "-1")
FlowRouter.go url
else if selectionInfo.itemData.isFlow
url = selectionInfo.itemData.url
if url
Session.set("workflowCategory",selectionInfo.itemData.parent || "-1")
Session.set("flowId", selectionInfo.itemData._id);
FlowRouter.go url
dxOptions.onItemSelectionChanged = (selectionInfo)->
dxOptions.keyExpr = <KEY>"
dxOptions.parentIdExpr = "parent"
dxOptions.displayExpr = "name"
dxOptions.hasItemsExpr = "hasItems"
dxOptions.rootValue = null
dxOptions.dataStructure = "plain"
dxOptions.virtualModeEnabled = true
# dxOptions.onItemExpanded = ()->
# dxOptions.onContentReady = ()->
self.dxTreeViewInstance = self.$(".gridSidebarContainer").dxTreeView(dxOptions).dxTreeView('instance')
selectMenu = selectMenu.bind(self)
self.autorun (c)->
Meteor.defer ()->
selectMenu Session.get("box")
| true | getInboxCategory = (category_id)->
inboxInstancesFlow = []
category = db.categories.findOne({_id: category_id})
if category_id && category_id != '-1'
category_forms = db.forms.find({category: category_id}, {fields: {_id:1}}).fetch();
else
category_forms = db.forms.find({category: {
$in: [null, ""]
}}, {fields: {_id:1}}).fetch();
category_flows = db.flows.find({form: {$in: category_forms.getProperty("_id")}})
category_inbox_count = 0
flow_instances = db.flow_instances.findOne(Steedos.getSpaceId())
category_flows.forEach (flow)->
flow_instance = _.find(flow_instances?.flows, (_f)->
return _f._id == flow._id
)
flow.inbox_count = flow_instance?.count || 0
if flow.inbox_count > 0
category_inbox_count = category_inbox_count + flow.inbox_count
inboxInstancesFlow.push(flow)
return {_id: category_id, name: category?.name, inbox_count: category_inbox_count, inboxInstancesFlow: inboxInstancesFlow}
getDraftCount = ()->
spaceId = Steedos.spaceId()
userId = Meteor.userId()
return db.instances.find({state:"draft",space:spaceId,submitter:userId,$or:[{inbox_users: {$exists:false}}, {inbox_users: []}]}).count()
getInboxBadge = ()->
# spaceId = Steedos.getSpaceId()
appId = Session.get("app_id")
return Steedos.getWorkflowBadge(appId);
getSpaceName = (_id)->
return db.spaces.findOne({_id: _id})?.name
getIsShowMonitorBox = ()->
if Meteor.settings.public?.workflow?.onlyFlowAdminsShowMonitorBox
space = db.spaces.findOne(Session.get("spaceId"))
if !space
return false
if space.admins?.includes(Meteor.userId())
return true
else
flow_ids = WorkflowManager.getMyAdminOrMonitorFlows()
if _.isEmpty(flow_ids)
return false
else
return true
return true
getInboxSpaces = ()->
return db.steedos_keyvalues.find({key: "badge"}).fetch().filter (_item)->
if _item?.value["workflow"] > 0 && _item.space && _item.space != Session.get("spaceId")
if db.spaces.findOne({_id: _item.space})
return _item
getBoxs = ()->
spaceId = Steedos.getSpaceId()
boxs = [
{
_id: "inbox"
name: t("inbox")
url: "/workflow/space/#{spaceId}/inbox/"
}
{
_id: "outbox"
name: t("outbox")
url: "/workflow/space/#{spaceId}/outbox/"
}
{
_id: "mybox"
name: t("my_instances")
}
{
_id: "draft"
name: t("draft")
url: "/workflow/space/#{spaceId}/draft/"
parent: "mybox"
}
{
_id: "pending"
name: t("pending")
url: "/workflow/space/#{spaceId}/pending/"
parent: "mybox"
}
{
_id: "completed"
name: t("completed")
url: "/workflow/space/#{spaceId}/completed/"
parent: "mybox"
}
]
if getIsShowMonitorBox()
# 把监控箱插入到已审批后面
boxs.splice 2, 0,
_id: "monitor"
name: t("monitor")
url: "/workflow/space/#{spaceId}/monitor/"
otherInboxs = getInboxSpaces()
otherInboxs.forEach (n, i)->
spaceName = getSpaceName(n.space)
count = Steedos.getBadge "workflow", n.space
otherItem =
_id: n._id
name: spaceName
url: "/workflow/space/#{n.space}/inbox/"
inbox_count: count
isOtherInbox: true
if i == 0
otherItem.isFirstOtherInbox = true
boxs.push otherItem
return boxs
getCategories = ()->
categories = WorkflowManager.getSpaceCategories(Session.get("spaceId"), Session.get("workflow_categories"))
categories.push({ _id: "-1", name: TAPi18n.__("workflow_no_category"), space: Session.get('spaceId') })
return categories
getStoreItems = ()->
boxs = getBoxs()
categories = getCategories()
flows = []
spaceId = Steedos.getSpaceId()
if boxs and categories
if _.isArray(boxs) and boxs.length
selectedItem = Tracker.nonreactive ()->
return Session.get("box")
unless selectedItem
# 默认选中第一个菜单,即Inbox
selectedItem = "inbox"
boxs.forEach (item)->
item.isRoot = true
switch item._id
when "inbox"
item.icon = 'ion ion-archive'
when "outbox"
item.icon = 'ion ion-android-done-all'
when "mybox"
item.icon = 'ion ion-android-person'
when "draft"
item.icon = 'ion ion-compose'
when "pending"
item.icon = 'ion ion-ios-loop'
when "completed"
item.icon = 'ion ion-android-checkbox-outline'
when "monitor"
item.icon = 'ion ion-eye'
else
item.icon = 'ion ion-archive'
item.hasItems = item._id == "inbox" && !!categories.length
if item._id == "mybox"
item.hasItems = true
item.expanded = item.hasItems
if item._id == "draft"
item.draft_count = getDraftCount()
else if item._id == "inbox"
item.inbox_count = getInboxBadge()
if item._id == selectedItem
item.selected = true
selectedItem = Tracker.nonreactive ()->
return Session.get("workflowCategory")
categories.forEach (item)->
item.parent = "inbox"
item.isCategory = true
item.url = "/workflow/space/#{spaceId}/inbox/"
categoryItemData = getInboxCategory item._id
item.inbox_count = categoryItemData?.inbox_count
item.hasItems = item.inbox_count > 0
if item._id == selectedItem
item.selected = true
parentBox = boxs.find((n)-> return n._id == item.parent)
if parentBox
parentBox.expanded = true
parentBox.selected = false
selectedItem = Tracker.nonreactive ()->
return Session.get("flowId")
categoryItemData?.inboxInstancesFlow?.forEach (flow)->
flow.parent = item._id
flow.isFlow = true
flow.url = "/workflow/space/#{spaceId}/inbox/"
flow.hasItems = false
if flow._id == selectedItem
flow.selected = true
parentCategory = categories.find((n)-> return n._id == flow.parent)
if parentCategory
parentCategory.expanded = true
parentCategory.selected = false
flows.push flow
categories = categories.filter (n)-> return n.hasItems
return _.union boxs, categories, flows
selectMenu = (_id)->
# 选中dxTreeView中某项
this.dxTreeViewInstance?.selectItem(this.$(".dx-treeview-node[data-item-id=#{_id}]"))
Template.workflowTreeMenu.onCreated ->
Template.workflowTreeMenu.onRendered ->
self = this
self.autorun (c)->
spaceId = Steedos.spaceId()
userId = Meteor.userId()
loginToken = Accounts._storedLoginToken()
if spaceId and userId
self.dxTreeViewInstance?.dispose()
storeItems = getStoreItems()
console.log "Reloading instance dxTreeViewInstance"
if !storeItems
return;
dxOptions =
searchEnabled: false
dataSource:
store: storeItems
itemTemplate: (itemData, itemIndex, itemElement)->
itemElement.attr("title", itemData.name)
if itemData.icon
itemElement.append("<i class=\"dx-icon #{itemData.icon}\"></i>");
itemElement.append("<span>" + itemData.name + "</span>");
count = if itemData.draft_count then itemData.draft_count else itemData.inbox_count
if count
if itemData._id == "draft" or itemData.isFlow
bg = "bg-special"
else if itemData.isRoot
bg = "bg-red"
else
bg = "bg-gray"
htmlText = """
<span class="pull-right-container">
<span class="label pull-right #{bg}">#{count}</span>
</span>
"""
itemElement.append(htmlText)
if itemData.isFirstOtherInbox
Meteor.defer ()->
itemElement.closest(".dx-treeview-node").addClass("other-inbox-node").addClass("first-other-inbox-node")
else if itemData.isOtherInbox
Meteor.defer ()->
itemElement.closest(".dx-treeview-node").addClass("other-inbox-node")
sidebar_multiple = false
dxOptions.selectNodesRecursive = false
dxOptions.selectByClick = true
dxOptions.selectionMode = if sidebar_multiple then "multiple" else "single"
dxOptions.showCheckBoxesMode = if sidebar_multiple then "normal" else "none"
dxOptions.onItemClick = (selectionInfo)->
if selectionInfo.itemData._id == "mybox"
# 我的文件菜单不需要选中
selectionInfo.event.preventDefault()
if selectionInfo.node.selected
# 如果选项已经选中则不需要变更状态,即不可以把已经选中的状态变更为未选中
selectionInfo.event.preventDefault()
else
if selectionInfo.itemData.isRoot
# 切换箱子的时候清空搜索条件
$("#instance_search_tip_close_btn").click()
url = selectionInfo.itemData.url
if url
Session.set("workflowCategory", undefined)
FlowRouter.go url
else if selectionInfo.itemData.isCategory
url = selectionInfo.itemData.url
if url
Session.set("flowId", false)
Session.set("workflowCategory",selectionInfo.itemData._id || "-1")
FlowRouter.go url
else if selectionInfo.itemData.isFlow
url = selectionInfo.itemData.url
if url
Session.set("workflowCategory",selectionInfo.itemData.parent || "-1")
Session.set("flowId", selectionInfo.itemData._id);
FlowRouter.go url
dxOptions.onItemSelectionChanged = (selectionInfo)->
dxOptions.keyExpr = PI:KEY:<KEY>END_PI"
dxOptions.parentIdExpr = "parent"
dxOptions.displayExpr = "name"
dxOptions.hasItemsExpr = "hasItems"
dxOptions.rootValue = null
dxOptions.dataStructure = "plain"
dxOptions.virtualModeEnabled = true
# dxOptions.onItemExpanded = ()->
# dxOptions.onContentReady = ()->
self.dxTreeViewInstance = self.$(".gridSidebarContainer").dxTreeView(dxOptions).dxTreeView('instance')
selectMenu = selectMenu.bind(self)
self.autorun (c)->
Meteor.defer ()->
selectMenu Session.get("box")
|
[
{
"context": "bers: [{\n image: 'team/mbg.jpg'\n name: 'Missouri Botanical Garden'\n description: 'Founded in 1859, the Missour",
"end": 139,
"score": 0.9981200695037842,
"start": 114,
"tag": "NAME",
"value": "Missouri Botanical Garden"
},
{
"context": "://biodiversity... | content/team.coffee | zooniverse/sciencegossip | 3 | module.exports =
organizations:
title: "Partners"
members: [{
image: 'team/mbg.jpg'
name: 'Missouri Botanical Garden'
description: 'Founded in 1859, the Missouri Botanical Garden is the United States’ oldest botanical garden in continuous operation and a National Historic Landmark located in St. Louis, MO. The Garden is a center for botanical research and science education, and has served as the technical development team for the Biodiversity Heritage Library since 2007.'
},{
image: 'team/bhl.jpg'
name: 'Biodiversity Heritage Library'
description: 'The Biodiversity Heritage Library (BHL) is a consortium of natural history and botanical libraries that cooperate to digitize the legacy literature of biodiversity held in their collections and to make that literature available for open access and responsible use as a part of a global “biodiversity commons.”'
url: ['http://biodiversitylibrary.org', 'https://twitter.com/biodivlibrary']
},{
image: 'team/conscicom.jpg'
name: 'Constructing Scientific Communities'
description: 'This <abbr title="Arts & Humanities Research Council">AHRC</abbr> Science in Culture project brings together historical and literary research in the nineteenth century with contemporary scientific practice, looking at the ways in which patterns of popular communication and engagement in nineteenth-century science can offer models for current practice.'
url: ['http://conscicom.org/', 'https://twitter.com/conscicom']
},{
image: 'team/zooniverse.jpg'
name: 'Zooniverse'
description: 'The Zooniverse is home to the internet’s largest, most popular and most successful citizen science projects. The Zooniverse and the suite of projects it contains is produced, maintained and developed by the Citizen Science Alliance (CSA). The member institutions of the CSA work with many academic and other partners around the world to produce projects that use the efforts and ability of volunteers to help scientists and researchers.'
url: ['https://www.zooniverse.org/', 'https://twitter.com/the_zooniverse', 'https://github.com/zooniverse']
}]
missouri:
title: "Missouri Botanical Garden"
members: [{
image: 'team/trish.jpg'
name: 'Trish Rose-Sandler'
location: 'St Louis, MO, USA'
description: '''
Though a humanities scholar and librarian by training, was hired by the Biodiversity Heritage Library over 5 years ago to serve as their metadata guru. Now manages several BHL-related projects including Art of Life and Purposeful Gaming and is based in the Center for Biodiversity Informatics at Missouri Botanical Garden.
'''
},{
image: 'team/william.jpg'
name: 'William Ulate'
location: 'St Louis, MO, USA'
description: '''
A kind (of) Computer Scientist, father of one, who got into Biodiversity Informatics 15 years ago and then flew from Costa Rica to work for global Biodiversity Heritage Library based in the Center for Biodiversity Informatics at Missouri Botanical Garden.
'''
},{
image: 'team/mike.jpg'
name: 'Mike Lichtenberg'
location: 'St Louis, MO, USA'
description: '''
Software developer with more than 20 years of experience who has been involved with the Biodiversity Heritage Library since 2007.
'''
}]
conscicom:
title: "Constructing Scientific Communities"
members: [{
image: 'team/sally.jpg'
name: 'Sally Shuttleworth'
location: 'Oxford, UK'
description: 'Principal Investigator'
},{
image: 'team/chris.jpg'
name: 'Chris Lintott'
location: 'Oxford, UK'
description: 'Co-investigator'
url: 'http://twitter.com/chrislintott'
},{
image: 'team/geoff.jpg'
name: 'Geoffrey Belknap'
location: 'Leicester, UK'
description: 'Postdoctoral researcher, Constructing Scientific Communities'
url: 'http://twitter.com/geoffreybelknap'
}]
developers:
title: "Zooniverse"
members: [{
image: 'team/jim.jpg'
name: 'Jim O\'Donnell'
location: 'Oxford, UK'
description: 'Web developer'
url: 'http://twitter.com/pekingspring'
},{
image: 'team/victoria.jpg'
name: 'Victoria Van Hyning'
location: 'Oxford, UK'
description: 'Humanities project lead'
url: 'http://twitter.com/VanHyningV'
},{
image: 'team/adam.jpg'
name: 'Adam McMaster'
location: 'Oxford, UK'
description: 'Web infrastructure'
url: 'http://twitter.com/astopy'
}]
| 50145 | module.exports =
organizations:
title: "Partners"
members: [{
image: 'team/mbg.jpg'
name: '<NAME>'
description: 'Founded in 1859, the Missouri Botanical Garden is the United States’ oldest botanical garden in continuous operation and a National Historic Landmark located in St. Louis, MO. The Garden is a center for botanical research and science education, and has served as the technical development team for the Biodiversity Heritage Library since 2007.'
},{
image: 'team/bhl.jpg'
name: 'Biodiversity Heritage Library'
description: 'The Biodiversity Heritage Library (BHL) is a consortium of natural history and botanical libraries that cooperate to digitize the legacy literature of biodiversity held in their collections and to make that literature available for open access and responsible use as a part of a global “biodiversity commons.”'
url: ['http://biodiversitylibrary.org', 'https://twitter.com/biodivlibrary']
},{
image: 'team/conscicom.jpg'
name: 'Constructing Scientific Communities'
description: 'This <abbr title="Arts & Humanities Research Council">AHRC</abbr> Science in Culture project brings together historical and literary research in the nineteenth century with contemporary scientific practice, looking at the ways in which patterns of popular communication and engagement in nineteenth-century science can offer models for current practice.'
url: ['http://conscicom.org/', 'https://twitter.com/conscicom']
},{
image: 'team/zooniverse.jpg'
name: 'Zooniverse'
description: 'The Zooniverse is home to the internet’s largest, most popular and most successful citizen science projects. The Zooniverse and the suite of projects it contains is produced, maintained and developed by the Citizen Science Alliance (CSA). The member institutions of the CSA work with many academic and other partners around the world to produce projects that use the efforts and ability of volunteers to help scientists and researchers.'
url: ['https://www.zooniverse.org/', 'https://twitter.com/the_zooniverse', 'https://github.com/zooniverse']
}]
missouri:
title: "Missouri Botanical Garden"
members: [{
image: 'team/trish.jpg'
name: '<NAME>'
location: 'St Louis, MO, USA'
description: '''
Though a humanities scholar and librarian by training, was hired by the Biodiversity Heritage Library over 5 years ago to serve as their metadata guru. Now manages several BHL-related projects including Art of Life and Purposeful Gaming and is based in the Center for Biodiversity Informatics at Missouri Botanical Garden.
'''
},{
image: 'team/william.jpg'
name: '<NAME>'
location: 'St Louis, MO, USA'
description: '''
A kind (of) Computer Scientist, father of one, who got into Biodiversity Informatics 15 years ago and then flew from Costa Rica to work for global Biodiversity Heritage Library based in the Center for Biodiversity Informatics at Missouri Botanical Garden.
'''
},{
image: 'team/mike.jpg'
name: '<NAME>'
location: 'St Louis, MO, USA'
description: '''
Software developer with more than 20 years of experience who has been involved with the Biodiversity Heritage Library since 2007.
'''
}]
conscicom:
title: "Constructing Scientific Communities"
members: [{
image: 'team/sally.jpg'
name: '<NAME>'
location: 'Oxford, UK'
description: 'Principal Investigator'
},{
image: 'team/chris.jpg'
name: '<NAME>'
location: 'Oxford, UK'
description: 'Co-investigator'
url: 'http://twitter.com/chrislintott'
},{
image: 'team/geoff.jpg'
name: '<NAME>'
location: 'Leicester, UK'
description: 'Postdoctoral researcher, Constructing Scientific Communities'
url: 'http://twitter.com/geoffreybelknap'
}]
developers:
title: "Zooniverse"
members: [{
image: 'team/jim.jpg'
name: '<NAME>'
location: 'Oxford, UK'
description: 'Web developer'
url: 'http://twitter.com/pekingspring'
},{
image: 'team/victoria.jpg'
name: '<NAME>'
location: 'Oxford, UK'
description: 'Humanities project lead'
url: 'http://twitter.com/VanHyningV'
},{
image: 'team/adam.jpg'
name: '<NAME>'
location: 'Oxford, UK'
description: 'Web infrastructure'
url: 'http://twitter.com/astopy'
}]
| true | module.exports =
organizations:
title: "Partners"
members: [{
image: 'team/mbg.jpg'
name: 'PI:NAME:<NAME>END_PI'
description: 'Founded in 1859, the Missouri Botanical Garden is the United States’ oldest botanical garden in continuous operation and a National Historic Landmark located in St. Louis, MO. The Garden is a center for botanical research and science education, and has served as the technical development team for the Biodiversity Heritage Library since 2007.'
},{
image: 'team/bhl.jpg'
name: 'Biodiversity Heritage Library'
description: 'The Biodiversity Heritage Library (BHL) is a consortium of natural history and botanical libraries that cooperate to digitize the legacy literature of biodiversity held in their collections and to make that literature available for open access and responsible use as a part of a global “biodiversity commons.”'
url: ['http://biodiversitylibrary.org', 'https://twitter.com/biodivlibrary']
},{
image: 'team/conscicom.jpg'
name: 'Constructing Scientific Communities'
description: 'This <abbr title="Arts & Humanities Research Council">AHRC</abbr> Science in Culture project brings together historical and literary research in the nineteenth century with contemporary scientific practice, looking at the ways in which patterns of popular communication and engagement in nineteenth-century science can offer models for current practice.'
url: ['http://conscicom.org/', 'https://twitter.com/conscicom']
},{
image: 'team/zooniverse.jpg'
name: 'Zooniverse'
description: 'The Zooniverse is home to the internet’s largest, most popular and most successful citizen science projects. The Zooniverse and the suite of projects it contains is produced, maintained and developed by the Citizen Science Alliance (CSA). The member institutions of the CSA work with many academic and other partners around the world to produce projects that use the efforts and ability of volunteers to help scientists and researchers.'
url: ['https://www.zooniverse.org/', 'https://twitter.com/the_zooniverse', 'https://github.com/zooniverse']
}]
missouri:
title: "Missouri Botanical Garden"
members: [{
image: 'team/trish.jpg'
name: 'PI:NAME:<NAME>END_PI'
location: 'St Louis, MO, USA'
description: '''
Though a humanities scholar and librarian by training, was hired by the Biodiversity Heritage Library over 5 years ago to serve as their metadata guru. Now manages several BHL-related projects including Art of Life and Purposeful Gaming and is based in the Center for Biodiversity Informatics at Missouri Botanical Garden.
'''
},{
image: 'team/william.jpg'
name: 'PI:NAME:<NAME>END_PI'
location: 'St Louis, MO, USA'
description: '''
A kind (of) Computer Scientist, father of one, who got into Biodiversity Informatics 15 years ago and then flew from Costa Rica to work for global Biodiversity Heritage Library based in the Center for Biodiversity Informatics at Missouri Botanical Garden.
'''
},{
image: 'team/mike.jpg'
name: 'PI:NAME:<NAME>END_PI'
location: 'St Louis, MO, USA'
description: '''
Software developer with more than 20 years of experience who has been involved with the Biodiversity Heritage Library since 2007.
'''
}]
conscicom:
title: "Constructing Scientific Communities"
members: [{
image: 'team/sally.jpg'
name: 'PI:NAME:<NAME>END_PI'
location: 'Oxford, UK'
description: 'Principal Investigator'
},{
image: 'team/chris.jpg'
name: 'PI:NAME:<NAME>END_PI'
location: 'Oxford, UK'
description: 'Co-investigator'
url: 'http://twitter.com/chrislintott'
},{
image: 'team/geoff.jpg'
name: 'PI:NAME:<NAME>END_PI'
location: 'Leicester, UK'
description: 'Postdoctoral researcher, Constructing Scientific Communities'
url: 'http://twitter.com/geoffreybelknap'
}]
developers:
title: "Zooniverse"
members: [{
image: 'team/jim.jpg'
name: 'PI:NAME:<NAME>END_PI'
location: 'Oxford, UK'
description: 'Web developer'
url: 'http://twitter.com/pekingspring'
},{
image: 'team/victoria.jpg'
name: 'PI:NAME:<NAME>END_PI'
location: 'Oxford, UK'
description: 'Humanities project lead'
url: 'http://twitter.com/VanHyningV'
},{
image: 'team/adam.jpg'
name: 'PI:NAME:<NAME>END_PI'
location: 'Oxford, UK'
description: 'Web infrastructure'
url: 'http://twitter.com/astopy'
}]
|
[
{
"context": "sOfQuantumNeutrinoFields\n professor: \"Professor Hubert Farnsworth\"\n books: [\":shrug:\"]\n\n drop: ->\n con",
"end": 87,
"score": 0.9998666644096375,
"start": 70,
"tag": "NAME",
"value": "Hubert Farnsworth"
}
] | test/resources/exports/export-equals-instance.coffee | hulu/splitshot | 13 | class TheMathematicsOfQuantumNeutrinoFields
professor: "Professor Hubert Farnsworth"
books: [":shrug:"]
drop: ->
console.log("Good riddence")
@register: ->
console.log("Good luck")
module.exports = new TheMathematicsOfQuantumNeutrinoFields()
| 95761 | class TheMathematicsOfQuantumNeutrinoFields
professor: "Professor <NAME>"
books: [":shrug:"]
drop: ->
console.log("Good riddence")
@register: ->
console.log("Good luck")
module.exports = new TheMathematicsOfQuantumNeutrinoFields()
| true | class TheMathematicsOfQuantumNeutrinoFields
professor: "Professor PI:NAME:<NAME>END_PI"
books: [":shrug:"]
drop: ->
console.log("Good riddence")
@register: ->
console.log("Good luck")
module.exports = new TheMathematicsOfQuantumNeutrinoFields()
|
[
{
"context": "# Copyright (C) 2016-present Arctic Ice Studio <development@arcticicestudio.com>\n# Copyright (C)",
"end": 46,
"score": 0.6975352168083191,
"start": 29,
"tag": "NAME",
"value": "Arctic Ice Studio"
},
{
"context": "# Copyright (C) 2016-present Arctic Ice Studio <developm... | spec/darker-form-focusing-effect-spec.coffee | germanescobar/nord-atom-ui | 125 | # Copyright (C) 2016-present Arctic Ice Studio <development@arcticicestudio.com>
# Copyright (C) 2016-present Sven Greb <development@svengreb.de>
# Project: Nord Atom UI
# Repository: https://github.com/arcticicestudio/nord-atom-ui
# License: MIT
describe "Nord Atom UI theme", ->
beforeEach ->
waitsForPromise ->
atom.packages.activatePackage('nord-atom-ui')
it "allows to use darker colors for focused forms to be set via theme settings", ->
expect(document.documentElement.getAttribute('theme-nord-atom-ui-form-focus-effect')).toBe null
atom.config.set('nord-atom-ui.darkerFormFocusEffect', true)
expect(document.documentElement.getAttribute('theme-nord-atom-ui-form-focus-effect')).toBe 'nosnowlight'
| 155983 | # Copyright (C) 2016-present <NAME> <<EMAIL>>
# Copyright (C) 2016-present <NAME> <<EMAIL>>
# Project: Nord Atom UI
# Repository: https://github.com/arcticicestudio/nord-atom-ui
# License: MIT
describe "Nord Atom UI theme", ->
beforeEach ->
waitsForPromise ->
atom.packages.activatePackage('nord-atom-ui')
it "allows to use darker colors for focused forms to be set via theme settings", ->
expect(document.documentElement.getAttribute('theme-nord-atom-ui-form-focus-effect')).toBe null
atom.config.set('nord-atom-ui.darkerFormFocusEffect', true)
expect(document.documentElement.getAttribute('theme-nord-atom-ui-form-focus-effect')).toBe 'nosnowlight'
| true | # Copyright (C) 2016-present PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# Copyright (C) 2016-present PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# Project: Nord Atom UI
# Repository: https://github.com/arcticicestudio/nord-atom-ui
# License: MIT
describe "Nord Atom UI theme", ->
beforeEach ->
waitsForPromise ->
atom.packages.activatePackage('nord-atom-ui')
it "allows to use darker colors for focused forms to be set via theme settings", ->
expect(document.documentElement.getAttribute('theme-nord-atom-ui-form-focus-effect')).toBe null
atom.config.set('nord-atom-ui.darkerFormFocusEffect', true)
expect(document.documentElement.getAttribute('theme-nord-atom-ui-form-focus-effect')).toBe 'nosnowlight'
|
[
{
"context": "ialApiId\":\"14\",\n \"profile\":{\n \"nickname\":\"umut\",\n \"hash\":\"6096f133628c477db64002beaf0ceb72\"",
"end": 610,
"score": 0.9994233250617981,
"start": 606,
"tag": "USERNAME",
"value": "umut"
},
{
"context": "f133628c477db64002beaf0ceb72\",\n \... | client/mocks/mock.teamMembersWithPendings.coffee | ezgikaysi/koding | 1 | module.exports = {
"5720e8792dd5bdeff16f503c":{
"globalFlags":["super-admin"],
"counts":{
"followers":0,
"following":0,
"lastLoginDate":"2016-04-27T20:49:32.999Z",
"likes":0,
"referredUsers":0,
"topics":0
},
"onlineStatus":"online",
"meta":{
"data":{
"createdAt":"2016-04-27T16:27:37.805Z",
"modifiedAt":"2016-04-27T16:27:37.805Z",
"likes":0
},
"createdAt":"2016-04-27T16:27:37.805Z",
"modifiedAt":"2016-04-27T16:27:37.805Z","likes":0
},
"socialApiId":"14",
"profile":{
"nickname":"umut",
"hash":"6096f133628c477db64002beaf0ceb72",
"firstName":"Umut",
"lastName":"Sirin",
"email":"umut@koding.com"
},
"isExempt":false,
"timestamp_":"2016-04-27T16:35:15.342Z",
"role":"owner",
"bongo_":{
"constructorName":"JAccount",
"instanceId":"eea4918ac79d05c33553a8fdd5c0cb7c"
},
"watchers":{},
"_id":"5720e8792dd5bdeff16f503c",
"type":"registered",
"systemInfo":{
"defaultToLastUsedEnvironment":true
}
},
"57214ffd47d188b6e4e667e1":{
"lastName":"LASTNAME",
"groupName":"kiskis",
"code":"VyRzyrcg-",
"hash":"768e10d385fae5070e39ebe94bb4aaef",
"status":"pending",
"role":"member",
"bongo_":{
"constructorName":"JInvitation",
"instanceId":"96d24106fd31d186444466076f28b659"
},
"watchers":{},
"_id":"57214ffd47d188b6e4e667e1",
"createdAt":"2016-04-27T23:49:17.876Z",
"firstName":"FIRSTNAME",
"modifiedAt":"2016-04-27T23:49:17.876Z",
"email":"fullname@k.com"
},
"57214d75091313c27b4a4aa6":{
"groupName":"kiskis",
"code":"NyU53EqgZ",
"hash":"1d4ef2842438182c8966e6ee1f03b0ac",
"status":"pending",
"role":"member",
"bongo_":{
"constructorName":"JInvitation",
"instanceId":"33786aa20ef034e488e2b20d22d66a47"
},
"watchers":{},
"_id":"57214d75091313c27b4a4aa6",
"createdAt":"2016-04-27T23:38:29.827Z",
"modifiedAt":"2016-04-28T05:28:36.805Z",
"email":"noname@k.io"
},
"5721406bc4d422f252a643aa":{
"lastName":"LASTNAME",
"groupName":"kiskis",
"code":"NynYyEqe-",
"hash":"63565debae150796918aad60928b91de",
"status":"pending",
"role":"member",
"bongo_":{
"constructorName":"JInvitation",
"instanceId":"797dd5c0a63c7f6f5b2483ebe6bcc1dd"
},
"watchers":{},
"_id":"5721406bc4d422f252a643aa",
"createdAt":"2016-04-27T22:42:51.279Z",
"modifiedAt":"2016-04-28T00:41:17.903Z",
"email":"lastname@kd.io"
},
"5196fcb0bc9bdb0000000011":{
"globalFlags":["super-admin"],
"counts":{
"lastLoginDate":"2016-04-27T21:08:39.064Z",
"topics":0,
"following":0,
"comments":0,
"followers":0,
"referredUsers":0,
"statusUpdates":0,
"invitations":0,
"staffLikes":0,
"likes":0
},
"onlineStatus":"online",
"meta":{
"data":{
"modifiedAt":"2014-06-11T00:01:48.675Z",
"createdAt":"2013-05-18T03:59:44.831Z",
"likes":0
},
"createdAt":"2013-05-18T03:59:44.831Z",
"modifiedAt":"2014-06-11T00:01:48.675Z",
"likes":0
},
"socialApiId":"1",
"profile":{
"nickname":"devrim",
"firstName":"Devrim",
"lastName":"Yasar",
"hash":"02e68fe6ba0d08c7ea5b63320beedc46",
"email":"devrim@koding.com"
},
"timestamp_":"2016-04-27T21:08:39.009Z",
"role":"admin",
"bongo_":{
"constructorName":"JAccount",
"instanceId":"5b418b7be07085e915411dd8d2d8a16f"
},
"watchers":{},
"_id":"5196fcb0bc9bdb0000000011",
"type":"registered",
"systemInfo":{
"defaultToLastUsedEnvironment":true
}
}
}
| 81304 | module.exports = {
"5720e8792dd5bdeff16f503c":{
"globalFlags":["super-admin"],
"counts":{
"followers":0,
"following":0,
"lastLoginDate":"2016-04-27T20:49:32.999Z",
"likes":0,
"referredUsers":0,
"topics":0
},
"onlineStatus":"online",
"meta":{
"data":{
"createdAt":"2016-04-27T16:27:37.805Z",
"modifiedAt":"2016-04-27T16:27:37.805Z",
"likes":0
},
"createdAt":"2016-04-27T16:27:37.805Z",
"modifiedAt":"2016-04-27T16:27:37.805Z","likes":0
},
"socialApiId":"14",
"profile":{
"nickname":"umut",
"hash":"6096f133628c477db64002beaf0ceb72",
"firstName":"<NAME>",
"lastName":"<NAME>",
"email":"<EMAIL>"
},
"isExempt":false,
"timestamp_":"2016-04-27T16:35:15.342Z",
"role":"owner",
"bongo_":{
"constructorName":"JAccount",
"instanceId":"eea4918ac79d05c33553a8fdd5c0cb7c"
},
"watchers":{},
"_id":"5720e8792dd5bdeff16f503c",
"type":"registered",
"systemInfo":{
"defaultToLastUsedEnvironment":true
}
},
"57214ffd47d188b6e4e667e1":{
"lastName":"<NAME>",
"groupName":"kiskis",
"code":"VyRzyrcg-",
"hash":"768e10d385fae5070e39ebe94bb4aaef",
"status":"pending",
"role":"member",
"bongo_":{
"constructorName":"JInvitation",
"instanceId":"96d24106fd31d186444466076f28b659"
},
"watchers":{},
"_id":"57214ffd47d188b6e4e667e1",
"createdAt":"2016-04-27T23:49:17.876Z",
"firstName":"<NAME>",
"modifiedAt":"2016-04-27T23:49:17.876Z",
"email":"<EMAIL>"
},
"57214d75091313c27b4a4aa6":{
"groupName":"kiskis",
"code":"NyU53EqgZ",
"hash":"1d4ef2842438182c8966e6ee1f03b0ac",
"status":"pending",
"role":"member",
"bongo_":{
"constructorName":"JInvitation",
"instanceId":"33786aa20ef034e488e2b20d22d66a47"
},
"watchers":{},
"_id":"57214d75091313c27b4a4aa6",
"createdAt":"2016-04-27T23:38:29.827Z",
"modifiedAt":"2016-04-28T05:28:36.805Z",
"email":"<EMAIL>"
},
"5721406bc4d422f252a643aa":{
"lastName":"<NAME>",
"groupName":"kiskis",
"code":"NynYyEqe-",
"hash":"63565debae150796918aad60928b91de",
"status":"pending",
"role":"member",
"bongo_":{
"constructorName":"JInvitation",
"instanceId":"797dd5c0a63c7f6f5b2483ebe6bcc1dd"
},
"watchers":{},
"_id":"5721406bc4d422f252a643aa",
"createdAt":"2016-04-27T22:42:51.279Z",
"modifiedAt":"2016-04-28T00:41:17.903Z",
"email":"<EMAIL>"
},
"5196fcb0bc9bdb0000000011":{
"globalFlags":["super-admin"],
"counts":{
"lastLoginDate":"2016-04-27T21:08:39.064Z",
"topics":0,
"following":0,
"comments":0,
"followers":0,
"referredUsers":0,
"statusUpdates":0,
"invitations":0,
"staffLikes":0,
"likes":0
},
"onlineStatus":"online",
"meta":{
"data":{
"modifiedAt":"2014-06-11T00:01:48.675Z",
"createdAt":"2013-05-18T03:59:44.831Z",
"likes":0
},
"createdAt":"2013-05-18T03:59:44.831Z",
"modifiedAt":"2014-06-11T00:01:48.675Z",
"likes":0
},
"socialApiId":"1",
"profile":{
"nickname":"devrim",
"firstName":"<NAME>",
"lastName":"<NAME>",
"hash":"02e68fe6ba0d08c7ea5b63320beedc46",
"email":"<EMAIL>"
},
"timestamp_":"2016-04-27T21:08:39.009Z",
"role":"admin",
"bongo_":{
"constructorName":"JAccount",
"instanceId":"5b418b7be07085e915411dd8d2d8a16f"
},
"watchers":{},
"_id":"5196fcb0bc9bdb0000000011",
"type":"registered",
"systemInfo":{
"defaultToLastUsedEnvironment":true
}
}
}
| true | module.exports = {
"5720e8792dd5bdeff16f503c":{
"globalFlags":["super-admin"],
"counts":{
"followers":0,
"following":0,
"lastLoginDate":"2016-04-27T20:49:32.999Z",
"likes":0,
"referredUsers":0,
"topics":0
},
"onlineStatus":"online",
"meta":{
"data":{
"createdAt":"2016-04-27T16:27:37.805Z",
"modifiedAt":"2016-04-27T16:27:37.805Z",
"likes":0
},
"createdAt":"2016-04-27T16:27:37.805Z",
"modifiedAt":"2016-04-27T16:27:37.805Z","likes":0
},
"socialApiId":"14",
"profile":{
"nickname":"umut",
"hash":"6096f133628c477db64002beaf0ceb72",
"firstName":"PI:NAME:<NAME>END_PI",
"lastName":"PI:NAME:<NAME>END_PI",
"email":"PI:EMAIL:<EMAIL>END_PI"
},
"isExempt":false,
"timestamp_":"2016-04-27T16:35:15.342Z",
"role":"owner",
"bongo_":{
"constructorName":"JAccount",
"instanceId":"eea4918ac79d05c33553a8fdd5c0cb7c"
},
"watchers":{},
"_id":"5720e8792dd5bdeff16f503c",
"type":"registered",
"systemInfo":{
"defaultToLastUsedEnvironment":true
}
},
"57214ffd47d188b6e4e667e1":{
"lastName":"PI:NAME:<NAME>END_PI",
"groupName":"kiskis",
"code":"VyRzyrcg-",
"hash":"768e10d385fae5070e39ebe94bb4aaef",
"status":"pending",
"role":"member",
"bongo_":{
"constructorName":"JInvitation",
"instanceId":"96d24106fd31d186444466076f28b659"
},
"watchers":{},
"_id":"57214ffd47d188b6e4e667e1",
"createdAt":"2016-04-27T23:49:17.876Z",
"firstName":"PI:NAME:<NAME>END_PI",
"modifiedAt":"2016-04-27T23:49:17.876Z",
"email":"PI:EMAIL:<EMAIL>END_PI"
},
"57214d75091313c27b4a4aa6":{
"groupName":"kiskis",
"code":"NyU53EqgZ",
"hash":"1d4ef2842438182c8966e6ee1f03b0ac",
"status":"pending",
"role":"member",
"bongo_":{
"constructorName":"JInvitation",
"instanceId":"33786aa20ef034e488e2b20d22d66a47"
},
"watchers":{},
"_id":"57214d75091313c27b4a4aa6",
"createdAt":"2016-04-27T23:38:29.827Z",
"modifiedAt":"2016-04-28T05:28:36.805Z",
"email":"PI:EMAIL:<EMAIL>END_PI"
},
"5721406bc4d422f252a643aa":{
"lastName":"PI:NAME:<NAME>END_PI",
"groupName":"kiskis",
"code":"NynYyEqe-",
"hash":"63565debae150796918aad60928b91de",
"status":"pending",
"role":"member",
"bongo_":{
"constructorName":"JInvitation",
"instanceId":"797dd5c0a63c7f6f5b2483ebe6bcc1dd"
},
"watchers":{},
"_id":"5721406bc4d422f252a643aa",
"createdAt":"2016-04-27T22:42:51.279Z",
"modifiedAt":"2016-04-28T00:41:17.903Z",
"email":"PI:EMAIL:<EMAIL>END_PI"
},
"5196fcb0bc9bdb0000000011":{
"globalFlags":["super-admin"],
"counts":{
"lastLoginDate":"2016-04-27T21:08:39.064Z",
"topics":0,
"following":0,
"comments":0,
"followers":0,
"referredUsers":0,
"statusUpdates":0,
"invitations":0,
"staffLikes":0,
"likes":0
},
"onlineStatus":"online",
"meta":{
"data":{
"modifiedAt":"2014-06-11T00:01:48.675Z",
"createdAt":"2013-05-18T03:59:44.831Z",
"likes":0
},
"createdAt":"2013-05-18T03:59:44.831Z",
"modifiedAt":"2014-06-11T00:01:48.675Z",
"likes":0
},
"socialApiId":"1",
"profile":{
"nickname":"devrim",
"firstName":"PI:NAME:<NAME>END_PI",
"lastName":"PI:NAME:<NAME>END_PI",
"hash":"02e68fe6ba0d08c7ea5b63320beedc46",
"email":"PI:EMAIL:<EMAIL>END_PI"
},
"timestamp_":"2016-04-27T21:08:39.009Z",
"role":"admin",
"bongo_":{
"constructorName":"JAccount",
"instanceId":"5b418b7be07085e915411dd8d2d8a16f"
},
"watchers":{},
"_id":"5196fcb0bc9bdb0000000011",
"type":"registered",
"systemInfo":{
"defaultToLastUsedEnvironment":true
}
}
}
|
[
{
"context": "equire './src/buffer-api.coffee'\n\naccess_token = 'YOUR_ACCES_TOKEN'\napi = new Buffer access_token\n\napi.ge",
"end": 65,
"score": 0.5426775217056274,
"start": 60,
"tag": "PASSWORD",
"value": "YOUR_"
},
{
"context": "e './src/buffer-api.coffee'\n\naccess_token = 'YOUR... | modules/buffer-api/sample.coffee | weld-io/social-scheduler | 0 | Buffer = require './src/buffer-api.coffee'
access_token = 'YOUR_ACCES_TOKEN'
api = new Buffer access_token
api.getUserInfo (err, user) ->
if err? then return console.log "Error: #{err}"
console.log "Name: #{user.name}"
console.log "Created: #{new Date user.created_at}"
console.log "Activity: #{new Date user.activity_at}"
api.getProfileInfo (err, profiles) ->
if err? then return console.log "Error: #{err}"
profile_id = profiles[0].id
update = {
text: 'test api',
profile_ids: [
profile_id
]
}
api.getSentUpdates(profile_id, (err, data) ->
if err? then return console.log "Error #{err}"
if data.total > 0 then console.log "Sent updates are being retrieved"
)
api.createUpdate(update, (err, data) ->
if err? then return console.log "Error #{err}"
if data.success
console.log "Update creation: successful"
id = data.updates[0].id
api.deleteUpdate(id, (err, data) ->
if err? then return console.log "Error #{err}"
if data.success then return console.log "Update removal: successful"
)
)
for profile in profiles
console.log "#{profile.service_username} @ #{profile.service}"
link = "http://bufferapp.com"
api.getLinks link, (err, info) =>
if err? then return console.log "Error: #{err}"
console.log "Links to #{link} : #{info.shares}"
api.getConfiguration (err, config) ->
if err? then return console.log "Error: #{err}"
console.log "Supported services:"
console.log service for service,info of config.services
| 183391 | Buffer = require './src/buffer-api.coffee'
access_token = '<PASSWORD> <KEY> <PASSWORD>'
api = new Buffer access_token
api.getUserInfo (err, user) ->
if err? then return console.log "Error: #{err}"
console.log "Name: #{user.name}"
console.log "Created: #{new Date user.created_at}"
console.log "Activity: #{new Date user.activity_at}"
api.getProfileInfo (err, profiles) ->
if err? then return console.log "Error: #{err}"
profile_id = profiles[0].id
update = {
text: 'test api',
profile_ids: [
profile_id
]
}
api.getSentUpdates(profile_id, (err, data) ->
if err? then return console.log "Error #{err}"
if data.total > 0 then console.log "Sent updates are being retrieved"
)
api.createUpdate(update, (err, data) ->
if err? then return console.log "Error #{err}"
if data.success
console.log "Update creation: successful"
id = data.updates[0].id
api.deleteUpdate(id, (err, data) ->
if err? then return console.log "Error #{err}"
if data.success then return console.log "Update removal: successful"
)
)
for profile in profiles
console.log "#{profile.service_username} @ #{profile.service}"
link = "http://bufferapp.com"
api.getLinks link, (err, info) =>
if err? then return console.log "Error: #{err}"
console.log "Links to #{link} : #{info.shares}"
api.getConfiguration (err, config) ->
if err? then return console.log "Error: #{err}"
console.log "Supported services:"
console.log service for service,info of config.services
| true | Buffer = require './src/buffer-api.coffee'
access_token = 'PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI'
api = new Buffer access_token
api.getUserInfo (err, user) ->
if err? then return console.log "Error: #{err}"
console.log "Name: #{user.name}"
console.log "Created: #{new Date user.created_at}"
console.log "Activity: #{new Date user.activity_at}"
api.getProfileInfo (err, profiles) ->
if err? then return console.log "Error: #{err}"
profile_id = profiles[0].id
update = {
text: 'test api',
profile_ids: [
profile_id
]
}
api.getSentUpdates(profile_id, (err, data) ->
if err? then return console.log "Error #{err}"
if data.total > 0 then console.log "Sent updates are being retrieved"
)
api.createUpdate(update, (err, data) ->
if err? then return console.log "Error #{err}"
if data.success
console.log "Update creation: successful"
id = data.updates[0].id
api.deleteUpdate(id, (err, data) ->
if err? then return console.log "Error #{err}"
if data.success then return console.log "Update removal: successful"
)
)
for profile in profiles
console.log "#{profile.service_username} @ #{profile.service}"
link = "http://bufferapp.com"
api.getLinks link, (err, info) =>
if err? then return console.log "Error: #{err}"
console.log "Links to #{link} : #{info.shares}"
api.getConfiguration (err, config) ->
if err? then return console.log "Error: #{err}"
console.log "Supported services:"
console.log service for service,info of config.services
|
[
{
"context": "============\n # Core System by Hyakka Studio\n # By Geoffrey Chueng <kahogeoff@gmail.com> [Hyakka Studio]\n # HRM_Core",
"end": 138,
"score": 0.9998857378959656,
"start": 123,
"tag": "NAME",
"value": "Geoffrey Chueng"
},
{
"context": "re System by Hyakka Studio\n # By ... | src/HRM_Core.coffee | HyakkaStudio/RPG-Maker-MV-Plugins | 2 | ###
# =============================================================================
# Core System by Hyakka Studio
# By Geoffrey Chueng <kahogeoff@gmail.com> [Hyakka Studio]
# HRM_Core.js
# Version: 0.1
# Released under MIT
# Keep this section when you are using this plugin without any editing
# =============================================================================
###
###:
# @plugindesc The core system for any script the created by Hyakka Studio.
# @author Geoffrey Chueng [Hyakka Studio]
#
# @help
# ----- Core System by Hyakka Studio -----
#
# REMINDER: This plugin must be loaded after any other HRM Script.
###
Imported = Imported or {}
Imported['HRM_Core'] = true
HRM = HRM or {}
HRM.Core = HRM.Core or {}
(($) ->
_Note = HRM.NoteSystem
_Battery = HRM.BatterySystem
###
# Create the plugin command
###
_Game_Interpreter_pluginCommand = Game_Interpreter::pluginCommand
Game_Interpreter::pluginCommand = (command, args) ->
_Game_Interpreter_pluginCommand.call this
###
# Enable the plugin commands if "NoteSystem" has been loaded
###
if Imported['HRM_NoteSystem'] and command == "Notebook"
switch args[0]
when 'open'
_Note.EnterNoteScene()
break
when 'add'
_Note.AddNote args[1], args[2]
break
else
break
###
# Enable the plugin commands if "BatterySystem" has been loaded
###
if Imported['HRM_BatterySystem'] and command == "Battery"
switch args[0]
when 'drain'
_value = Number args[1]
_Battery.DrainBattery _value
break
when 'recharge'
_value = Number args[1]
_Battery.RechargeBattery _value
break
when 'start'
_Battery.StartDrainBattery()
break
when 'stop'
_Battery.StopDrainBattery()
break
else
break
return
'use strict'
return
) HRM.Core
| 81975 | ###
# =============================================================================
# Core System by Hyakka Studio
# By <NAME> <<EMAIL>> [Hyakka Studio]
# HRM_Core.js
# Version: 0.1
# Released under MIT
# Keep this section when you are using this plugin without any editing
# =============================================================================
###
###:
# @plugindesc The core system for any script the created by Hyakka Studio.
# @author <NAME> [Hyakka Studio]
#
# @help
# ----- Core System by Hyakka Studio -----
#
# REMINDER: This plugin must be loaded after any other HRM Script.
###
Imported = Imported or {}
Imported['HRM_Core'] = true
HRM = HRM or {}
HRM.Core = HRM.Core or {}
(($) ->
_Note = HRM.NoteSystem
_Battery = HRM.BatterySystem
###
# Create the plugin command
###
_Game_Interpreter_pluginCommand = Game_Interpreter::pluginCommand
Game_Interpreter::pluginCommand = (command, args) ->
_Game_Interpreter_pluginCommand.call this
###
# Enable the plugin commands if "NoteSystem" has been loaded
###
if Imported['HRM_NoteSystem'] and command == "Notebook"
switch args[0]
when 'open'
_Note.EnterNoteScene()
break
when 'add'
_Note.AddNote args[1], args[2]
break
else
break
###
# Enable the plugin commands if "BatterySystem" has been loaded
###
if Imported['HRM_BatterySystem'] and command == "Battery"
switch args[0]
when 'drain'
_value = Number args[1]
_Battery.DrainBattery _value
break
when 'recharge'
_value = Number args[1]
_Battery.RechargeBattery _value
break
when 'start'
_Battery.StartDrainBattery()
break
when 'stop'
_Battery.StopDrainBattery()
break
else
break
return
'use strict'
return
) HRM.Core
| true | ###
# =============================================================================
# Core System by Hyakka Studio
# By PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> [Hyakka Studio]
# HRM_Core.js
# Version: 0.1
# Released under MIT
# Keep this section when you are using this plugin without any editing
# =============================================================================
###
###:
# @plugindesc The core system for any script the created by Hyakka Studio.
# @author PI:NAME:<NAME>END_PI [Hyakka Studio]
#
# @help
# ----- Core System by Hyakka Studio -----
#
# REMINDER: This plugin must be loaded after any other HRM Script.
###
Imported = Imported or {}
Imported['HRM_Core'] = true
HRM = HRM or {}
HRM.Core = HRM.Core or {}
(($) ->
_Note = HRM.NoteSystem
_Battery = HRM.BatterySystem
###
# Create the plugin command
###
_Game_Interpreter_pluginCommand = Game_Interpreter::pluginCommand
Game_Interpreter::pluginCommand = (command, args) ->
_Game_Interpreter_pluginCommand.call this
###
# Enable the plugin commands if "NoteSystem" has been loaded
###
if Imported['HRM_NoteSystem'] and command == "Notebook"
switch args[0]
when 'open'
_Note.EnterNoteScene()
break
when 'add'
_Note.AddNote args[1], args[2]
break
else
break
###
# Enable the plugin commands if "BatterySystem" has been loaded
###
if Imported['HRM_BatterySystem'] and command == "Battery"
switch args[0]
when 'drain'
_value = Number args[1]
_Battery.DrainBattery _value
break
when 'recharge'
_value = Number args[1]
_Battery.RechargeBattery _value
break
when 'start'
_Battery.StartDrainBattery()
break
when 'stop'
_Battery.StopDrainBattery()
break
else
break
return
'use strict'
return
) HRM.Core
|
[
{
"context": " @_super()\n @elementSizeDidChange()\n # TODO(Peter): This is a hack to detect if user is using lion ",
"end": 220,
"score": 0.9943896532058716,
"start": 215,
"tag": "NAME",
"value": "Peter"
}
] | src/views.coffee | blend/ember-table | 0 | Ember.Table.TablesContainer = Ember.View.extend Ember.ResizeHandler,
templateName: 'tables-container'
classNames: 'tables-container'
didInsertElement: ->
@_super()
@elementSizeDidChange()
# TODO(Peter): This is a hack to detect if user is using lion and scroll
# bars are set to show when scrolling
scrollBarWidth = $.getScrollbarWidth()
isLion = navigator?.appVersion['10_7'] isnt -1 and scrollBarWidth is 0
scrollBarWidth = 8 if isLion
@set 'controller._scrollbarSize', scrollBarWidth
onResize: ->
@elementSizeDidChange()
elementSizeDidChange: ->
@set 'controller._width', @$().width()
@set 'controller._height', @$().height()
Ember.Table.TableContainer = Ember.View.extend Ember.StyleBindingsMixin,
classNames: ['table-container']
styleBindings: ['height', 'width']
# This should be a mixin
Ember.Table.TableBlock = Ember.CollectionView.extend Ember.StyleBindingsMixin,
classNames: ['table-block']
styleBindings: ['width', 'height']
itemViewClass: 'Ember.Table.TableRow'
columns: null
content: null
scrollLeft: null
onScrollLeftDidChange: Ember.observer ->
@$().scrollLeft @get('scrollLeft')
, 'scrollLeft'
Ember.Table.LazyTableBlock = Ember.LazyContainerView.extend
classNames: ['table-block']
rowHeightBinding: 'controller.rowHeight'
itemViewClass: 'Ember.Table.TableRow'
styleBindings: ['width']
columns: null
content: null
scrollLeft: null
scrollTop: null
onScrollLeftDidChange: Ember.observer ->
@$().scrollLeft @get('scrollLeft')
, 'scrollLeft'
Ember.Table.TableRow = Ember.LazyItemView.extend
templateName: 'table-row'
classNames: 'table-row'
classNameBindings: ['row.active:active', 'row.selected:selected']
styleBindings: ['width', 'height']
rowBinding: 'content'
columnsBinding: 'parentView.columns'
widthBinding: 'controller._rowWidth'
heightBinding: 'controller.rowHeight'
mouseEnter: (event) ->
row = @get 'row'
row.set 'active', yes if row
mouseLeave: (event) ->
row = @get 'row'
row.set 'active', no if row
teardownContent: ->
row = @get 'row'
row.set 'active', no if row
Ember.Table.TableCell = Ember.View.extend Ember.StyleBindingsMixin,
templateName: 'table-cell'
classNames: ['table-cell']
styleBindings: ['width']
rowBinding: 'parentView.row'
columnBinding: 'content'
rowContentBinding:'row.content'
widthBinding: 'column.columnWidth'
cellContent: Ember.computed (key, value) ->
row = @get 'rowContent'
column = @get 'column'
return unless row and column
if arguments.length is 1
value = column.getCellContent row
else
column.setCellContent row, value
value
.property 'rowContent.isLoaded', 'column'
################################################################################
Ember.Table.HeaderBlock = Ember.Table.TableBlock.extend
classNames: ['header-block']
itemViewClass: 'Ember.Table.HeaderRow'
content: Ember.computed ->
[@get('columns')]
.property 'columns'
Ember.Table.HeaderRow = Ember.View.extend Ember.StyleBindingsMixin,
templateName: 'header-row'
classNames: ['table-row', 'header-row']
styleBindings: ['height']
columnsBinding: 'content'
heightBinding: 'controller.headerHeight'
# options for jQuery UI sortable
sortableOption: Ember.computed ->
axis: 'x'
cursor: 'pointer'
helper: 'clone'
containment: 'parent'
placeholder: 'ui-state-highlight'
scroll: true
tolerance: 'pointer'
update: _.bind(@onColumnSort, this)
.property()
didInsertElement: ->
@_super()
@$('> div').sortable(@get('sortableOption'))
onColumnSort: (event, ui) ->
newIndex = ui.item.index()
view = Ember.View.views[ui.item.attr('id')]
columns = @get 'columns'
column = view.get 'column'
columns.removeObject column
columns.insertAt newIndex, column
Ember.Table.HeaderCell = Ember.View.extend Ember.StyleBindingsMixin,
templateName: 'header-cell'
classNames: ['table-cell', 'header-cell']
styleBindings: ['width', 'height']
columnBinding: 'content'
widthBinding: 'column.columnWidth'
heightBinding: 'controller.headerHeight'
# jQuery UI resizable option
resizableOption: Ember.computed ->
handles: 'e'
minHeight: 40
minWidth: 100
maxWidth: 500
resize: _.bind(@onColumnResize, this)
.property()
didInsertElement: ->
@$().resizable(@get('resizableOption'))
onColumnResize: (event, ui) ->
@set 'width', ui.size.width
################################################################################
Ember.Table.HeaderTableContainer =
Ember.Table.TableContainer.extend Ember.MouseWheelHandlerMixin,
templateName: 'header-container'
classNames: ['table-container', 'fixed-table-container',
'header-container']
heightBinding: 'controller.headerHeight'
widthBinding: 'controller._tableContainerWidth'
scrollLeftBinding:'controller._tableScrollLeft'
onMouseWheel: (event, delta, deltaX, deltaY) ->
scrollLeft = @$('.right-table-block').scrollLeft() + deltaX * 50
@set 'scrollLeft', scrollLeft
event.preventDefault()
Ember.Table.BodyTableContainer =
Ember.Table.TableContainer.extend Ember.MouseWheelHandlerMixin,
Ember.ScrollHandlerMixin,
templateName: 'body-container'
classNames: ['table-container', 'body-container']
heightBinding: 'controller._bodyHeight'
widthBinding: 'controller._width'
scrollTopBinding:'controller._tableScrollTop'
scrollLeftBinding:'controller._tableScrollLeft'
onScrollTopDidChange: Ember.observer ->
@$().scrollTop @get('scrollTop')
, 'scrollTop'
onScroll: (event) ->
@set 'scrollTop', event.target.scrollTop
event.preventDefault()
onMouseWheel: (event, delta, deltaX, deltaY) ->
return unless Math.abs(deltaX) > Math.abs(deltaY)
scrollLeft = @$('.right-table-block').scrollLeft() + deltaX * 50
@set 'scrollLeft', scrollLeft
event.preventDefault()
Ember.Table.FooterTableContainer =
Ember.Table.TableContainer.extend Ember.MouseWheelHandlerMixin,
templateName: 'footer-container'
classNames: ['table-container', 'fixed-table-container',
'footer-container']
heightBinding: 'controller.footerHeight'
widthBinding: 'controller._tableContainerWidth'
scrollLeftBinding:'controller._tableScrollLeft'
onMouseWheel: (event, delta, deltaX, deltaY) ->
scrollLeft = @$('.right-table-block').scrollLeft() + deltaX * 50
@set 'scrollLeft', scrollLeft
event.preventDefault()
Ember.Table.ScrollContainer =
Ember.View.extend Ember.StyleBindingsMixin, Ember.ScrollHandlerMixin,
templateName: 'scroll-container'
classNames: ['scroll-container']
styleBindings: ['top', 'left', 'width', 'height']
widthBinding: 'controller._scrollContainerWidth'
heightBinding: 'controller._scrollContainerHeight'
topBinding: 'controller.headerHeight'
leftBinding: 'controller._fixedColumnsWidth'
scrollTopBinding: 'controller._tableScrollTop'
scrollLeftBinding:'controller._tableScrollLeft'
onScroll: (event) ->
@set 'scrollLeft', event.target.scrollLeft
event.preventDefault()
onScrollLeftDidChange: Ember.observer ->
@$().scrollLeft @get('scrollLeft')
, 'scrollLeft'
Ember.Table.ScrollPanel = Ember.View.extend Ember.StyleBindingsMixin,
classNames: ['scroll-panel']
styleBindings: ['width', 'height']
widthBinding: 'controller._tableColumnsWidth'
heightBinding: 'controller._tableContentHeight' | 32887 | Ember.Table.TablesContainer = Ember.View.extend Ember.ResizeHandler,
templateName: 'tables-container'
classNames: 'tables-container'
didInsertElement: ->
@_super()
@elementSizeDidChange()
# TODO(<NAME>): This is a hack to detect if user is using lion and scroll
# bars are set to show when scrolling
scrollBarWidth = $.getScrollbarWidth()
isLion = navigator?.appVersion['10_7'] isnt -1 and scrollBarWidth is 0
scrollBarWidth = 8 if isLion
@set 'controller._scrollbarSize', scrollBarWidth
onResize: ->
@elementSizeDidChange()
elementSizeDidChange: ->
@set 'controller._width', @$().width()
@set 'controller._height', @$().height()
Ember.Table.TableContainer = Ember.View.extend Ember.StyleBindingsMixin,
classNames: ['table-container']
styleBindings: ['height', 'width']
# This should be a mixin
Ember.Table.TableBlock = Ember.CollectionView.extend Ember.StyleBindingsMixin,
classNames: ['table-block']
styleBindings: ['width', 'height']
itemViewClass: 'Ember.Table.TableRow'
columns: null
content: null
scrollLeft: null
onScrollLeftDidChange: Ember.observer ->
@$().scrollLeft @get('scrollLeft')
, 'scrollLeft'
Ember.Table.LazyTableBlock = Ember.LazyContainerView.extend
classNames: ['table-block']
rowHeightBinding: 'controller.rowHeight'
itemViewClass: 'Ember.Table.TableRow'
styleBindings: ['width']
columns: null
content: null
scrollLeft: null
scrollTop: null
onScrollLeftDidChange: Ember.observer ->
@$().scrollLeft @get('scrollLeft')
, 'scrollLeft'
Ember.Table.TableRow = Ember.LazyItemView.extend
templateName: 'table-row'
classNames: 'table-row'
classNameBindings: ['row.active:active', 'row.selected:selected']
styleBindings: ['width', 'height']
rowBinding: 'content'
columnsBinding: 'parentView.columns'
widthBinding: 'controller._rowWidth'
heightBinding: 'controller.rowHeight'
mouseEnter: (event) ->
row = @get 'row'
row.set 'active', yes if row
mouseLeave: (event) ->
row = @get 'row'
row.set 'active', no if row
teardownContent: ->
row = @get 'row'
row.set 'active', no if row
Ember.Table.TableCell = Ember.View.extend Ember.StyleBindingsMixin,
templateName: 'table-cell'
classNames: ['table-cell']
styleBindings: ['width']
rowBinding: 'parentView.row'
columnBinding: 'content'
rowContentBinding:'row.content'
widthBinding: 'column.columnWidth'
cellContent: Ember.computed (key, value) ->
row = @get 'rowContent'
column = @get 'column'
return unless row and column
if arguments.length is 1
value = column.getCellContent row
else
column.setCellContent row, value
value
.property 'rowContent.isLoaded', 'column'
################################################################################
Ember.Table.HeaderBlock = Ember.Table.TableBlock.extend
classNames: ['header-block']
itemViewClass: 'Ember.Table.HeaderRow'
content: Ember.computed ->
[@get('columns')]
.property 'columns'
Ember.Table.HeaderRow = Ember.View.extend Ember.StyleBindingsMixin,
templateName: 'header-row'
classNames: ['table-row', 'header-row']
styleBindings: ['height']
columnsBinding: 'content'
heightBinding: 'controller.headerHeight'
# options for jQuery UI sortable
sortableOption: Ember.computed ->
axis: 'x'
cursor: 'pointer'
helper: 'clone'
containment: 'parent'
placeholder: 'ui-state-highlight'
scroll: true
tolerance: 'pointer'
update: _.bind(@onColumnSort, this)
.property()
didInsertElement: ->
@_super()
@$('> div').sortable(@get('sortableOption'))
onColumnSort: (event, ui) ->
newIndex = ui.item.index()
view = Ember.View.views[ui.item.attr('id')]
columns = @get 'columns'
column = view.get 'column'
columns.removeObject column
columns.insertAt newIndex, column
Ember.Table.HeaderCell = Ember.View.extend Ember.StyleBindingsMixin,
templateName: 'header-cell'
classNames: ['table-cell', 'header-cell']
styleBindings: ['width', 'height']
columnBinding: 'content'
widthBinding: 'column.columnWidth'
heightBinding: 'controller.headerHeight'
# jQuery UI resizable option
resizableOption: Ember.computed ->
handles: 'e'
minHeight: 40
minWidth: 100
maxWidth: 500
resize: _.bind(@onColumnResize, this)
.property()
didInsertElement: ->
@$().resizable(@get('resizableOption'))
onColumnResize: (event, ui) ->
@set 'width', ui.size.width
################################################################################
Ember.Table.HeaderTableContainer =
Ember.Table.TableContainer.extend Ember.MouseWheelHandlerMixin,
templateName: 'header-container'
classNames: ['table-container', 'fixed-table-container',
'header-container']
heightBinding: 'controller.headerHeight'
widthBinding: 'controller._tableContainerWidth'
scrollLeftBinding:'controller._tableScrollLeft'
onMouseWheel: (event, delta, deltaX, deltaY) ->
scrollLeft = @$('.right-table-block').scrollLeft() + deltaX * 50
@set 'scrollLeft', scrollLeft
event.preventDefault()
Ember.Table.BodyTableContainer =
Ember.Table.TableContainer.extend Ember.MouseWheelHandlerMixin,
Ember.ScrollHandlerMixin,
templateName: 'body-container'
classNames: ['table-container', 'body-container']
heightBinding: 'controller._bodyHeight'
widthBinding: 'controller._width'
scrollTopBinding:'controller._tableScrollTop'
scrollLeftBinding:'controller._tableScrollLeft'
onScrollTopDidChange: Ember.observer ->
@$().scrollTop @get('scrollTop')
, 'scrollTop'
onScroll: (event) ->
@set 'scrollTop', event.target.scrollTop
event.preventDefault()
onMouseWheel: (event, delta, deltaX, deltaY) ->
return unless Math.abs(deltaX) > Math.abs(deltaY)
scrollLeft = @$('.right-table-block').scrollLeft() + deltaX * 50
@set 'scrollLeft', scrollLeft
event.preventDefault()
Ember.Table.FooterTableContainer =
Ember.Table.TableContainer.extend Ember.MouseWheelHandlerMixin,
templateName: 'footer-container'
classNames: ['table-container', 'fixed-table-container',
'footer-container']
heightBinding: 'controller.footerHeight'
widthBinding: 'controller._tableContainerWidth'
scrollLeftBinding:'controller._tableScrollLeft'
onMouseWheel: (event, delta, deltaX, deltaY) ->
scrollLeft = @$('.right-table-block').scrollLeft() + deltaX * 50
@set 'scrollLeft', scrollLeft
event.preventDefault()
Ember.Table.ScrollContainer =
Ember.View.extend Ember.StyleBindingsMixin, Ember.ScrollHandlerMixin,
templateName: 'scroll-container'
classNames: ['scroll-container']
styleBindings: ['top', 'left', 'width', 'height']
widthBinding: 'controller._scrollContainerWidth'
heightBinding: 'controller._scrollContainerHeight'
topBinding: 'controller.headerHeight'
leftBinding: 'controller._fixedColumnsWidth'
scrollTopBinding: 'controller._tableScrollTop'
scrollLeftBinding:'controller._tableScrollLeft'
onScroll: (event) ->
@set 'scrollLeft', event.target.scrollLeft
event.preventDefault()
onScrollLeftDidChange: Ember.observer ->
@$().scrollLeft @get('scrollLeft')
, 'scrollLeft'
Ember.Table.ScrollPanel = Ember.View.extend Ember.StyleBindingsMixin,
classNames: ['scroll-panel']
styleBindings: ['width', 'height']
widthBinding: 'controller._tableColumnsWidth'
heightBinding: 'controller._tableContentHeight' | true | Ember.Table.TablesContainer = Ember.View.extend Ember.ResizeHandler,
templateName: 'tables-container'
classNames: 'tables-container'
didInsertElement: ->
@_super()
@elementSizeDidChange()
# TODO(PI:NAME:<NAME>END_PI): This is a hack to detect if user is using lion and scroll
# bars are set to show when scrolling
scrollBarWidth = $.getScrollbarWidth()
isLion = navigator?.appVersion['10_7'] isnt -1 and scrollBarWidth is 0
scrollBarWidth = 8 if isLion
@set 'controller._scrollbarSize', scrollBarWidth
onResize: ->
@elementSizeDidChange()
elementSizeDidChange: ->
@set 'controller._width', @$().width()
@set 'controller._height', @$().height()
Ember.Table.TableContainer = Ember.View.extend Ember.StyleBindingsMixin,
classNames: ['table-container']
styleBindings: ['height', 'width']
# This should be a mixin
Ember.Table.TableBlock = Ember.CollectionView.extend Ember.StyleBindingsMixin,
classNames: ['table-block']
styleBindings: ['width', 'height']
itemViewClass: 'Ember.Table.TableRow'
columns: null
content: null
scrollLeft: null
onScrollLeftDidChange: Ember.observer ->
@$().scrollLeft @get('scrollLeft')
, 'scrollLeft'
Ember.Table.LazyTableBlock = Ember.LazyContainerView.extend
classNames: ['table-block']
rowHeightBinding: 'controller.rowHeight'
itemViewClass: 'Ember.Table.TableRow'
styleBindings: ['width']
columns: null
content: null
scrollLeft: null
scrollTop: null
onScrollLeftDidChange: Ember.observer ->
@$().scrollLeft @get('scrollLeft')
, 'scrollLeft'
Ember.Table.TableRow = Ember.LazyItemView.extend
templateName: 'table-row'
classNames: 'table-row'
classNameBindings: ['row.active:active', 'row.selected:selected']
styleBindings: ['width', 'height']
rowBinding: 'content'
columnsBinding: 'parentView.columns'
widthBinding: 'controller._rowWidth'
heightBinding: 'controller.rowHeight'
mouseEnter: (event) ->
row = @get 'row'
row.set 'active', yes if row
mouseLeave: (event) ->
row = @get 'row'
row.set 'active', no if row
teardownContent: ->
row = @get 'row'
row.set 'active', no if row
Ember.Table.TableCell = Ember.View.extend Ember.StyleBindingsMixin,
templateName: 'table-cell'
classNames: ['table-cell']
styleBindings: ['width']
rowBinding: 'parentView.row'
columnBinding: 'content'
rowContentBinding:'row.content'
widthBinding: 'column.columnWidth'
cellContent: Ember.computed (key, value) ->
row = @get 'rowContent'
column = @get 'column'
return unless row and column
if arguments.length is 1
value = column.getCellContent row
else
column.setCellContent row, value
value
.property 'rowContent.isLoaded', 'column'
################################################################################
Ember.Table.HeaderBlock = Ember.Table.TableBlock.extend
classNames: ['header-block']
itemViewClass: 'Ember.Table.HeaderRow'
content: Ember.computed ->
[@get('columns')]
.property 'columns'
Ember.Table.HeaderRow = Ember.View.extend Ember.StyleBindingsMixin,
templateName: 'header-row'
classNames: ['table-row', 'header-row']
styleBindings: ['height']
columnsBinding: 'content'
heightBinding: 'controller.headerHeight'
# options for jQuery UI sortable
sortableOption: Ember.computed ->
axis: 'x'
cursor: 'pointer'
helper: 'clone'
containment: 'parent'
placeholder: 'ui-state-highlight'
scroll: true
tolerance: 'pointer'
update: _.bind(@onColumnSort, this)
.property()
didInsertElement: ->
@_super()
@$('> div').sortable(@get('sortableOption'))
onColumnSort: (event, ui) ->
newIndex = ui.item.index()
view = Ember.View.views[ui.item.attr('id')]
columns = @get 'columns'
column = view.get 'column'
columns.removeObject column
columns.insertAt newIndex, column
Ember.Table.HeaderCell = Ember.View.extend Ember.StyleBindingsMixin,
templateName: 'header-cell'
classNames: ['table-cell', 'header-cell']
styleBindings: ['width', 'height']
columnBinding: 'content'
widthBinding: 'column.columnWidth'
heightBinding: 'controller.headerHeight'
# jQuery UI resizable option
resizableOption: Ember.computed ->
handles: 'e'
minHeight: 40
minWidth: 100
maxWidth: 500
resize: _.bind(@onColumnResize, this)
.property()
didInsertElement: ->
@$().resizable(@get('resizableOption'))
onColumnResize: (event, ui) ->
@set 'width', ui.size.width
################################################################################
Ember.Table.HeaderTableContainer =
Ember.Table.TableContainer.extend Ember.MouseWheelHandlerMixin,
templateName: 'header-container'
classNames: ['table-container', 'fixed-table-container',
'header-container']
heightBinding: 'controller.headerHeight'
widthBinding: 'controller._tableContainerWidth'
scrollLeftBinding:'controller._tableScrollLeft'
onMouseWheel: (event, delta, deltaX, deltaY) ->
scrollLeft = @$('.right-table-block').scrollLeft() + deltaX * 50
@set 'scrollLeft', scrollLeft
event.preventDefault()
Ember.Table.BodyTableContainer =
Ember.Table.TableContainer.extend Ember.MouseWheelHandlerMixin,
Ember.ScrollHandlerMixin,
templateName: 'body-container'
classNames: ['table-container', 'body-container']
heightBinding: 'controller._bodyHeight'
widthBinding: 'controller._width'
scrollTopBinding:'controller._tableScrollTop'
scrollLeftBinding:'controller._tableScrollLeft'
onScrollTopDidChange: Ember.observer ->
@$().scrollTop @get('scrollTop')
, 'scrollTop'
onScroll: (event) ->
@set 'scrollTop', event.target.scrollTop
event.preventDefault()
onMouseWheel: (event, delta, deltaX, deltaY) ->
return unless Math.abs(deltaX) > Math.abs(deltaY)
scrollLeft = @$('.right-table-block').scrollLeft() + deltaX * 50
@set 'scrollLeft', scrollLeft
event.preventDefault()
Ember.Table.FooterTableContainer =
Ember.Table.TableContainer.extend Ember.MouseWheelHandlerMixin,
templateName: 'footer-container'
classNames: ['table-container', 'fixed-table-container',
'footer-container']
heightBinding: 'controller.footerHeight'
widthBinding: 'controller._tableContainerWidth'
scrollLeftBinding:'controller._tableScrollLeft'
onMouseWheel: (event, delta, deltaX, deltaY) ->
scrollLeft = @$('.right-table-block').scrollLeft() + deltaX * 50
@set 'scrollLeft', scrollLeft
event.preventDefault()
Ember.Table.ScrollContainer =
Ember.View.extend Ember.StyleBindingsMixin, Ember.ScrollHandlerMixin,
templateName: 'scroll-container'
classNames: ['scroll-container']
styleBindings: ['top', 'left', 'width', 'height']
widthBinding: 'controller._scrollContainerWidth'
heightBinding: 'controller._scrollContainerHeight'
topBinding: 'controller.headerHeight'
leftBinding: 'controller._fixedColumnsWidth'
scrollTopBinding: 'controller._tableScrollTop'
scrollLeftBinding:'controller._tableScrollLeft'
onScroll: (event) ->
@set 'scrollLeft', event.target.scrollLeft
event.preventDefault()
onScrollLeftDidChange: Ember.observer ->
@$().scrollLeft @get('scrollLeft')
, 'scrollLeft'
Ember.Table.ScrollPanel = Ember.View.extend Ember.StyleBindingsMixin,
classNames: ['scroll-panel']
styleBindings: ['width', 'height']
widthBinding: 'controller._tableColumnsWidth'
heightBinding: 'controller._tableContentHeight' |
[
{
"context": "hostName: %s', hostName\n\n @socket = io \"http://115.28.1.109:8000/socketio\",\n reconnection: true\n re",
"end": 2012,
"score": 0.9997222423553467,
"start": 2000,
"tag": "IP_ADDRESS",
"value": "115.28.1.109"
},
{
"context": "ty().append(imgTag)\n\n Devic... | lib/build/build-state-view.coffee | yezhiming/atom-butterfly | 3 | #
# 显示任务状态,点击构建时弹出,作为一个tab
#
{$, View, SelectListView, $$} = require 'atom'
qrcode = require '../utils/qrcode'
request = require 'request'
io = require 'socket.io-client'
Q = require 'q'
puzzleClient = require '../utils/puzzle-client'
ConsoleView = require '../utils/console-view'
{allowUnsafeNewFunction} = require('loophole')
Download = allowUnsafeNewFunction -> require 'download'
Device = require '../../script/runDevice'
module.exports =
class BuildStatusView extends View
@content: ->
@div class: 'build-state-view butterfly overlay from-top', =>
@h1 'Build Status'
@div style: 'text-align: center', =>
@span outlet: 'loading', class: 'loading loading-spinner-large inline-block'
@div =>
@div class: "form-group", =>
@label 'ID:'
@span class: 'task-id'
@div class: "form-group", =>
@label 'UUID:'
@span class: 'task-uuid'
@div class: "form-group", =>
@label 'State:'
@span class: 'task-state'
@span class: 'glyphicon glyphicon-remove text-error hidden'
@div id: 'qrcode'
@subview 'console', new ConsoleView()
@div class: 'actions', =>
@div class: 'pull-left',outlet:"closebutton", =>
@button 'Close', click: 'destroy', class: 'inline-block-tight btn'
@div class: 'pull-right', =>
@button 'Cancel', click: 'cancel',outlet:'cancelbutton', class: 'inline-block-tight btn'
@button 'Refresh', click: 'refreshTaskState',outlet:'refreshbutton', class: 'inline-block-tight btn'
initialize: ->
@cancelbutton.disable()
@refreshbutton.disable()
attach: ->
atom.workspaceView.append(this)
@console.toggleLogger()
console.log "try to connect."
# puzzleClient.server: http://bsl.foreveross.com/puzzle/socketio 服务器默认的path为/
hostName = puzzleClient.server.substr 0, puzzleClient.server.lastIndexOf('/')
console.log 'hostName: %s', hostName
@socket = io "http://115.28.1.109:8000/socketio",
reconnection: true
reconnectionDelay: 50
reconnectionDelayMax: 12000
timeout: 3000
@socket.on 'connect', =>
console.log "socket connected. #{puzzleClient.access_token}"
@socket.emit 'bind', puzzleClient.access_token
@socket.on 'disconnect', ->
console.log "socket disconnected."
@socket.on 'reconnect', (n)->
console.log "socket reconnect. #{n} counts"
@socket.on 'error', (err) ->
console.log "socket error: #{err}"
@socket.on 'timeout', ->
console.log "socket timeout"
@socket.on 'update', (job) =>
console.log "task #{job.id} updated"
@setTask(job)
# if job.id == @task.id
# console.log "task #{job.id} updated"
# @task = job
# @find('.task-state').text job.state
# @showState(job)
@socket.on 'stdout', (out) => @console.append(out.content)
@socket.on 'stderr', (out) => @console.append(out.content, 'text-error')
destroy: ->
@remove()
setTask: (@task) ->
@find('.task-id').text @task.id
@find('.task-uuid').text @task.data.uuid
@find('.task-state').text @task.state
@showState(@task)
showState: (task) ->
@loading.show()
switch task.state
when 'complete'
@loading.hide()
@updateQRCode(task.data.platform)
@cancelbutton.disable()
@refreshbutton.disable()
when 'failed'
@loading.hide()
@find('.glyphicon-remove').removeClass('hidden')
@cancelbutton.disable()
@refreshbutton.disable()
refreshTaskState: ->
puzzleClient.getTask @task.id
.then (task) => @setTask(task)
.catch (err) -> alert "error: #{err}"
updateQRCode: (platform) ->
console.log "update qrcode for platform: #{platform}"
qr = qrcode(4, 'M')
if platform == 'ios'
# @devicebtn.show()
qr.addData("#{puzzleClient.serverSecured}/archives/#{@task.id}/install/ios")
else if platform == 'android'
qr.addData("#{puzzleClient.serverSecured}/archives/#{@task.id}.apk")
else
throw new Error('qrcode: unkown platform.')
qr.make()
imgTag = qr.createImgTag(4)
@find('#qrcode').empty().append(imgTag)
DeviceFun:->
# https://172.16.1.95:8443/archives/device/4/ios
downLoadPath = "#{puzzleClient.server}/archives/device/#{@task.id}/ios"
# downLoadPath = "http://172.16.1.95:8080/archives/device/5/ios"
destPath = "#{atom.project.path}/#{@task.id}/comeontom.app"
# destPath = "#{atom.project.path}/5/comeontom.app"
console.log "downLoadPath#{downLoadPath}"
download = new Download({ extract: true, strip: 1, mode: '777' })
.get(downLoadPath)
.dest(destPath)
download.run (err, files, stream)->
if err
throw err
Device(destPath,(status)->
console.log "status:#{status}"
)
cancel:->
selectConfirm=confirm("请确认是否中止编译?");
if selectConfirm
if @task and @task.state != 'complete'
@loading.hide()
@find('.glyphicon-remove').removeClass('hidden')
@find('.task-state').text "failed"
@cancelbutton.disable()
@refreshbutton.disable()
puzzleClient.deleteTask @task.id
.then ->
console.log "task #{@task.id} deleted."
.catch ->
console.error "failed to delete task #{@task.id}"
buttonAbled: ->
@refreshbutton.attr("disabled",false)
@cancelbutton.attr("disabled",false)
| 161423 | #
# 显示任务状态,点击构建时弹出,作为一个tab
#
{$, View, SelectListView, $$} = require 'atom'
qrcode = require '../utils/qrcode'
request = require 'request'
io = require 'socket.io-client'
Q = require 'q'
puzzleClient = require '../utils/puzzle-client'
ConsoleView = require '../utils/console-view'
{allowUnsafeNewFunction} = require('loophole')
Download = allowUnsafeNewFunction -> require 'download'
Device = require '../../script/runDevice'
module.exports =
class BuildStatusView extends View
@content: ->
@div class: 'build-state-view butterfly overlay from-top', =>
@h1 'Build Status'
@div style: 'text-align: center', =>
@span outlet: 'loading', class: 'loading loading-spinner-large inline-block'
@div =>
@div class: "form-group", =>
@label 'ID:'
@span class: 'task-id'
@div class: "form-group", =>
@label 'UUID:'
@span class: 'task-uuid'
@div class: "form-group", =>
@label 'State:'
@span class: 'task-state'
@span class: 'glyphicon glyphicon-remove text-error hidden'
@div id: 'qrcode'
@subview 'console', new ConsoleView()
@div class: 'actions', =>
@div class: 'pull-left',outlet:"closebutton", =>
@button 'Close', click: 'destroy', class: 'inline-block-tight btn'
@div class: 'pull-right', =>
@button 'Cancel', click: 'cancel',outlet:'cancelbutton', class: 'inline-block-tight btn'
@button 'Refresh', click: 'refreshTaskState',outlet:'refreshbutton', class: 'inline-block-tight btn'
initialize: ->
@cancelbutton.disable()
@refreshbutton.disable()
attach: ->
atom.workspaceView.append(this)
@console.toggleLogger()
console.log "try to connect."
# puzzleClient.server: http://bsl.foreveross.com/puzzle/socketio 服务器默认的path为/
hostName = puzzleClient.server.substr 0, puzzleClient.server.lastIndexOf('/')
console.log 'hostName: %s', hostName
@socket = io "http://172.16.31.10:8000/socketio",
reconnection: true
reconnectionDelay: 50
reconnectionDelayMax: 12000
timeout: 3000
@socket.on 'connect', =>
console.log "socket connected. #{puzzleClient.access_token}"
@socket.emit 'bind', puzzleClient.access_token
@socket.on 'disconnect', ->
console.log "socket disconnected."
@socket.on 'reconnect', (n)->
console.log "socket reconnect. #{n} counts"
@socket.on 'error', (err) ->
console.log "socket error: #{err}"
@socket.on 'timeout', ->
console.log "socket timeout"
@socket.on 'update', (job) =>
console.log "task #{job.id} updated"
@setTask(job)
# if job.id == @task.id
# console.log "task #{job.id} updated"
# @task = job
# @find('.task-state').text job.state
# @showState(job)
@socket.on 'stdout', (out) => @console.append(out.content)
@socket.on 'stderr', (out) => @console.append(out.content, 'text-error')
destroy: ->
@remove()
setTask: (@task) ->
@find('.task-id').text @task.id
@find('.task-uuid').text @task.data.uuid
@find('.task-state').text @task.state
@showState(@task)
showState: (task) ->
@loading.show()
switch task.state
when 'complete'
@loading.hide()
@updateQRCode(task.data.platform)
@cancelbutton.disable()
@refreshbutton.disable()
when 'failed'
@loading.hide()
@find('.glyphicon-remove').removeClass('hidden')
@cancelbutton.disable()
@refreshbutton.disable()
refreshTaskState: ->
puzzleClient.getTask @task.id
.then (task) => @setTask(task)
.catch (err) -> alert "error: #{err}"
updateQRCode: (platform) ->
console.log "update qrcode for platform: #{platform}"
qr = qrcode(4, 'M')
if platform == 'ios'
# @devicebtn.show()
qr.addData("#{puzzleClient.serverSecured}/archives/#{@task.id}/install/ios")
else if platform == 'android'
qr.addData("#{puzzleClient.serverSecured}/archives/#{@task.id}.apk")
else
throw new Error('qrcode: unkown platform.')
qr.make()
imgTag = qr.createImgTag(4)
@find('#qrcode').empty().append(imgTag)
DeviceFun:->
# https://172.16.1.95:8443/archives/device/4/ios
downLoadPath = "#{puzzleClient.server}/archives/device/#{@task.id}/ios"
# downLoadPath = "http://172.16.1.95:8080/archives/device/5/ios"
destPath = "#{atom.project.path}/#{@task.id}/comeontom.app"
# destPath = "#{atom.project.path}/5/comeontom.app"
console.log "downLoadPath#{downLoadPath}"
download = new Download({ extract: true, strip: 1, mode: '777' })
.get(downLoadPath)
.dest(destPath)
download.run (err, files, stream)->
if err
throw err
Device(destPath,(status)->
console.log "status:#{status}"
)
cancel:->
selectConfirm=confirm("请确认是否中止编译?");
if selectConfirm
if @task and @task.state != 'complete'
@loading.hide()
@find('.glyphicon-remove').removeClass('hidden')
@find('.task-state').text "failed"
@cancelbutton.disable()
@refreshbutton.disable()
puzzleClient.deleteTask @task.id
.then ->
console.log "task #{@task.id} deleted."
.catch ->
console.error "failed to delete task #{@task.id}"
buttonAbled: ->
@refreshbutton.attr("disabled",false)
@cancelbutton.attr("disabled",false)
| true | #
# 显示任务状态,点击构建时弹出,作为一个tab
#
{$, View, SelectListView, $$} = require 'atom'
qrcode = require '../utils/qrcode'
request = require 'request'
io = require 'socket.io-client'
Q = require 'q'
puzzleClient = require '../utils/puzzle-client'
ConsoleView = require '../utils/console-view'
{allowUnsafeNewFunction} = require('loophole')
Download = allowUnsafeNewFunction -> require 'download'
Device = require '../../script/runDevice'
module.exports =
class BuildStatusView extends View
@content: ->
@div class: 'build-state-view butterfly overlay from-top', =>
@h1 'Build Status'
@div style: 'text-align: center', =>
@span outlet: 'loading', class: 'loading loading-spinner-large inline-block'
@div =>
@div class: "form-group", =>
@label 'ID:'
@span class: 'task-id'
@div class: "form-group", =>
@label 'UUID:'
@span class: 'task-uuid'
@div class: "form-group", =>
@label 'State:'
@span class: 'task-state'
@span class: 'glyphicon glyphicon-remove text-error hidden'
@div id: 'qrcode'
@subview 'console', new ConsoleView()
@div class: 'actions', =>
@div class: 'pull-left',outlet:"closebutton", =>
@button 'Close', click: 'destroy', class: 'inline-block-tight btn'
@div class: 'pull-right', =>
@button 'Cancel', click: 'cancel',outlet:'cancelbutton', class: 'inline-block-tight btn'
@button 'Refresh', click: 'refreshTaskState',outlet:'refreshbutton', class: 'inline-block-tight btn'
initialize: ->
@cancelbutton.disable()
@refreshbutton.disable()
attach: ->
atom.workspaceView.append(this)
@console.toggleLogger()
console.log "try to connect."
# puzzleClient.server: http://bsl.foreveross.com/puzzle/socketio 服务器默认的path为/
hostName = puzzleClient.server.substr 0, puzzleClient.server.lastIndexOf('/')
console.log 'hostName: %s', hostName
@socket = io "http://PI:IP_ADDRESS:172.16.31.10END_PI:8000/socketio",
reconnection: true
reconnectionDelay: 50
reconnectionDelayMax: 12000
timeout: 3000
@socket.on 'connect', =>
console.log "socket connected. #{puzzleClient.access_token}"
@socket.emit 'bind', puzzleClient.access_token
@socket.on 'disconnect', ->
console.log "socket disconnected."
@socket.on 'reconnect', (n)->
console.log "socket reconnect. #{n} counts"
@socket.on 'error', (err) ->
console.log "socket error: #{err}"
@socket.on 'timeout', ->
console.log "socket timeout"
@socket.on 'update', (job) =>
console.log "task #{job.id} updated"
@setTask(job)
# if job.id == @task.id
# console.log "task #{job.id} updated"
# @task = job
# @find('.task-state').text job.state
# @showState(job)
@socket.on 'stdout', (out) => @console.append(out.content)
@socket.on 'stderr', (out) => @console.append(out.content, 'text-error')
destroy: ->
@remove()
setTask: (@task) ->
@find('.task-id').text @task.id
@find('.task-uuid').text @task.data.uuid
@find('.task-state').text @task.state
@showState(@task)
showState: (task) ->
@loading.show()
switch task.state
when 'complete'
@loading.hide()
@updateQRCode(task.data.platform)
@cancelbutton.disable()
@refreshbutton.disable()
when 'failed'
@loading.hide()
@find('.glyphicon-remove').removeClass('hidden')
@cancelbutton.disable()
@refreshbutton.disable()
refreshTaskState: ->
puzzleClient.getTask @task.id
.then (task) => @setTask(task)
.catch (err) -> alert "error: #{err}"
updateQRCode: (platform) ->
console.log "update qrcode for platform: #{platform}"
qr = qrcode(4, 'M')
if platform == 'ios'
# @devicebtn.show()
qr.addData("#{puzzleClient.serverSecured}/archives/#{@task.id}/install/ios")
else if platform == 'android'
qr.addData("#{puzzleClient.serverSecured}/archives/#{@task.id}.apk")
else
throw new Error('qrcode: unkown platform.')
qr.make()
imgTag = qr.createImgTag(4)
@find('#qrcode').empty().append(imgTag)
DeviceFun:->
# https://172.16.1.95:8443/archives/device/4/ios
downLoadPath = "#{puzzleClient.server}/archives/device/#{@task.id}/ios"
# downLoadPath = "http://172.16.1.95:8080/archives/device/5/ios"
destPath = "#{atom.project.path}/#{@task.id}/comeontom.app"
# destPath = "#{atom.project.path}/5/comeontom.app"
console.log "downLoadPath#{downLoadPath}"
download = new Download({ extract: true, strip: 1, mode: '777' })
.get(downLoadPath)
.dest(destPath)
download.run (err, files, stream)->
if err
throw err
Device(destPath,(status)->
console.log "status:#{status}"
)
cancel:->
selectConfirm=confirm("请确认是否中止编译?");
if selectConfirm
if @task and @task.state != 'complete'
@loading.hide()
@find('.glyphicon-remove').removeClass('hidden')
@find('.task-state').text "failed"
@cancelbutton.disable()
@refreshbutton.disable()
puzzleClient.deleteTask @task.id
.then ->
console.log "task #{@task.id} deleted."
.catch ->
console.error "failed to delete task #{@task.id}"
buttonAbled: ->
@refreshbutton.attr("disabled",false)
@cancelbutton.attr("disabled",false)
|
[
{
"context": "#################\n# Copyright (C) 2015-2016 by Vaughn Iverson\n# meteor-job-collection-playground is free so",
"end": 124,
"score": 0.9997842907905579,
"start": 110,
"tag": "NAME",
"value": "Vaughn Iverson"
},
{
"context": "around this bug:\n # https... | play.coffee | vsivsi/meteor-job-collection-playground | 23 | ############################################################################
# Copyright (C) 2015-2016 by Vaughn Iverson
# meteor-job-collection-playground is free software released under the MIT/X11 license.
# See included LICENSE file for details.
############################################################################
myJobs = new JobCollection 'queue',
idGeneration: 'MONGO'
transform: (d) ->
try
res = new Job myJobs, d
catch e
res = d
return res
later = myJobs.later
if Meteor.isClient
tick = 2500
stats = new Mongo.Collection 'jobStats'
Meteor.subscribe 'clientStats'
jobsProcessed = new ReactiveVar(0)
reactiveWindowWidth = new ReactiveVar(0)
Meteor.startup () ->
timeout = null
reactiveWindowWidth.set $(window).width()
$(window).resize () ->
Meteor.clearTimeout(timeout) if timeout
timeout = Meteor.setTimeout () ->
timeout = null
reactiveWindowWidth.set $(window).width()
, 100
parseState = new ReactiveVar ""
parseSched = new ReactiveVar []
reactiveDate = new ReactiveVar new Date()
localWorker = new ReactiveVar null
Meteor.setInterval((() -> reactiveDate.set new Date()), tick)
q = null
myType = 'testJob_null'
timeFormatter = (time) ->
now = reactiveDate.get()
if Math.abs(time - now) < tick
"Now"
else
moment(time).from(now)
# Ensure that the callback is not called multiple times
once = (func) ->
called = false
return () ->
unless called
called = true
func()
else
console.warn("Callback invoked multiple times!")
nextStep = (func) ->
Meteor.setTimeout(func, 500)
Tracker.autorun () ->
userId = Meteor.userId()
suffix = if userId then "_#{userId.substr(0,5)}" else ""
myType = "testJob#{suffix}"
Meteor.subscribe 'allJobs', userId
q?.shutdown { level: 'hard' }
q = myJobs.processJobs myType, { pollInterval: false, workTimeout: 60*1000 }, (job, cb) ->
done = 0
localWorker.set job.doc
workStep = () ->
lw = localWorker.get()
if lw
done++
if done is 20
localWorker.set null
jobsProcessed.set jobsProcessed.get() + 1
job.done(once(cb))
else
job.progress done, 20, (err, res) ->
if err or not res
localWorker.set null
job.fail('Progress update failed', once(cb))
else
localWorker.set job.doc
nextStep workStep
else if lw is null
job.fail('User aborted job', once(cb))
else
# Simulate a crash
once(cb)() # Return without .done or .fail, creating a zombie
workStep()
obs = myJobs.find({ type: myType, status: 'ready' })
.observe
added: () -> q.trigger()
Template.registerHelper "jobCollection", () -> myJobs
Template.registerHelper "localWorker", () -> localWorker.get()
Template.registerHelper "wideScreen", () -> reactiveWindowWidth.get() > 1745
Template.registerHelper "relativeTime", (time) ->
timeFormatter time
Template.registerHelper "equals", (a, b) -> a is b
truncateId = (id, length = 6) ->
if id
if typeof id is 'object'
id = "#{id.valueOf()}"
"#{id.substr(0,6)}…"
else
""
Template.registerHelper "truncateId", truncateId
Template.top.helpers
userId: () ->
Meteor.userId()
clientsConnected: () ->
return stats.findOne('stats')?.currentClients or '0'
Template.workerPanel.helpers
jobsProcessed: () ->
return jobsProcessed.get()
Template.workerPanel.events
'click .fail-job': (e, t) ->
localWorker.set null
'click .crash-job': (e, t) ->
localWorker.set false
Template.jobTable.helpers
jobEntries: () ->
# Reactively populate the table
this.find({}, { sort: { after: -1 }})
jobsProcessed: () ->
return stats.findOne('stats')?.jobsProcessed or '0'
numWorkers: () ->
return stats.findOne('stats')?.clientsSeen or '0'
handleButtonPopup = () ->
this.$('.button')
.popup
inline: true
position: 'bottom center'
delay:
show: 500
hide: 0
Template.pauseButton.onRendered handleButtonPopup
Template.removeButton.onRendered handleButtonPopup
Template.resumeButton.onRendered handleButtonPopup
Template.restartButton.onRendered handleButtonPopup
Template.rerunButton.onRendered handleButtonPopup
Template.cancelButton.onRendered handleButtonPopup
Template.readyNowButton.onRendered handleButtonPopup
Template.jobEntry.events
'click .cancel-job': (e, t) ->
job = Template.currentData()
job.cancel() if job
'click .remove-job': (e, t) ->
job = Template.currentData()
job.remove() if job
'click .restart-job': (e, t) ->
job = Template.currentData()
job.restart({ retries: if job._doc.retries then 0 else 1 }) if job
'click .rerun-job': (e, t) ->
job = Template.currentData()
job.rerun({ wait: 15000 }) if job
'click .pause-job': (e, t) ->
job = Template.currentData()
job.pause() if job
'click .resume-job': (e, t) ->
job = Template.currentData()
job.resume() if job
'click .ready-job': (e, t) ->
job = Template.currentData()
job.ready({ time: myJobs.foreverDate }) if job
# If two values sum to forever, then ∞, else the first value
isInfinity = (val1, val2) ->
if (val1 + val2) is Job.forever
"∞"
else
val1
Template.jobEntry.helpers
statusBG: () ->
{
waiting: 'grey'
ready: 'blue'
paused: 'black'
running: 'default'
cancelled: 'yellow'
failed: 'red'
completed: 'green'
}[this.status]
numRepeats: () -> isInfinity this.repeats, this.repeated
numRetries: () -> isInfinity this.retries, this.retried
futurePast: () ->
now = reactiveDate.get()
if this.after > now
"text-danger"
else
"text-success"
cancellable: () ->
this.status in Job.jobStatusCancellable
removable: () ->
this.status in Job.jobStatusRemovable
restartable: () ->
this.status in Job.jobStatusRestartable
pausable: () ->
this.status in Job.jobStatusPausable
Template.newJobInput.helpers
inputParseState: () ->
parseState.get()
inputReady: () ->
parseState.get() is "has-success"
inputError: () ->
if parseState.get() is "has-error"
"error"
else
""
nextTimes: () ->
reactiveDate.get()
for t in parseSched.get().next(3)
"#{moment(t).calendar()} (local time), #{moment(t).fromNow()}. [#{moment(t).toISOString()}]"
Template.logEntries.helpers
recentEvents: (numEvents = 5) ->
output = []
this.find({}, { fields: { log: 1, type: 1 }, transform: null, limit: numEvents, sort: { updated: -1 }})
.forEach (doc) ->
for event in doc.log
event.type = doc.type
event.jobId = truncateId doc._id
event.runId = truncateId event.runId
event.level = "error" if event.level is 'danger'
output.push event
output.sort (a, b) ->
b.time - a.time
output.slice 0, numEvents
levelIcon: () ->
switch this.level
when 'info' then 'info'
when 'success' then 'trophy'
when 'warning' then 'warning sign'
when 'error' then 'thumbs down'
else 'bug'
validateCRON = (val) ->
re = /^(?:\*|\d{1,2})(?:(?:(?:[\/-]\d{1,2})?)|(?:,\d{1,2})+)\ *(?:\ (?:\*|\d{1,2})(?:(?:(?:[\/-]\d{1,2})?)|(?:,\d{1,2})+)\ *)*$/
return null unless val.match re
sp = val.split /\ +/
if 5 <= sp.length <= 6
return sp.length is 6
else
return null
newJobSubmit = (e, t) ->
val = t.find("#inputLater").value
cronFlag = validateCRON val
if cronFlag?
s = later.parse.cron val, cronFlag
s.error = -1 if s?
else
s = later.parse.text(val)
if s.error is -1
job = new Job(myJobs, myType, { owner: Meteor.userId() })
.retry({ retries: 2, wait: 30000, backoff: 'exponential'})
.repeat({ schedule: s })
.save({cancelRepeats: true})
else
parseState.set "has-error"
Template.newJobInput.events
'click #newJob': newJobSubmit
'keyup #inputLater': (e, t) ->
if e.keyCode is 13
newJobSubmit e, t
'input #inputLater': (e, t) ->
val = e.target.value.trim()
unless val
parseState.set ""
parseSched.set []
else
s = later.parse.text val
# The following is to work around this bug:
# https://github.com/bunkat/later/issues/97
try
later.schedule(s).next()
catch
s = {}
if s.error is -1
parseState.set "has-success"
parseSched.set later.schedule(s)
else
cronFlag = validateCRON val
if cronFlag?
sCron = later.parse.cron val, cronFlag
if sCron
parseState.set "has-success"
parseSched.set later.schedule(sCron)
else
parseState.set parseState.set "has-warning"
parseSched.set []
else
parseState.set "has-warning"
parseSched.set []
Template.jobControls.events
'click .pause-queue': (e, t) ->
if $(e.target).hasClass 'active'
$(e.target).removeClass 'active'
ids = t.data.find({ status: 'paused' },{ fields: { _id: 1 }}).map (d) -> d._id
t.data.resumeJobs(ids) if ids.length > 0
else
$(e.target).addClass 'active'
ids = t.data.find({ status: { $in: Job.jobStatusPausable }}, { fields: { _id: 1 }}).map (d) -> d._id
t.data.pauseJobs(ids) if ids.length > 0
'click .cancel-queue': (e, t) ->
ids = t.data.find({ status: { $in: Job.jobStatusCancellable }}, { fields: { _id: 1 }}).map (d) -> d._id
t.data.cancelJobs(ids) if ids.length > 0
'click .restart-queue': (e, t) ->
ids = t.data.find({ status: { $in: Job.jobStatusRestartable }}, { fields: { _id: 1 }}).map (d) -> d._id
t.data.restartJobs(ids) if ids.length > 0
'click .rerun-queue': (e, t) ->
t.data.find({ status: 'completed' }).forEach (d) ->
d.rerun { wait: 15000 }
'click .remove-queue': (e, t) ->
ids = t.data.find({ status: { $in: Job.jobStatusRemovable }}, { fields: { _id: 1 }}).map (d) -> d._id
t.data.removeJobs(ids) if ids.length > 0
#######################################################
if Meteor.isServer
# myJobs.setLogStream process.stdout
myJobs.promote 5000
Meteor.startup () ->
# Don't allow users to modify the user docs
Meteor.users.deny({update: () -> true })
myJobs.startJobServer()
jobsProcessed = 0
clientsSeen = {}
currentClients = {}
publishStatsChanges = () ->
f() for c, f of currentClients
return null
Meteor.publish 'clientStats', () ->
currentClients[@connection.id] = () =>
@changed 'jobStats', 'stats',
jobsProcessed: jobsProcessed
clientsSeen: Object.keys(clientsSeen).length
currentClients: Object.keys(currentClients).length
@onStop () =>
delete currentClients[@connection.id]
publishStatsChanges()
@added 'jobStats', 'stats',
jobsProcessed: jobsProcessed
clientsSeen: Object.keys(clientsSeen).length
currentClients: Object.keys(currentClients).length
@ready()
publishStatsChanges()
myJobs.events.on 'jobDone', (msg) ->
unless msg.error or not msg.connection
jobsProcessed++
clientsSeen[msg.connection.id] ?= 0
clientsSeen[msg.connection.id]++
publishStatsChanges()
Meteor.publish 'allJobs', (clientUserId) ->
# This prevents a race condition on the client between Meteor.userId() and subscriptions to this publish
# See: https://stackoverflow.com/questions/24445404/how-to-prevent-a-client-reactive-race-between-meteor-userid-and-a-subscription/24460877#24460877
if this.userId is clientUserId
suffix = if this.userId then "_#{this.userId.substr(0,5)}" else ""
return myJobs.find({ type: "testJob#{suffix}", 'data.owner': this.userId })
else
return []
myJobs.events.on 'error', (msg) ->
console.warn "#{new Date()}, #{msg.userId}, #{msg.method}, #{msg.error}\n"
# Only allow job owners to manage or rerun jobs
myJobs.allow
manager: (userId, method, params) ->
ids = params[0]
unless typeof ids is 'object' and ids instanceof Array
ids = [ ids ]
numIds = ids.length
numMatches = myJobs.find({ _id: { $in: ids }, 'data.owner': userId }).count()
return numMatches is numIds
jobRerun: (userId, method, params) ->
id = params[0]
numMatches = myJobs.find({ _id: id, 'data.owner': userId }).count()
return numMatches is 1
jobSave: (userId, method, params) ->
doc = params[0]
return doc.data.owner is userId
getWork: (userId, method, params) ->
suffix = if userId then "_#{userId.substr(0,5)}" else ""
params[0][0] is "testJob#{suffix}" and params[0].length is 1
worker: (userId, method, params) ->
if method is 'getWork'
return false
else
id = params[0]
numMatches = myJobs.find({ _id: id, 'data.owner': userId }).count()
return numMatches is 1
new Job(myJobs, 'cleanup', {})
.repeat({ schedule: myJobs.later.parse.text("every 5 minutes") })
.save({cancelRepeats: true})
q = myJobs.processJobs 'cleanup', { pollInterval: false, workTimeout: 60*1000 }, (job, cb) ->
current = new Date()
current.setMinutes(current.getMinutes() - 5)
ids = myJobs.find({
status:
$in: Job.jobStatusRemovable
updated:
$lt: current},
{fields: { _id: 1 }}).map (d) -> d._id
myJobs.removeJobs(ids) if ids.length > 0
# console.warn "Removed #{ids.length} old jobs"
job.done("Removed #{ids.length} old jobs")
cb()
myJobs.find({ type: 'cleanup', status: 'ready' })
.observe
added: () ->
q.trigger()
| 31538 | ############################################################################
# Copyright (C) 2015-2016 by <NAME>
# meteor-job-collection-playground is free software released under the MIT/X11 license.
# See included LICENSE file for details.
############################################################################
myJobs = new JobCollection 'queue',
idGeneration: 'MONGO'
transform: (d) ->
try
res = new Job myJobs, d
catch e
res = d
return res
later = myJobs.later
if Meteor.isClient
tick = 2500
stats = new Mongo.Collection 'jobStats'
Meteor.subscribe 'clientStats'
jobsProcessed = new ReactiveVar(0)
reactiveWindowWidth = new ReactiveVar(0)
Meteor.startup () ->
timeout = null
reactiveWindowWidth.set $(window).width()
$(window).resize () ->
Meteor.clearTimeout(timeout) if timeout
timeout = Meteor.setTimeout () ->
timeout = null
reactiveWindowWidth.set $(window).width()
, 100
parseState = new ReactiveVar ""
parseSched = new ReactiveVar []
reactiveDate = new ReactiveVar new Date()
localWorker = new ReactiveVar null
Meteor.setInterval((() -> reactiveDate.set new Date()), tick)
q = null
myType = 'testJob_null'
timeFormatter = (time) ->
now = reactiveDate.get()
if Math.abs(time - now) < tick
"Now"
else
moment(time).from(now)
# Ensure that the callback is not called multiple times
once = (func) ->
called = false
return () ->
unless called
called = true
func()
else
console.warn("Callback invoked multiple times!")
nextStep = (func) ->
Meteor.setTimeout(func, 500)
Tracker.autorun () ->
userId = Meteor.userId()
suffix = if userId then "_#{userId.substr(0,5)}" else ""
myType = "testJob#{suffix}"
Meteor.subscribe 'allJobs', userId
q?.shutdown { level: 'hard' }
q = myJobs.processJobs myType, { pollInterval: false, workTimeout: 60*1000 }, (job, cb) ->
done = 0
localWorker.set job.doc
workStep = () ->
lw = localWorker.get()
if lw
done++
if done is 20
localWorker.set null
jobsProcessed.set jobsProcessed.get() + 1
job.done(once(cb))
else
job.progress done, 20, (err, res) ->
if err or not res
localWorker.set null
job.fail('Progress update failed', once(cb))
else
localWorker.set job.doc
nextStep workStep
else if lw is null
job.fail('User aborted job', once(cb))
else
# Simulate a crash
once(cb)() # Return without .done or .fail, creating a zombie
workStep()
obs = myJobs.find({ type: myType, status: 'ready' })
.observe
added: () -> q.trigger()
Template.registerHelper "jobCollection", () -> myJobs
Template.registerHelper "localWorker", () -> localWorker.get()
Template.registerHelper "wideScreen", () -> reactiveWindowWidth.get() > 1745
Template.registerHelper "relativeTime", (time) ->
timeFormatter time
Template.registerHelper "equals", (a, b) -> a is b
truncateId = (id, length = 6) ->
if id
if typeof id is 'object'
id = "#{id.valueOf()}"
"#{id.substr(0,6)}…"
else
""
Template.registerHelper "truncateId", truncateId
Template.top.helpers
userId: () ->
Meteor.userId()
clientsConnected: () ->
return stats.findOne('stats')?.currentClients or '0'
Template.workerPanel.helpers
jobsProcessed: () ->
return jobsProcessed.get()
Template.workerPanel.events
'click .fail-job': (e, t) ->
localWorker.set null
'click .crash-job': (e, t) ->
localWorker.set false
Template.jobTable.helpers
jobEntries: () ->
# Reactively populate the table
this.find({}, { sort: { after: -1 }})
jobsProcessed: () ->
return stats.findOne('stats')?.jobsProcessed or '0'
numWorkers: () ->
return stats.findOne('stats')?.clientsSeen or '0'
handleButtonPopup = () ->
this.$('.button')
.popup
inline: true
position: 'bottom center'
delay:
show: 500
hide: 0
Template.pauseButton.onRendered handleButtonPopup
Template.removeButton.onRendered handleButtonPopup
Template.resumeButton.onRendered handleButtonPopup
Template.restartButton.onRendered handleButtonPopup
Template.rerunButton.onRendered handleButtonPopup
Template.cancelButton.onRendered handleButtonPopup
Template.readyNowButton.onRendered handleButtonPopup
Template.jobEntry.events
'click .cancel-job': (e, t) ->
job = Template.currentData()
job.cancel() if job
'click .remove-job': (e, t) ->
job = Template.currentData()
job.remove() if job
'click .restart-job': (e, t) ->
job = Template.currentData()
job.restart({ retries: if job._doc.retries then 0 else 1 }) if job
'click .rerun-job': (e, t) ->
job = Template.currentData()
job.rerun({ wait: 15000 }) if job
'click .pause-job': (e, t) ->
job = Template.currentData()
job.pause() if job
'click .resume-job': (e, t) ->
job = Template.currentData()
job.resume() if job
'click .ready-job': (e, t) ->
job = Template.currentData()
job.ready({ time: myJobs.foreverDate }) if job
# If two values sum to forever, then ∞, else the first value
isInfinity = (val1, val2) ->
if (val1 + val2) is Job.forever
"∞"
else
val1
Template.jobEntry.helpers
statusBG: () ->
{
waiting: 'grey'
ready: 'blue'
paused: 'black'
running: 'default'
cancelled: 'yellow'
failed: 'red'
completed: 'green'
}[this.status]
numRepeats: () -> isInfinity this.repeats, this.repeated
numRetries: () -> isInfinity this.retries, this.retried
futurePast: () ->
now = reactiveDate.get()
if this.after > now
"text-danger"
else
"text-success"
cancellable: () ->
this.status in Job.jobStatusCancellable
removable: () ->
this.status in Job.jobStatusRemovable
restartable: () ->
this.status in Job.jobStatusRestartable
pausable: () ->
this.status in Job.jobStatusPausable
Template.newJobInput.helpers
inputParseState: () ->
parseState.get()
inputReady: () ->
parseState.get() is "has-success"
inputError: () ->
if parseState.get() is "has-error"
"error"
else
""
nextTimes: () ->
reactiveDate.get()
for t in parseSched.get().next(3)
"#{moment(t).calendar()} (local time), #{moment(t).fromNow()}. [#{moment(t).toISOString()}]"
Template.logEntries.helpers
recentEvents: (numEvents = 5) ->
output = []
this.find({}, { fields: { log: 1, type: 1 }, transform: null, limit: numEvents, sort: { updated: -1 }})
.forEach (doc) ->
for event in doc.log
event.type = doc.type
event.jobId = truncateId doc._id
event.runId = truncateId event.runId
event.level = "error" if event.level is 'danger'
output.push event
output.sort (a, b) ->
b.time - a.time
output.slice 0, numEvents
levelIcon: () ->
switch this.level
when 'info' then 'info'
when 'success' then 'trophy'
when 'warning' then 'warning sign'
when 'error' then 'thumbs down'
else 'bug'
validateCRON = (val) ->
re = /^(?:\*|\d{1,2})(?:(?:(?:[\/-]\d{1,2})?)|(?:,\d{1,2})+)\ *(?:\ (?:\*|\d{1,2})(?:(?:(?:[\/-]\d{1,2})?)|(?:,\d{1,2})+)\ *)*$/
return null unless val.match re
sp = val.split /\ +/
if 5 <= sp.length <= 6
return sp.length is 6
else
return null
newJobSubmit = (e, t) ->
val = t.find("#inputLater").value
cronFlag = validateCRON val
if cronFlag?
s = later.parse.cron val, cronFlag
s.error = -1 if s?
else
s = later.parse.text(val)
if s.error is -1
job = new Job(myJobs, myType, { owner: Meteor.userId() })
.retry({ retries: 2, wait: 30000, backoff: 'exponential'})
.repeat({ schedule: s })
.save({cancelRepeats: true})
else
parseState.set "has-error"
Template.newJobInput.events
'click #newJob': newJobSubmit
'keyup #inputLater': (e, t) ->
if e.keyCode is 13
newJobSubmit e, t
'input #inputLater': (e, t) ->
val = e.target.value.trim()
unless val
parseState.set ""
parseSched.set []
else
s = later.parse.text val
# The following is to work around this bug:
# https://github.com/bunkat/later/issues/97
try
later.schedule(s).next()
catch
s = {}
if s.error is -1
parseState.set "has-success"
parseSched.set later.schedule(s)
else
cronFlag = validateCRON val
if cronFlag?
sCron = later.parse.cron val, cronFlag
if sCron
parseState.set "has-success"
parseSched.set later.schedule(sCron)
else
parseState.set parseState.set "has-warning"
parseSched.set []
else
parseState.set "has-warning"
parseSched.set []
Template.jobControls.events
'click .pause-queue': (e, t) ->
if $(e.target).hasClass 'active'
$(e.target).removeClass 'active'
ids = t.data.find({ status: 'paused' },{ fields: { _id: 1 }}).map (d) -> d._id
t.data.resumeJobs(ids) if ids.length > 0
else
$(e.target).addClass 'active'
ids = t.data.find({ status: { $in: Job.jobStatusPausable }}, { fields: { _id: 1 }}).map (d) -> d._id
t.data.pauseJobs(ids) if ids.length > 0
'click .cancel-queue': (e, t) ->
ids = t.data.find({ status: { $in: Job.jobStatusCancellable }}, { fields: { _id: 1 }}).map (d) -> d._id
t.data.cancelJobs(ids) if ids.length > 0
'click .restart-queue': (e, t) ->
ids = t.data.find({ status: { $in: Job.jobStatusRestartable }}, { fields: { _id: 1 }}).map (d) -> d._id
t.data.restartJobs(ids) if ids.length > 0
'click .rerun-queue': (e, t) ->
t.data.find({ status: 'completed' }).forEach (d) ->
d.rerun { wait: 15000 }
'click .remove-queue': (e, t) ->
ids = t.data.find({ status: { $in: Job.jobStatusRemovable }}, { fields: { _id: 1 }}).map (d) -> d._id
t.data.removeJobs(ids) if ids.length > 0
#######################################################
if Meteor.isServer
# myJobs.setLogStream process.stdout
myJobs.promote 5000
Meteor.startup () ->
# Don't allow users to modify the user docs
Meteor.users.deny({update: () -> true })
myJobs.startJobServer()
jobsProcessed = 0
clientsSeen = {}
currentClients = {}
publishStatsChanges = () ->
f() for c, f of currentClients
return null
Meteor.publish 'clientStats', () ->
currentClients[@connection.id] = () =>
@changed 'jobStats', 'stats',
jobsProcessed: jobsProcessed
clientsSeen: Object.keys(clientsSeen).length
currentClients: Object.keys(currentClients).length
@onStop () =>
delete currentClients[@connection.id]
publishStatsChanges()
@added 'jobStats', 'stats',
jobsProcessed: jobsProcessed
clientsSeen: Object.keys(clientsSeen).length
currentClients: Object.keys(currentClients).length
@ready()
publishStatsChanges()
myJobs.events.on 'jobDone', (msg) ->
unless msg.error or not msg.connection
jobsProcessed++
clientsSeen[msg.connection.id] ?= 0
clientsSeen[msg.connection.id]++
publishStatsChanges()
Meteor.publish 'allJobs', (clientUserId) ->
# This prevents a race condition on the client between Meteor.userId() and subscriptions to this publish
# See: https://stackoverflow.com/questions/24445404/how-to-prevent-a-client-reactive-race-between-meteor-userid-and-a-subscription/24460877#24460877
if this.userId is clientUserId
suffix = if this.userId then "_#{this.userId.substr(0,5)}" else ""
return myJobs.find({ type: "testJob#{suffix}", 'data.owner': this.userId })
else
return []
myJobs.events.on 'error', (msg) ->
console.warn "#{new Date()}, #{msg.userId}, #{msg.method}, #{msg.error}\n"
# Only allow job owners to manage or rerun jobs
myJobs.allow
manager: (userId, method, params) ->
ids = params[0]
unless typeof ids is 'object' and ids instanceof Array
ids = [ ids ]
numIds = ids.length
numMatches = myJobs.find({ _id: { $in: ids }, 'data.owner': userId }).count()
return numMatches is numIds
jobRerun: (userId, method, params) ->
id = params[0]
numMatches = myJobs.find({ _id: id, 'data.owner': userId }).count()
return numMatches is 1
jobSave: (userId, method, params) ->
doc = params[0]
return doc.data.owner is userId
getWork: (userId, method, params) ->
suffix = if userId then "_#{userId.substr(0,5)}" else ""
params[0][0] is "testJob#{suffix}" and params[0].length is 1
worker: (userId, method, params) ->
if method is 'getWork'
return false
else
id = params[0]
numMatches = myJobs.find({ _id: id, 'data.owner': userId }).count()
return numMatches is 1
new Job(myJobs, 'cleanup', {})
.repeat({ schedule: myJobs.later.parse.text("every 5 minutes") })
.save({cancelRepeats: true})
q = myJobs.processJobs 'cleanup', { pollInterval: false, workTimeout: 60*1000 }, (job, cb) ->
current = new Date()
current.setMinutes(current.getMinutes() - 5)
ids = myJobs.find({
status:
$in: Job.jobStatusRemovable
updated:
$lt: current},
{fields: { _id: 1 }}).map (d) -> d._id
myJobs.removeJobs(ids) if ids.length > 0
# console.warn "Removed #{ids.length} old jobs"
job.done("Removed #{ids.length} old jobs")
cb()
myJobs.find({ type: 'cleanup', status: 'ready' })
.observe
added: () ->
q.trigger()
| true | ############################################################################
# Copyright (C) 2015-2016 by PI:NAME:<NAME>END_PI
# meteor-job-collection-playground is free software released under the MIT/X11 license.
# See included LICENSE file for details.
############################################################################
myJobs = new JobCollection 'queue',
idGeneration: 'MONGO'
transform: (d) ->
try
res = new Job myJobs, d
catch e
res = d
return res
later = myJobs.later
if Meteor.isClient
tick = 2500
stats = new Mongo.Collection 'jobStats'
Meteor.subscribe 'clientStats'
jobsProcessed = new ReactiveVar(0)
reactiveWindowWidth = new ReactiveVar(0)
Meteor.startup () ->
timeout = null
reactiveWindowWidth.set $(window).width()
$(window).resize () ->
Meteor.clearTimeout(timeout) if timeout
timeout = Meteor.setTimeout () ->
timeout = null
reactiveWindowWidth.set $(window).width()
, 100
parseState = new ReactiveVar ""
parseSched = new ReactiveVar []
reactiveDate = new ReactiveVar new Date()
localWorker = new ReactiveVar null
Meteor.setInterval((() -> reactiveDate.set new Date()), tick)
q = null
myType = 'testJob_null'
timeFormatter = (time) ->
now = reactiveDate.get()
if Math.abs(time - now) < tick
"Now"
else
moment(time).from(now)
# Ensure that the callback is not called multiple times
once = (func) ->
called = false
return () ->
unless called
called = true
func()
else
console.warn("Callback invoked multiple times!")
nextStep = (func) ->
Meteor.setTimeout(func, 500)
Tracker.autorun () ->
userId = Meteor.userId()
suffix = if userId then "_#{userId.substr(0,5)}" else ""
myType = "testJob#{suffix}"
Meteor.subscribe 'allJobs', userId
q?.shutdown { level: 'hard' }
q = myJobs.processJobs myType, { pollInterval: false, workTimeout: 60*1000 }, (job, cb) ->
done = 0
localWorker.set job.doc
workStep = () ->
lw = localWorker.get()
if lw
done++
if done is 20
localWorker.set null
jobsProcessed.set jobsProcessed.get() + 1
job.done(once(cb))
else
job.progress done, 20, (err, res) ->
if err or not res
localWorker.set null
job.fail('Progress update failed', once(cb))
else
localWorker.set job.doc
nextStep workStep
else if lw is null
job.fail('User aborted job', once(cb))
else
# Simulate a crash
once(cb)() # Return without .done or .fail, creating a zombie
workStep()
obs = myJobs.find({ type: myType, status: 'ready' })
.observe
added: () -> q.trigger()
Template.registerHelper "jobCollection", () -> myJobs
Template.registerHelper "localWorker", () -> localWorker.get()
Template.registerHelper "wideScreen", () -> reactiveWindowWidth.get() > 1745
Template.registerHelper "relativeTime", (time) ->
timeFormatter time
Template.registerHelper "equals", (a, b) -> a is b
truncateId = (id, length = 6) ->
if id
if typeof id is 'object'
id = "#{id.valueOf()}"
"#{id.substr(0,6)}…"
else
""
Template.registerHelper "truncateId", truncateId
Template.top.helpers
userId: () ->
Meteor.userId()
clientsConnected: () ->
return stats.findOne('stats')?.currentClients or '0'
Template.workerPanel.helpers
jobsProcessed: () ->
return jobsProcessed.get()
Template.workerPanel.events
'click .fail-job': (e, t) ->
localWorker.set null
'click .crash-job': (e, t) ->
localWorker.set false
Template.jobTable.helpers
jobEntries: () ->
# Reactively populate the table
this.find({}, { sort: { after: -1 }})
jobsProcessed: () ->
return stats.findOne('stats')?.jobsProcessed or '0'
numWorkers: () ->
return stats.findOne('stats')?.clientsSeen or '0'
handleButtonPopup = () ->
this.$('.button')
.popup
inline: true
position: 'bottom center'
delay:
show: 500
hide: 0
Template.pauseButton.onRendered handleButtonPopup
Template.removeButton.onRendered handleButtonPopup
Template.resumeButton.onRendered handleButtonPopup
Template.restartButton.onRendered handleButtonPopup
Template.rerunButton.onRendered handleButtonPopup
Template.cancelButton.onRendered handleButtonPopup
Template.readyNowButton.onRendered handleButtonPopup
Template.jobEntry.events
'click .cancel-job': (e, t) ->
job = Template.currentData()
job.cancel() if job
'click .remove-job': (e, t) ->
job = Template.currentData()
job.remove() if job
'click .restart-job': (e, t) ->
job = Template.currentData()
job.restart({ retries: if job._doc.retries then 0 else 1 }) if job
'click .rerun-job': (e, t) ->
job = Template.currentData()
job.rerun({ wait: 15000 }) if job
'click .pause-job': (e, t) ->
job = Template.currentData()
job.pause() if job
'click .resume-job': (e, t) ->
job = Template.currentData()
job.resume() if job
'click .ready-job': (e, t) ->
job = Template.currentData()
job.ready({ time: myJobs.foreverDate }) if job
# If two values sum to forever, then ∞, else the first value
isInfinity = (val1, val2) ->
if (val1 + val2) is Job.forever
"∞"
else
val1
Template.jobEntry.helpers
statusBG: () ->
{
waiting: 'grey'
ready: 'blue'
paused: 'black'
running: 'default'
cancelled: 'yellow'
failed: 'red'
completed: 'green'
}[this.status]
numRepeats: () -> isInfinity this.repeats, this.repeated
numRetries: () -> isInfinity this.retries, this.retried
futurePast: () ->
now = reactiveDate.get()
if this.after > now
"text-danger"
else
"text-success"
cancellable: () ->
this.status in Job.jobStatusCancellable
removable: () ->
this.status in Job.jobStatusRemovable
restartable: () ->
this.status in Job.jobStatusRestartable
pausable: () ->
this.status in Job.jobStatusPausable
Template.newJobInput.helpers
inputParseState: () ->
parseState.get()
inputReady: () ->
parseState.get() is "has-success"
inputError: () ->
if parseState.get() is "has-error"
"error"
else
""
nextTimes: () ->
reactiveDate.get()
for t in parseSched.get().next(3)
"#{moment(t).calendar()} (local time), #{moment(t).fromNow()}. [#{moment(t).toISOString()}]"
Template.logEntries.helpers
recentEvents: (numEvents = 5) ->
output = []
this.find({}, { fields: { log: 1, type: 1 }, transform: null, limit: numEvents, sort: { updated: -1 }})
.forEach (doc) ->
for event in doc.log
event.type = doc.type
event.jobId = truncateId doc._id
event.runId = truncateId event.runId
event.level = "error" if event.level is 'danger'
output.push event
output.sort (a, b) ->
b.time - a.time
output.slice 0, numEvents
levelIcon: () ->
switch this.level
when 'info' then 'info'
when 'success' then 'trophy'
when 'warning' then 'warning sign'
when 'error' then 'thumbs down'
else 'bug'
validateCRON = (val) ->
re = /^(?:\*|\d{1,2})(?:(?:(?:[\/-]\d{1,2})?)|(?:,\d{1,2})+)\ *(?:\ (?:\*|\d{1,2})(?:(?:(?:[\/-]\d{1,2})?)|(?:,\d{1,2})+)\ *)*$/
return null unless val.match re
sp = val.split /\ +/
if 5 <= sp.length <= 6
return sp.length is 6
else
return null
newJobSubmit = (e, t) ->
val = t.find("#inputLater").value
cronFlag = validateCRON val
if cronFlag?
s = later.parse.cron val, cronFlag
s.error = -1 if s?
else
s = later.parse.text(val)
if s.error is -1
job = new Job(myJobs, myType, { owner: Meteor.userId() })
.retry({ retries: 2, wait: 30000, backoff: 'exponential'})
.repeat({ schedule: s })
.save({cancelRepeats: true})
else
parseState.set "has-error"
Template.newJobInput.events
'click #newJob': newJobSubmit
'keyup #inputLater': (e, t) ->
if e.keyCode is 13
newJobSubmit e, t
'input #inputLater': (e, t) ->
val = e.target.value.trim()
unless val
parseState.set ""
parseSched.set []
else
s = later.parse.text val
# The following is to work around this bug:
# https://github.com/bunkat/later/issues/97
try
later.schedule(s).next()
catch
s = {}
if s.error is -1
parseState.set "has-success"
parseSched.set later.schedule(s)
else
cronFlag = validateCRON val
if cronFlag?
sCron = later.parse.cron val, cronFlag
if sCron
parseState.set "has-success"
parseSched.set later.schedule(sCron)
else
parseState.set parseState.set "has-warning"
parseSched.set []
else
parseState.set "has-warning"
parseSched.set []
Template.jobControls.events
'click .pause-queue': (e, t) ->
if $(e.target).hasClass 'active'
$(e.target).removeClass 'active'
ids = t.data.find({ status: 'paused' },{ fields: { _id: 1 }}).map (d) -> d._id
t.data.resumeJobs(ids) if ids.length > 0
else
$(e.target).addClass 'active'
ids = t.data.find({ status: { $in: Job.jobStatusPausable }}, { fields: { _id: 1 }}).map (d) -> d._id
t.data.pauseJobs(ids) if ids.length > 0
'click .cancel-queue': (e, t) ->
ids = t.data.find({ status: { $in: Job.jobStatusCancellable }}, { fields: { _id: 1 }}).map (d) -> d._id
t.data.cancelJobs(ids) if ids.length > 0
'click .restart-queue': (e, t) ->
ids = t.data.find({ status: { $in: Job.jobStatusRestartable }}, { fields: { _id: 1 }}).map (d) -> d._id
t.data.restartJobs(ids) if ids.length > 0
'click .rerun-queue': (e, t) ->
t.data.find({ status: 'completed' }).forEach (d) ->
d.rerun { wait: 15000 }
'click .remove-queue': (e, t) ->
ids = t.data.find({ status: { $in: Job.jobStatusRemovable }}, { fields: { _id: 1 }}).map (d) -> d._id
t.data.removeJobs(ids) if ids.length > 0
#######################################################
if Meteor.isServer
# myJobs.setLogStream process.stdout
myJobs.promote 5000
Meteor.startup () ->
# Don't allow users to modify the user docs
Meteor.users.deny({update: () -> true })
myJobs.startJobServer()
jobsProcessed = 0
clientsSeen = {}
currentClients = {}
publishStatsChanges = () ->
f() for c, f of currentClients
return null
Meteor.publish 'clientStats', () ->
currentClients[@connection.id] = () =>
@changed 'jobStats', 'stats',
jobsProcessed: jobsProcessed
clientsSeen: Object.keys(clientsSeen).length
currentClients: Object.keys(currentClients).length
@onStop () =>
delete currentClients[@connection.id]
publishStatsChanges()
@added 'jobStats', 'stats',
jobsProcessed: jobsProcessed
clientsSeen: Object.keys(clientsSeen).length
currentClients: Object.keys(currentClients).length
@ready()
publishStatsChanges()
myJobs.events.on 'jobDone', (msg) ->
unless msg.error or not msg.connection
jobsProcessed++
clientsSeen[msg.connection.id] ?= 0
clientsSeen[msg.connection.id]++
publishStatsChanges()
Meteor.publish 'allJobs', (clientUserId) ->
# This prevents a race condition on the client between Meteor.userId() and subscriptions to this publish
# See: https://stackoverflow.com/questions/24445404/how-to-prevent-a-client-reactive-race-between-meteor-userid-and-a-subscription/24460877#24460877
if this.userId is clientUserId
suffix = if this.userId then "_#{this.userId.substr(0,5)}" else ""
return myJobs.find({ type: "testJob#{suffix}", 'data.owner': this.userId })
else
return []
myJobs.events.on 'error', (msg) ->
console.warn "#{new Date()}, #{msg.userId}, #{msg.method}, #{msg.error}\n"
# Only allow job owners to manage or rerun jobs
myJobs.allow
manager: (userId, method, params) ->
ids = params[0]
unless typeof ids is 'object' and ids instanceof Array
ids = [ ids ]
numIds = ids.length
numMatches = myJobs.find({ _id: { $in: ids }, 'data.owner': userId }).count()
return numMatches is numIds
jobRerun: (userId, method, params) ->
id = params[0]
numMatches = myJobs.find({ _id: id, 'data.owner': userId }).count()
return numMatches is 1
jobSave: (userId, method, params) ->
doc = params[0]
return doc.data.owner is userId
getWork: (userId, method, params) ->
suffix = if userId then "_#{userId.substr(0,5)}" else ""
params[0][0] is "testJob#{suffix}" and params[0].length is 1
worker: (userId, method, params) ->
if method is 'getWork'
return false
else
id = params[0]
numMatches = myJobs.find({ _id: id, 'data.owner': userId }).count()
return numMatches is 1
new Job(myJobs, 'cleanup', {})
.repeat({ schedule: myJobs.later.parse.text("every 5 minutes") })
.save({cancelRepeats: true})
q = myJobs.processJobs 'cleanup', { pollInterval: false, workTimeout: 60*1000 }, (job, cb) ->
current = new Date()
current.setMinutes(current.getMinutes() - 5)
ids = myJobs.find({
status:
$in: Job.jobStatusRemovable
updated:
$lt: current},
{fields: { _id: 1 }}).map (d) -> d._id
myJobs.removeJobs(ids) if ids.length > 0
# console.warn "Removed #{ids.length} old jobs"
job.done("Removed #{ids.length} old jobs")
cb()
myJobs.find({ type: 'cleanup', status: 'ready' })
.observe
added: () ->
q.trigger()
|
[
{
"context": "browser uploading a file.\"\n\tmsg += \"Please contact info@mooqita.org.\"\n\tsAlert.error msg\n\n\tthrow new Meteor.Error msg\n",
"end": 482,
"score": 0.9999268651008606,
"start": 466,
"tag": "EMAIL",
"value": "info@mooqita.org"
}
] | client/components/script/upload.coffee | agottschalk10/worklearn | 0 | ##############################################
#
##############################################
##############################################
_files = {}
_get_file_data_from_event = (event) ->
if event.srcElement
crm_data = event.srcElement.result
if crm_data
return crm_data
if event.target
moz_data = event.target.result
if moz_data
return moz_data
msg = "We encountered a problem with your browser uploading a file."
msg += "Please contact info@mooqita.org."
sAlert.error msg
throw new Meteor.Error msg
##############################################
_get_file_size_text = (byte) ->
kb = Math.round(byte / 1024)
if kb < 500
return kb + " Kbyte"
mb = Math.round(kb / 1024)
if mb < 1
return Math.round(kb / 1024, 2)
return mb + " Mbyte"
##############################################
get_box_id = () ->
box_id = Template.instance().box_id.get()
if not box_id
sAlert.error('Object does not have a box_id')
return box_id
##############################################
get_files = () ->
box_id = get_box_id()
res = _files[box_id]
return res
##############################################
add_files = (n, box_id = null) ->
if not box_id
box_id = get_box_id()
d = _files[box_id]
Array::push.apply d, n
_files[box_id] = d
Session.set('_files', Math.random())
##############################################
get_form = (box_id = null) ->
if not box_id
box_id = get_box_id()
frm = $('#dropbox_'+box_id)
return frm
##############################################
# Upload
##############################################
##############################################
Template.upload.onCreated ->
this.uploaded = new ReactiveVar("")
files = Session.get('_files')
if not files
Session.set('_files', Math.random())
if this.data.name in _files
sAlert.log('upload name: "' + this.data.name + '" already in use.')
return
box_id = Math.floor(Math.random()*10000000)
this.box_id = new ReactiveVar(box_id)
_files[box_id] = []
##############################################
Template.upload.helpers
uploaded: ->
return Template.instance().uploaded.get()
files: ->
if Session.get('_files') != 0
return get_files()
box_id: ->
return get_box_id()
upload_style: ()->
div = document.createElement('div')
do_drag = (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div))
can_do = do_drag && 'FormData' in window && 'FileReader' in window
can_do=true
if can_do == true
return('has-advanced-upload')
else
return('')
##############################################
Template.upload.events
'dropped .dropbox': (event) ->
n = event.originalEvent.dataTransfer.files
if n.length == 0
box_id = get_box_id()
event.originalEvent.dataTransfer.items[0].getAsString (data)->
add_files ['"'+data+'"'], box_id
if not this.multiple
get_form(box_id).trigger('submit')
else
add_files n
if not this.multiple
get_form().trigger('submit')
'change #file': (event)->
n = event.target.files
add_files n
if not this.multiple
get_form().trigger('submit')
'submit form': (event) ->
self = Template.instance()
event.preventDefault()
frm = get_form()
if frm.hasClass('is-uploading')
return false
if !Meteor.userId()
sAlert.error "Please login to upload files."
return
files = get_files()
box_id = get_box_id()
if !files
sAlert.error "No files selected to upload."
return
if files.length == 0
sAlert.error ("No files selected to upload.")
return
frm.addClass('is-uploading').removeClass('is-error')
upload_method = this.method
filesToRead = files.length
filesRead = 0
filesUp = 0
cumulative_size = 0
max_size = this.max_size
if not max
max = 4*1024*1024
for file in files
col = this.collection_name
item = this.item_id
field = this.field
fileReader = new FileReader()
type = file.type
if type == ""
type = file.name.split(".")
type = type[type.length-1]
if not typeof file == "object"
sAlert.error 'File upload failed not a valid file.'
continue
fileReader.onload = (ev) ->
filesRead += 1
raw = _get_file_data_from_event(ev)
base = btoa(raw)
data = "data:" + type + ";base64," + base
cumulative_size = cumulative_size + data.length
if cumulative_size > max_size
frm.removeClass('is-uploading')
_files[box_id] = []
fs_t = _get_file_size_text cumulative_size
ms_t = _get_file_size_text max_size
tx = "File upload failed. Cumulative file size is: "
tx += fs_t + "."
tx += "Maximum allowed is "
tx += ms_t + "."
sAlert.error(tx)
frm.addClass("is-error")
return
Meteor.call upload_method, col, item, field, data, type,
(err, rsp)->
filesUp += 1
if err
sAlert.error('File upload failed: ' + err)
frm.addClass('is-error')
if filesUp==filesToRead
frm.removeClass('is-uploading')
self.uploaded.set _files[box_id][0].name
_files[box_id] = []
if not err
sAlert.success('Upload done!')
try
fileReader.readAsBinaryString(file)
catch error
sAlert.error 'File upload failed: ' + error
event.target.files = null
'dragover .dropbox, dragenter .dropbox': (event)->
get_form().addClass('is-dragover')
'dragleave .dropbox, dragend .dropbox, drop .dropbox': (event)->
get_form().removeClass('is-dragover')
'dragexit .dropbox': (event) ->
sAlert.info('exit')
'click #restart': (event) ->
get_form().removeClass('is-uploading').removeClass('is-error')
| 88460 | ##############################################
#
##############################################
##############################################
_files = {}
_get_file_data_from_event = (event) ->
if event.srcElement
crm_data = event.srcElement.result
if crm_data
return crm_data
if event.target
moz_data = event.target.result
if moz_data
return moz_data
msg = "We encountered a problem with your browser uploading a file."
msg += "Please contact <EMAIL>."
sAlert.error msg
throw new Meteor.Error msg
##############################################
_get_file_size_text = (byte) ->
kb = Math.round(byte / 1024)
if kb < 500
return kb + " Kbyte"
mb = Math.round(kb / 1024)
if mb < 1
return Math.round(kb / 1024, 2)
return mb + " Mbyte"
##############################################
get_box_id = () ->
box_id = Template.instance().box_id.get()
if not box_id
sAlert.error('Object does not have a box_id')
return box_id
##############################################
get_files = () ->
box_id = get_box_id()
res = _files[box_id]
return res
##############################################
add_files = (n, box_id = null) ->
if not box_id
box_id = get_box_id()
d = _files[box_id]
Array::push.apply d, n
_files[box_id] = d
Session.set('_files', Math.random())
##############################################
get_form = (box_id = null) ->
if not box_id
box_id = get_box_id()
frm = $('#dropbox_'+box_id)
return frm
##############################################
# Upload
##############################################
##############################################
Template.upload.onCreated ->
this.uploaded = new ReactiveVar("")
files = Session.get('_files')
if not files
Session.set('_files', Math.random())
if this.data.name in _files
sAlert.log('upload name: "' + this.data.name + '" already in use.')
return
box_id = Math.floor(Math.random()*10000000)
this.box_id = new ReactiveVar(box_id)
_files[box_id] = []
##############################################
Template.upload.helpers
uploaded: ->
return Template.instance().uploaded.get()
files: ->
if Session.get('_files') != 0
return get_files()
box_id: ->
return get_box_id()
upload_style: ()->
div = document.createElement('div')
do_drag = (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div))
can_do = do_drag && 'FormData' in window && 'FileReader' in window
can_do=true
if can_do == true
return('has-advanced-upload')
else
return('')
##############################################
Template.upload.events
'dropped .dropbox': (event) ->
n = event.originalEvent.dataTransfer.files
if n.length == 0
box_id = get_box_id()
event.originalEvent.dataTransfer.items[0].getAsString (data)->
add_files ['"'+data+'"'], box_id
if not this.multiple
get_form(box_id).trigger('submit')
else
add_files n
if not this.multiple
get_form().trigger('submit')
'change #file': (event)->
n = event.target.files
add_files n
if not this.multiple
get_form().trigger('submit')
'submit form': (event) ->
self = Template.instance()
event.preventDefault()
frm = get_form()
if frm.hasClass('is-uploading')
return false
if !Meteor.userId()
sAlert.error "Please login to upload files."
return
files = get_files()
box_id = get_box_id()
if !files
sAlert.error "No files selected to upload."
return
if files.length == 0
sAlert.error ("No files selected to upload.")
return
frm.addClass('is-uploading').removeClass('is-error')
upload_method = this.method
filesToRead = files.length
filesRead = 0
filesUp = 0
cumulative_size = 0
max_size = this.max_size
if not max
max = 4*1024*1024
for file in files
col = this.collection_name
item = this.item_id
field = this.field
fileReader = new FileReader()
type = file.type
if type == ""
type = file.name.split(".")
type = type[type.length-1]
if not typeof file == "object"
sAlert.error 'File upload failed not a valid file.'
continue
fileReader.onload = (ev) ->
filesRead += 1
raw = _get_file_data_from_event(ev)
base = btoa(raw)
data = "data:" + type + ";base64," + base
cumulative_size = cumulative_size + data.length
if cumulative_size > max_size
frm.removeClass('is-uploading')
_files[box_id] = []
fs_t = _get_file_size_text cumulative_size
ms_t = _get_file_size_text max_size
tx = "File upload failed. Cumulative file size is: "
tx += fs_t + "."
tx += "Maximum allowed is "
tx += ms_t + "."
sAlert.error(tx)
frm.addClass("is-error")
return
Meteor.call upload_method, col, item, field, data, type,
(err, rsp)->
filesUp += 1
if err
sAlert.error('File upload failed: ' + err)
frm.addClass('is-error')
if filesUp==filesToRead
frm.removeClass('is-uploading')
self.uploaded.set _files[box_id][0].name
_files[box_id] = []
if not err
sAlert.success('Upload done!')
try
fileReader.readAsBinaryString(file)
catch error
sAlert.error 'File upload failed: ' + error
event.target.files = null
'dragover .dropbox, dragenter .dropbox': (event)->
get_form().addClass('is-dragover')
'dragleave .dropbox, dragend .dropbox, drop .dropbox': (event)->
get_form().removeClass('is-dragover')
'dragexit .dropbox': (event) ->
sAlert.info('exit')
'click #restart': (event) ->
get_form().removeClass('is-uploading').removeClass('is-error')
| true | ##############################################
#
##############################################
##############################################
_files = {}
_get_file_data_from_event = (event) ->
if event.srcElement
crm_data = event.srcElement.result
if crm_data
return crm_data
if event.target
moz_data = event.target.result
if moz_data
return moz_data
msg = "We encountered a problem with your browser uploading a file."
msg += "Please contact PI:EMAIL:<EMAIL>END_PI."
sAlert.error msg
throw new Meteor.Error msg
##############################################
_get_file_size_text = (byte) ->
kb = Math.round(byte / 1024)
if kb < 500
return kb + " Kbyte"
mb = Math.round(kb / 1024)
if mb < 1
return Math.round(kb / 1024, 2)
return mb + " Mbyte"
##############################################
get_box_id = () ->
box_id = Template.instance().box_id.get()
if not box_id
sAlert.error('Object does not have a box_id')
return box_id
##############################################
get_files = () ->
box_id = get_box_id()
res = _files[box_id]
return res
##############################################
add_files = (n, box_id = null) ->
if not box_id
box_id = get_box_id()
d = _files[box_id]
Array::push.apply d, n
_files[box_id] = d
Session.set('_files', Math.random())
##############################################
get_form = (box_id = null) ->
if not box_id
box_id = get_box_id()
frm = $('#dropbox_'+box_id)
return frm
##############################################
# Upload
##############################################
##############################################
Template.upload.onCreated ->
this.uploaded = new ReactiveVar("")
files = Session.get('_files')
if not files
Session.set('_files', Math.random())
if this.data.name in _files
sAlert.log('upload name: "' + this.data.name + '" already in use.')
return
box_id = Math.floor(Math.random()*10000000)
this.box_id = new ReactiveVar(box_id)
_files[box_id] = []
##############################################
Template.upload.helpers
uploaded: ->
return Template.instance().uploaded.get()
files: ->
if Session.get('_files') != 0
return get_files()
box_id: ->
return get_box_id()
upload_style: ()->
div = document.createElement('div')
do_drag = (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div))
can_do = do_drag && 'FormData' in window && 'FileReader' in window
can_do=true
if can_do == true
return('has-advanced-upload')
else
return('')
##############################################
Template.upload.events
'dropped .dropbox': (event) ->
n = event.originalEvent.dataTransfer.files
if n.length == 0
box_id = get_box_id()
event.originalEvent.dataTransfer.items[0].getAsString (data)->
add_files ['"'+data+'"'], box_id
if not this.multiple
get_form(box_id).trigger('submit')
else
add_files n
if not this.multiple
get_form().trigger('submit')
'change #file': (event)->
n = event.target.files
add_files n
if not this.multiple
get_form().trigger('submit')
'submit form': (event) ->
self = Template.instance()
event.preventDefault()
frm = get_form()
if frm.hasClass('is-uploading')
return false
if !Meteor.userId()
sAlert.error "Please login to upload files."
return
files = get_files()
box_id = get_box_id()
if !files
sAlert.error "No files selected to upload."
return
if files.length == 0
sAlert.error ("No files selected to upload.")
return
frm.addClass('is-uploading').removeClass('is-error')
upload_method = this.method
filesToRead = files.length
filesRead = 0
filesUp = 0
cumulative_size = 0
max_size = this.max_size
if not max
max = 4*1024*1024
for file in files
col = this.collection_name
item = this.item_id
field = this.field
fileReader = new FileReader()
type = file.type
if type == ""
type = file.name.split(".")
type = type[type.length-1]
if not typeof file == "object"
sAlert.error 'File upload failed not a valid file.'
continue
fileReader.onload = (ev) ->
filesRead += 1
raw = _get_file_data_from_event(ev)
base = btoa(raw)
data = "data:" + type + ";base64," + base
cumulative_size = cumulative_size + data.length
if cumulative_size > max_size
frm.removeClass('is-uploading')
_files[box_id] = []
fs_t = _get_file_size_text cumulative_size
ms_t = _get_file_size_text max_size
tx = "File upload failed. Cumulative file size is: "
tx += fs_t + "."
tx += "Maximum allowed is "
tx += ms_t + "."
sAlert.error(tx)
frm.addClass("is-error")
return
Meteor.call upload_method, col, item, field, data, type,
(err, rsp)->
filesUp += 1
if err
sAlert.error('File upload failed: ' + err)
frm.addClass('is-error')
if filesUp==filesToRead
frm.removeClass('is-uploading')
self.uploaded.set _files[box_id][0].name
_files[box_id] = []
if not err
sAlert.success('Upload done!')
try
fileReader.readAsBinaryString(file)
catch error
sAlert.error 'File upload failed: ' + error
event.target.files = null
'dragover .dropbox, dragenter .dropbox': (event)->
get_form().addClass('is-dragover')
'dragleave .dropbox, dragend .dropbox, drop .dropbox': (event)->
get_form().removeClass('is-dragover')
'dragexit .dropbox': (event) ->
sAlert.info('exit')
'click #restart': (event) ->
get_form().removeClass('is-uploading').removeClass('is-error')
|
[
{
"context": "toewijzen van een variabele (bijvoorbeeld naam = \"Henk\"). Om te kijken of een uitspraak true of false is",
"end": 1659,
"score": 0.7556160688400269,
"start": 1655,
"tag": "NAME",
"value": "Henk"
}
] | _coffeescripts/interactive_lessons/hoofdstuk1_geert.coffee | b1592/b1592.github.io | 2 | this.lesson = new Lesson([
new Question(
{
description: "Ruby kan ook rekenen. Typ maar eens 3 + 4.",
answer: /^-?\d+\s*\+\s*-?\d+\s*$/,
possible_errors: {
min: /^\d+\s*-\s*\d+\s*$/
},
error_messages: {
min: "Inderdaad, Ruby kan ook getallen van elkaar aftrekken! Typ je toch even 3 + 4?",
default: "Dat is niet goed. Tel je twee getallen op?"
}
}),
new Question(
{
description: "Heel goed. Wat dacht je van 5 * 8?",
answer: /^-?\d+\s*\*\s*-?\d+\s*$/,
possible_errors: {
},
error_messages: {
default: "Dat is niet goed. Gebruik je * (een sterretje)?"
}
}),
new Question(
{
description: "* (sterretje) betekent 'keer'. Wat denk je dat 2 ** 4 doet?",
answer: /^-?\d+\s*\*\*\s*-?\d+\s*$/,
possible_errors: {
},
error_messages: {
default: "Dat is niet goed. Gebruik je **?"
}
}),
new Question(
{
description: "** is machtsverheffen. Nu gaan we aan Ruby vragen of een uitspraak 'waar' of 'niet waar' is. Typ eens 3 < 5 (drie is kleiner dan 5.)",
answer: /^3\s*<\s*5\s*$/,
possible_errors: {
},
error_messages: {
default: "Dat is niet goed. Gebruik < ('kleiner dan'.)"
}
}),
new Question(
{
description: "true!. Typ nu eens 1 + 1 == 3.",
answer: /^1\s*\+\s*1\s*==\s*3\s*$/,
possible_errors: {
enkele_is: /^1\s*\+\s*1\s*=\s*3\s*$/
},
error_messages: {
enkele_is: 'Gebruik een dubbel is-teken! Een enkel is-teken wordt gebruikt voor het toewijzen van een variabele (bijvoorbeeld naam = "Henk"). Om te kijken of een uitspraak true of false is heb je == nodig. Ruby snapt het niet, zie je? Typ 1 + 1 == 3.'
default: "Dat is niet goed. Typ je 1 + 1 == 3?"
}
}),
new Question(
{
description: "1 + 1 is natuurlijk geen 3, dus Ruby geeft false. Typ nu eens 5 != 10 (vijf is niet gelijk aan tien.)",
answer: /^-?\d+\s*!=\s*-?\d+\s*$/,
possible_errors: {
},
error_messages: {
default: "Dat is niet goed. Gebruik je != (is niet gelijk aan?)"
}
}),
]) | 127645 | this.lesson = new Lesson([
new Question(
{
description: "Ruby kan ook rekenen. Typ maar eens 3 + 4.",
answer: /^-?\d+\s*\+\s*-?\d+\s*$/,
possible_errors: {
min: /^\d+\s*-\s*\d+\s*$/
},
error_messages: {
min: "Inderdaad, Ruby kan ook getallen van elkaar aftrekken! Typ je toch even 3 + 4?",
default: "Dat is niet goed. Tel je twee getallen op?"
}
}),
new Question(
{
description: "Heel goed. Wat dacht je van 5 * 8?",
answer: /^-?\d+\s*\*\s*-?\d+\s*$/,
possible_errors: {
},
error_messages: {
default: "Dat is niet goed. Gebruik je * (een sterretje)?"
}
}),
new Question(
{
description: "* (sterretje) betekent 'keer'. Wat denk je dat 2 ** 4 doet?",
answer: /^-?\d+\s*\*\*\s*-?\d+\s*$/,
possible_errors: {
},
error_messages: {
default: "Dat is niet goed. Gebruik je **?"
}
}),
new Question(
{
description: "** is machtsverheffen. Nu gaan we aan Ruby vragen of een uitspraak 'waar' of 'niet waar' is. Typ eens 3 < 5 (drie is kleiner dan 5.)",
answer: /^3\s*<\s*5\s*$/,
possible_errors: {
},
error_messages: {
default: "Dat is niet goed. Gebruik < ('kleiner dan'.)"
}
}),
new Question(
{
description: "true!. Typ nu eens 1 + 1 == 3.",
answer: /^1\s*\+\s*1\s*==\s*3\s*$/,
possible_errors: {
enkele_is: /^1\s*\+\s*1\s*=\s*3\s*$/
},
error_messages: {
enkele_is: 'Gebruik een dubbel is-teken! Een enkel is-teken wordt gebruikt voor het toewijzen van een variabele (bijvoorbeeld naam = "<NAME>"). Om te kijken of een uitspraak true of false is heb je == nodig. Ruby snapt het niet, zie je? Typ 1 + 1 == 3.'
default: "Dat is niet goed. Typ je 1 + 1 == 3?"
}
}),
new Question(
{
description: "1 + 1 is natuurlijk geen 3, dus Ruby geeft false. Typ nu eens 5 != 10 (vijf is niet gelijk aan tien.)",
answer: /^-?\d+\s*!=\s*-?\d+\s*$/,
possible_errors: {
},
error_messages: {
default: "Dat is niet goed. Gebruik je != (is niet gelijk aan?)"
}
}),
]) | true | this.lesson = new Lesson([
new Question(
{
description: "Ruby kan ook rekenen. Typ maar eens 3 + 4.",
answer: /^-?\d+\s*\+\s*-?\d+\s*$/,
possible_errors: {
min: /^\d+\s*-\s*\d+\s*$/
},
error_messages: {
min: "Inderdaad, Ruby kan ook getallen van elkaar aftrekken! Typ je toch even 3 + 4?",
default: "Dat is niet goed. Tel je twee getallen op?"
}
}),
new Question(
{
description: "Heel goed. Wat dacht je van 5 * 8?",
answer: /^-?\d+\s*\*\s*-?\d+\s*$/,
possible_errors: {
},
error_messages: {
default: "Dat is niet goed. Gebruik je * (een sterretje)?"
}
}),
new Question(
{
description: "* (sterretje) betekent 'keer'. Wat denk je dat 2 ** 4 doet?",
answer: /^-?\d+\s*\*\*\s*-?\d+\s*$/,
possible_errors: {
},
error_messages: {
default: "Dat is niet goed. Gebruik je **?"
}
}),
new Question(
{
description: "** is machtsverheffen. Nu gaan we aan Ruby vragen of een uitspraak 'waar' of 'niet waar' is. Typ eens 3 < 5 (drie is kleiner dan 5.)",
answer: /^3\s*<\s*5\s*$/,
possible_errors: {
},
error_messages: {
default: "Dat is niet goed. Gebruik < ('kleiner dan'.)"
}
}),
new Question(
{
description: "true!. Typ nu eens 1 + 1 == 3.",
answer: /^1\s*\+\s*1\s*==\s*3\s*$/,
possible_errors: {
enkele_is: /^1\s*\+\s*1\s*=\s*3\s*$/
},
error_messages: {
enkele_is: 'Gebruik een dubbel is-teken! Een enkel is-teken wordt gebruikt voor het toewijzen van een variabele (bijvoorbeeld naam = "PI:NAME:<NAME>END_PI"). Om te kijken of een uitspraak true of false is heb je == nodig. Ruby snapt het niet, zie je? Typ 1 + 1 == 3.'
default: "Dat is niet goed. Typ je 1 + 1 == 3?"
}
}),
new Question(
{
description: "1 + 1 is natuurlijk geen 3, dus Ruby geeft false. Typ nu eens 5 != 10 (vijf is niet gelijk aan tien.)",
answer: /^-?\d+\s*!=\s*-?\d+\s*$/,
possible_errors: {
},
error_messages: {
default: "Dat is niet goed. Gebruik je != (is niet gelijk aan?)"
}
}),
]) |
[
{
"context": ")\n\n SearchResult\n key: \"search-#{key}\"\n\n # -- Generates a configuration wind",
"end": 1739,
"score": 0.9010417461395264,
"start": 1730,
"tag": "KEY",
"value": "search-#{"
},
{
"context": "\n\n AccountConfig\n ... | client/app/components/panel.coffee | gelnior/cozy-emails | 0 | React = require 'react'
_ = require 'underscore'
# Components
{Spinner} = require('./basic_components').factories
AccountConfig = React.createFactory require './account_config'
Compose = React.createFactory require './compose'
Conversation = React.createFactory require './conversation'
MessageList = React.createFactory require './message-list'
Settings = React.createFactory require './settings'
SearchResult = React.createFactory require './search_result'
# React Mixins
RouterMixin = require '../mixins/router_mixin'
TooltipRefesherMixin = require '../mixins/tooltip_refresher_mixin'
# Flux stores
AccountStore = require '../stores/account_store'
MessageStore = require '../stores/message_store'
SearchStore = require '../stores/search_store'
SettingsStore = require '../stores/settings_store'
MessageActionCreator = require '../actions/message_action_creator'
{ComposeActions} = require '../constants/app_constants'
module.exports = Panel = React.createClass
displayName: 'Panel'
mixins: [
TooltipRefesherMixin
RouterMixin
]
# Build initial state from store values.
getInitialState: ->
@getStateFromStores()
componentDidMount: ->
MessageStore.addListener 'change', @fetchMessageComplete
componentWillUnmount: ->
MessageStore.removeListener 'change', @fetchMessageComplete
render: ->
# -- Generates a list of messages for a given account and mailbox
if @props.action is 'account.mailbox.messages'
@renderList()
else if @props.action is 'search'
key = encodeURIComponent SearchStore.getCurrentSearch()
SearchResult
key: "search-#{key}"
# -- Generates a configuration window for a given account
else if @props.action is 'account.config' or
@props.action is 'account.new'
id = @props.accountID or 'new'
AccountConfig
key: "account-config-#{id}"
tab: @props.tab
# -- Generates a conversation
else if @props.action is 'message' or
@props.action is 'conversation'
Conversation
messageID: @props.messageID
key: 'conversation-' + @props.messageID
ref: 'conversation'
# -- Display the settings form
else if @props.action is 'settings'
Settings
key : 'settings'
ref : 'settings'
settings: @state.settings
# -- Error case, shouldn't happen. Might be worth to make it pretty.
else
console.error "Unknown action #{@props.action}"
window.cozyMails.logInfo "Unknown action #{@props.action}"
return React.DOM.div null, "Unknown component #{@props.action}"
renderList: ->
unless @state.accounts.get @props.accountID
setTimeout =>
@redirect
direction : 'first'
action : 'default'
, 1
return React.DOM.div null, 'redirecting'
prefix = 'messageList-' + @props.mailboxID
MessageList
key : MessageStore.getQueryKey prefix
accountID : @props.accountID
mailboxID : @props.mailboxID
queryParams : MessageStore.getQueryParams()
# Rendering the compose component requires several parameters. The main one
# are related to the selected account, the selected mailbox and the compose
# state (classic, draft, reply, reply all or forward).
renderCompose: ->
options =
layout : 'full'
action : null
inReplyTo : null
settings : @state.settings
accounts : @state.accounts
selectedAccountID : @state.selectedAccount.get 'id'
selectedAccountLogin : @state.selectedAccount.get 'login'
selectedMailboxID : @props.selectedMailboxID
useIntents : @props.useIntents
ref : 'compose'
key : @props.action or 'compose'
component = null
# Generates an empty compose form
if @props.action is 'compose'
message = null
component = Compose options
# Generates the edit draft composition form.
else if @props.action is 'edit' or
@props.action is 'compose.edit'
component = Compose _.extend options,
key: options.key + '-' + @props.messageID
messageID: @props.messageID
# Generates the reply composition form.
else if @props.action is 'compose.reply'
options.action = ComposeActions.REPLY
component = @getReplyComponent options
# Generates the reply all composition form.
else if @props.action is 'compose.reply-all'
options.action = ComposeActions.REPLY_ALL
component = @getReplyComponent options
# Generates the forward composition form.
else if @props.action is 'compose.forward'
options.action = ComposeActions.FORWARD
component = @getReplyComponent options
else
throw new Error "unknown compose type : #{@prop.action}"
return component
# Configure the component depending on the given action.
# Returns a spinner if the message is not available.
getReplyComponent: (options) ->
options.id = @props.messageID
options.inReplyTo = @props.messageID
component = Compose options
return component
# Update state with store values.
fetchMessageComplete: (message) ->
return unless @isMounted()
@setState isLoadingReply: false
getStateFromStores: ->
return {
accounts : AccountStore.getAll()
selectedAccount : AccountStore.getSelectedOrDefault()
settings : SettingsStore.get()
isLoadingReply : not MessageStore.getByID(@props.messageID)?
}
| 182764 | React = require 'react'
_ = require 'underscore'
# Components
{Spinner} = require('./basic_components').factories
AccountConfig = React.createFactory require './account_config'
Compose = React.createFactory require './compose'
Conversation = React.createFactory require './conversation'
MessageList = React.createFactory require './message-list'
Settings = React.createFactory require './settings'
SearchResult = React.createFactory require './search_result'
# React Mixins
RouterMixin = require '../mixins/router_mixin'
TooltipRefesherMixin = require '../mixins/tooltip_refresher_mixin'
# Flux stores
AccountStore = require '../stores/account_store'
MessageStore = require '../stores/message_store'
SearchStore = require '../stores/search_store'
SettingsStore = require '../stores/settings_store'
MessageActionCreator = require '../actions/message_action_creator'
{ComposeActions} = require '../constants/app_constants'
module.exports = Panel = React.createClass
displayName: 'Panel'
mixins: [
TooltipRefesherMixin
RouterMixin
]
# Build initial state from store values.
getInitialState: ->
@getStateFromStores()
componentDidMount: ->
MessageStore.addListener 'change', @fetchMessageComplete
componentWillUnmount: ->
MessageStore.removeListener 'change', @fetchMessageComplete
render: ->
# -- Generates a list of messages for a given account and mailbox
if @props.action is 'account.mailbox.messages'
@renderList()
else if @props.action is 'search'
key = encodeURIComponent SearchStore.getCurrentSearch()
SearchResult
key: "<KEY>key}"
# -- Generates a configuration window for a given account
else if @props.action is 'account.config' or
@props.action is 'account.new'
id = @props.accountID or 'new'
AccountConfig
key: "<KEY>
tab: @props.tab
# -- Generates a conversation
else if @props.action is 'message' or
@props.action is 'conversation'
Conversation
messageID: @props.messageID
key: 'conversation<KEY>-' + @props.messageID
ref: 'conversation'
# -- Display the settings form
else if @props.action is 'settings'
Settings
key : 'settings'
ref : 'settings'
settings: @state.settings
# -- Error case, shouldn't happen. Might be worth to make it pretty.
else
console.error "Unknown action #{@props.action}"
window.cozyMails.logInfo "Unknown action #{@props.action}"
return React.DOM.div null, "Unknown component #{@props.action}"
renderList: ->
unless @state.accounts.get @props.accountID
setTimeout =>
@redirect
direction : 'first'
action : 'default'
, 1
return React.DOM.div null, 'redirecting'
prefix = 'messageList-' + @props.mailboxID
MessageList
key : MessageStore.getQueryKey prefix
accountID : @props.accountID
mailboxID : @props.mailboxID
queryParams : MessageStore.getQueryParams()
# Rendering the compose component requires several parameters. The main one
# are related to the selected account, the selected mailbox and the compose
# state (classic, draft, reply, reply all or forward).
renderCompose: ->
options =
layout : 'full'
action : null
inReplyTo : null
settings : @state.settings
accounts : @state.accounts
selectedAccountID : @state.selectedAccount.get 'id'
selectedAccountLogin : @state.selectedAccount.get 'login'
selectedMailboxID : @props.selectedMailboxID
useIntents : @props.useIntents
ref : 'compose'
key : @props.action or 'compose'
component = null
# Generates an empty compose form
if @props.action is 'compose'
message = null
component = Compose options
# Generates the edit draft composition form.
else if @props.action is 'edit' or
@props.action is 'compose.edit'
component = Compose _.extend options,
key: options.key + '-' + @props.messageID
messageID: @props.messageID
# Generates the reply composition form.
else if @props.action is 'compose.reply'
options.action = ComposeActions.REPLY
component = @getReplyComponent options
# Generates the reply all composition form.
else if @props.action is 'compose.reply-all'
options.action = ComposeActions.REPLY_ALL
component = @getReplyComponent options
# Generates the forward composition form.
else if @props.action is 'compose.forward'
options.action = ComposeActions.FORWARD
component = @getReplyComponent options
else
throw new Error "unknown compose type : #{@prop.action}"
return component
# Configure the component depending on the given action.
# Returns a spinner if the message is not available.
getReplyComponent: (options) ->
options.id = @props.messageID
options.inReplyTo = @props.messageID
component = Compose options
return component
# Update state with store values.
fetchMessageComplete: (message) ->
return unless @isMounted()
@setState isLoadingReply: false
getStateFromStores: ->
return {
accounts : AccountStore.getAll()
selectedAccount : AccountStore.getSelectedOrDefault()
settings : SettingsStore.get()
isLoadingReply : not MessageStore.getByID(@props.messageID)?
}
| true | React = require 'react'
_ = require 'underscore'
# Components
{Spinner} = require('./basic_components').factories
AccountConfig = React.createFactory require './account_config'
Compose = React.createFactory require './compose'
Conversation = React.createFactory require './conversation'
MessageList = React.createFactory require './message-list'
Settings = React.createFactory require './settings'
SearchResult = React.createFactory require './search_result'
# React Mixins
RouterMixin = require '../mixins/router_mixin'
TooltipRefesherMixin = require '../mixins/tooltip_refresher_mixin'
# Flux stores
AccountStore = require '../stores/account_store'
MessageStore = require '../stores/message_store'
SearchStore = require '../stores/search_store'
SettingsStore = require '../stores/settings_store'
MessageActionCreator = require '../actions/message_action_creator'
{ComposeActions} = require '../constants/app_constants'
module.exports = Panel = React.createClass
displayName: 'Panel'
mixins: [
TooltipRefesherMixin
RouterMixin
]
# Build initial state from store values.
getInitialState: ->
@getStateFromStores()
componentDidMount: ->
MessageStore.addListener 'change', @fetchMessageComplete
componentWillUnmount: ->
MessageStore.removeListener 'change', @fetchMessageComplete
render: ->
# -- Generates a list of messages for a given account and mailbox
if @props.action is 'account.mailbox.messages'
@renderList()
else if @props.action is 'search'
key = encodeURIComponent SearchStore.getCurrentSearch()
SearchResult
key: "PI:KEY:<KEY>END_PIkey}"
# -- Generates a configuration window for a given account
else if @props.action is 'account.config' or
@props.action is 'account.new'
id = @props.accountID or 'new'
AccountConfig
key: "PI:KEY:<KEY>END_PI
tab: @props.tab
# -- Generates a conversation
else if @props.action is 'message' or
@props.action is 'conversation'
Conversation
messageID: @props.messageID
key: 'conversationPI:KEY:<KEY>END_PI-' + @props.messageID
ref: 'conversation'
# -- Display the settings form
else if @props.action is 'settings'
Settings
key : 'settings'
ref : 'settings'
settings: @state.settings
# -- Error case, shouldn't happen. Might be worth to make it pretty.
else
console.error "Unknown action #{@props.action}"
window.cozyMails.logInfo "Unknown action #{@props.action}"
return React.DOM.div null, "Unknown component #{@props.action}"
renderList: ->
unless @state.accounts.get @props.accountID
setTimeout =>
@redirect
direction : 'first'
action : 'default'
, 1
return React.DOM.div null, 'redirecting'
prefix = 'messageList-' + @props.mailboxID
MessageList
key : MessageStore.getQueryKey prefix
accountID : @props.accountID
mailboxID : @props.mailboxID
queryParams : MessageStore.getQueryParams()
# Rendering the compose component requires several parameters. The main one
# are related to the selected account, the selected mailbox and the compose
# state (classic, draft, reply, reply all or forward).
renderCompose: ->
options =
layout : 'full'
action : null
inReplyTo : null
settings : @state.settings
accounts : @state.accounts
selectedAccountID : @state.selectedAccount.get 'id'
selectedAccountLogin : @state.selectedAccount.get 'login'
selectedMailboxID : @props.selectedMailboxID
useIntents : @props.useIntents
ref : 'compose'
key : @props.action or 'compose'
component = null
# Generates an empty compose form
if @props.action is 'compose'
message = null
component = Compose options
# Generates the edit draft composition form.
else if @props.action is 'edit' or
@props.action is 'compose.edit'
component = Compose _.extend options,
key: options.key + '-' + @props.messageID
messageID: @props.messageID
# Generates the reply composition form.
else if @props.action is 'compose.reply'
options.action = ComposeActions.REPLY
component = @getReplyComponent options
# Generates the reply all composition form.
else if @props.action is 'compose.reply-all'
options.action = ComposeActions.REPLY_ALL
component = @getReplyComponent options
# Generates the forward composition form.
else if @props.action is 'compose.forward'
options.action = ComposeActions.FORWARD
component = @getReplyComponent options
else
throw new Error "unknown compose type : #{@prop.action}"
return component
# Configure the component depending on the given action.
# Returns a spinner if the message is not available.
getReplyComponent: (options) ->
options.id = @props.messageID
options.inReplyTo = @props.messageID
component = Compose options
return component
# Update state with store values.
fetchMessageComplete: (message) ->
return unless @isMounted()
@setState isLoadingReply: false
getStateFromStores: ->
return {
accounts : AccountStore.getAll()
selectedAccount : AccountStore.getSelectedOrDefault()
settings : SettingsStore.get()
isLoadingReply : not MessageStore.getByID(@props.messageID)?
}
|
[
{
"context": "g', ->\n\t\t\toutput = table.horizontal [\n\t\t\t\t\tname: 'John Doe'\n\t\t\t\t\tage: 40\n\t\t\t\t\tjob: 'Developer'\n\t\t\t\t,\n\t\t\t\t\tna",
"end": 341,
"score": 0.9998136758804321,
"start": 333,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "\t\tage: 40\n\t\t\t... | tests/widgets/table.spec.coffee | balena-io-modules/resin-cli-visuals | 5 | m = require('mochainon')
table = require('../../lib/widgets/table')
describe 'Table:', ->
describe '.horizontal()', ->
it 'should return undefined if no data', ->
output = table.horizontal(null)
m.chai.expect(output).to.be.undefined
it 'should obey the imposed ordering', ->
output = table.horizontal [
name: 'John Doe'
age: 40
job: 'Developer'
,
name: 'Jane Doe'
age: 30
job: 'Designer'
], [ 'job', 'age', 'name' ]
m.chai.expect(output).to.equal [
'JOB AGE NAME'
'Developer 40 John Doe'
'Designer 30 Jane Doe'
].join('\n')
it 'should preserve new lines', ->
output = table.horizontal [
name: 'John Doe'
age: 40
job: 'Developer\nMusician'
,
name: 'Jane Doe'
age: 30
job: 'Designer\nActress'
], [ 'name', 'age', 'job' ]
m.chai.expect(output).to.equal [
'NAME AGE JOB'
'John Doe 40 Developer'
' Musician'
'Jane Doe 30 Designer'
' Actress'
].join('\n')
it 'should remove underscores from titles', ->
output = table.horizontal [
first_name: 'John'
last_name: 'Doe'
,
first_name: 'Jane'
last_name: 'Doe'
], [ 'first_name', 'last_name' ]
m.chai.expect(output).to.equal [
'FIRST NAME LAST NAME'
'John Doe'
'Jane Doe'
].join('\n')
it 'should handle camel case titles', ->
output = table.horizontal [
firstName: 'John'
lastName: 'Doe'
,
firstName: 'Jane'
lastName: 'Doe'
], [ 'firstName', 'lastName' ]
m.chai.expect(output).to.equal [
'FIRST NAME LAST NAME'
'John Doe'
'Jane Doe'
].join('\n')
it 'should print all data if no ordering', ->
output = table.horizontal [
name: 'John Doe'
age: 40
job: 'Developer'
,
name: 'Jane Doe'
age: 30
job: 'Designer'
]
m.chai.expect(output).to.equal [
'NAME AGE JOB'
'John Doe 40 Developer'
'Jane Doe 30 Designer'
].join('\n')
it 'should be able to dynamically rename columns', ->
output = table.horizontal [
name: 'John Doe'
age: 40
job: 'Developer'
,
name: 'Jane Doe'
age: 30
job: 'Designer'
], [
'name => The name'
'age => How old?'
'job => Life reason'
]
m.chai.expect(output).to.equal [
'THE NAME HOW OLD? LIFE REASON'
'John Doe 40 Developer'
'Jane Doe 30 Designer'
].join('\n')
describe '.vertical()', ->
it 'should output a vertical table', ->
output = table.vertical
name: 'John Doe'
age: 40
job: 'Developer'
, [ 'name', 'age', 'job' ]
m.chai.expect(output).to.equal [
'NAME: John Doe'
'AGE: 40'
'JOB: Developer'
].join('\n')
it 'should obey the imposed ordering', ->
output = table.vertical
name: 'John Doe'
age: 40
job: 'Developer'
, [ 'age', 'job', 'name' ]
m.chai.expect(output).to.equal [
'AGE: 40'
'JOB: Developer'
'NAME: John Doe'
].join('\n')
it 'should preserve new lines', ->
output = table.vertical
name: 'John Doe'
age: 40
job: 'Developer\nMusician'
, [ 'name', 'age', 'job' ]
m.chai.expect(output).to.equal [
'NAME: John Doe'
'AGE: 40'
'JOB: Developer'
' Musician'
].join('\n')
it 'should remove underscores from titles', ->
output = table.vertical
first_name: 'John'
last_name: 'Doe'
, [ 'first_name', 'last_name' ]
m.chai.expect(output).to.equal [
'FIRST NAME: John'
'LAST NAME: Doe'
].join('\n')
it 'should handle camel case titles', ->
output = table.vertical
firstName: 'John'
lastName: 'Doe'
, [ 'firstName', 'lastName' ]
m.chai.expect(output).to.equal [
'FIRST NAME: John'
'LAST NAME: Doe'
].join('\n')
it 'should print all data if no ordering', ->
output = table.vertical
name: 'John Doe'
age: 40
job: 'Developer'
m.chai.expect(output).to.equal [
'NAME: John Doe'
'AGE: 40'
'JOB: Developer'
].join('\n')
it 'should be able to dynamically rename columns', ->
output = table.vertical
name: 'John Doe'
age: 40
job: 'Developer'
, [
'name => The name'
'age => How old?'
'job => Life reason'
]
m.chai.expect(output).to.equal [
'THE NAME: John Doe'
'HOW OLD?: 40'
'LIFE REASON: Developer'
].join('\n')
it 'should support separators as empty string', ->
output = table.vertical
name: 'John Doe'
age: 40
job: 'Developer'
hobby: 'Musician'
, [
'name'
'age'
''
'job'
'hobby'
]
m.chai.expect(output).to.equal [
'NAME: John Doe'
'AGE: 40'
''
'JOB: Developer'
'HOBBY: Musician'
].join('\n')
it 'should support separators as null', ->
output = table.vertical
name: 'John Doe'
age: 40
job: 'Developer'
hobby: 'Musician'
, [
'name'
'age'
null
'job'
'hobby'
]
m.chai.expect(output).to.equal [
'NAME: John Doe'
'AGE: 40'
''
'JOB: Developer'
'HOBBY: Musician'
].join('\n')
it 'should support separators as blank strings', ->
output = table.vertical
name: 'John Doe'
age: 40
job: 'Developer'
hobby: 'Musician'
, [
'name'
'age'
' '
'job'
'hobby'
]
m.chai.expect(output).to.equal [
'NAME: John Doe'
'AGE: 40'
''
'JOB: Developer'
'HOBBY: Musician'
].join('\n')
it 'should support multiple separators', ->
output = table.vertical
name: 'John Doe'
age: 40
job: 'Developer'
hobby: 'Musician'
, [
'name'
''
'age'
''
'job'
''
'hobby'
]
m.chai.expect(output).to.equal [
'NAME: John Doe'
''
'AGE: 40'
''
'JOB: Developer'
''
'HOBBY: Musician'
].join('\n')
it 'should support group subtitles', ->
output = table.vertical
name: 'John Doe'
age: 40
job: 'Developer'
hobby: 'Musician'
, [
'$summary$'
'name'
'age'
''
'$extras$'
'job'
'hobby'
]
m.chai.expect(output).to.equal [
'== SUMMARY'
'NAME: John Doe'
'AGE: 40'
''
'== EXTRAS'
'JOB: Developer'
'HOBBY: Musician'
].join('\n')
it 'should support multi word group subtitles', ->
output = table.vertical
name: 'John Doe'
age: 40
job: 'Developer'
, [
'$person short summary$'
'name'
'age'
]
m.chai.expect(output).to.equal [
'== PERSON SHORT SUMMARY'
'NAME: John Doe'
'AGE: 40'
].join('\n')
| 61796 | m = require('mochainon')
table = require('../../lib/widgets/table')
describe 'Table:', ->
describe '.horizontal()', ->
it 'should return undefined if no data', ->
output = table.horizontal(null)
m.chai.expect(output).to.be.undefined
it 'should obey the imposed ordering', ->
output = table.horizontal [
name: '<NAME>'
age: 40
job: 'Developer'
,
name: '<NAME>'
age: 30
job: 'Designer'
], [ 'job', 'age', 'name' ]
m.chai.expect(output).to.equal [
'JOB AGE NAME'
'Developer 40 <NAME>'
'Designer 30 <NAME>'
].join('\n')
it 'should preserve new lines', ->
output = table.horizontal [
name: '<NAME>'
age: 40
job: 'Developer\nMusician'
,
name: '<NAME>'
age: 30
job: 'Designer\nActress'
], [ 'name', 'age', 'job' ]
m.chai.expect(output).to.equal [
'NAME AGE JOB'
'<NAME> 40 Developer'
' Musician'
'<NAME> 30 Designer'
' Actress'
].join('\n')
it 'should remove underscores from titles', ->
output = table.horizontal [
first_name: '<NAME>'
last_name: '<NAME>'
,
first_name: '<NAME>'
last_name: '<NAME>'
], [ 'first_name', 'last_name' ]
m.chai.expect(output).to.equal [
'FIRST NAME LAST NAME'
'<NAME> <NAME>'
'<NAME> <NAME>'
].join('\n')
it 'should handle camel case titles', ->
output = table.horizontal [
firstName: '<NAME>'
lastName: '<NAME>'
,
firstName: '<NAME>'
lastName: '<NAME>'
], [ 'firstName', 'lastName' ]
m.chai.expect(output).to.equal [
'FIRST NAME LAST NAME'
'<NAME> <NAME>'
'<NAME> <NAME>'
].join('\n')
it 'should print all data if no ordering', ->
output = table.horizontal [
name: '<NAME>'
age: 40
job: 'Developer'
,
name: '<NAME>'
age: 30
job: 'Designer'
]
m.chai.expect(output).to.equal [
'NAME AGE JOB'
'<NAME> 40 Developer'
'<NAME> 30 Designer'
].join('\n')
it 'should be able to dynamically rename columns', ->
output = table.horizontal [
name: '<NAME>'
age: 40
job: 'Developer'
,
name: '<NAME>'
age: 30
job: 'Designer'
], [
'name => The name'
'age => How old?'
'job => Life reason'
]
m.chai.expect(output).to.equal [
'THE NAME HOW OLD? LIFE REASON'
'<NAME> 40 Developer'
'<NAME> 30 Designer'
].join('\n')
describe '.vertical()', ->
it 'should output a vertical table', ->
output = table.vertical
name: '<NAME>'
age: 40
job: 'Developer'
, [ 'name', 'age', 'job' ]
m.chai.expect(output).to.equal [
'NAME: <NAME>'
'AGE: 40'
'JOB: Developer'
].join('\n')
it 'should obey the imposed ordering', ->
output = table.vertical
name: '<NAME>'
age: 40
job: 'Developer'
, [ 'age', 'job', 'name' ]
m.chai.expect(output).to.equal [
'AGE: 40'
'JOB: Developer'
'NAME: <NAME>'
].join('\n')
it 'should preserve new lines', ->
output = table.vertical
name: '<NAME>'
age: 40
job: 'Developer\nMusician'
, [ 'name', 'age', 'job' ]
m.chai.expect(output).to.equal [
'NAME: <NAME>'
'AGE: 40'
'JOB: Developer'
' Musician'
].join('\n')
it 'should remove underscores from titles', ->
output = table.vertical
first_name: '<NAME>'
last_name: '<NAME>'
, [ 'first_name', 'last_name' ]
m.chai.expect(output).to.equal [
'FIRST NAME: <NAME>'
'LAST NAME: <NAME>'
].join('\n')
it 'should handle camel case titles', ->
output = table.vertical
firstName: '<NAME>'
lastName: '<NAME>'
, [ 'firstName', 'lastName' ]
m.chai.expect(output).to.equal [
'FIRST NAME: <NAME>'
'LAST NAME: <NAME>'
].join('\n')
it 'should print all data if no ordering', ->
output = table.vertical
name: '<NAME>'
age: 40
job: 'Developer'
m.chai.expect(output).to.equal [
'NAME: <NAME>'
'AGE: 40'
'JOB: Developer'
].join('\n')
it 'should be able to dynamically rename columns', ->
output = table.vertical
name: '<NAME>'
age: 40
job: 'Developer'
, [
'name => The name'
'age => How old?'
'job => Life reason'
]
m.chai.expect(output).to.equal [
'THE NAME: <NAME>'
'HOW OLD?: 40'
'LIFE REASON: Developer'
].join('\n')
it 'should support separators as empty string', ->
output = table.vertical
name: '<NAME>'
age: 40
job: 'Developer'
hobby: 'Musician'
, [
'name'
'age'
''
'job'
'hobby'
]
m.chai.expect(output).to.equal [
'NAME: <NAME>'
'AGE: 40'
''
'JOB: Developer'
'HOBBY: Musician'
].join('\n')
it 'should support separators as null', ->
output = table.vertical
name: '<NAME>'
age: 40
job: 'Developer'
hobby: 'Musician'
, [
'name'
'age'
null
'job'
'hobby'
]
m.chai.expect(output).to.equal [
'NAME: <NAME>'
'AGE: 40'
''
'JOB: Developer'
'HOBBY: Musician'
].join('\n')
it 'should support separators as blank strings', ->
output = table.vertical
name: '<NAME>'
age: 40
job: 'Developer'
hobby: 'Musician'
, [
'name'
'age'
' '
'job'
'hobby'
]
m.chai.expect(output).to.equal [
'NAME: <NAME>'
'AGE: 40'
''
'JOB: Developer'
'HOBBY: Musician'
].join('\n')
it 'should support multiple separators', ->
output = table.vertical
name: '<NAME>'
age: 40
job: 'Developer'
hobby: 'Musician'
, [
'name'
''
'age'
''
'job'
''
'hobby'
]
m.chai.expect(output).to.equal [
'NAME: <NAME>'
''
'AGE: 40'
''
'JOB: Developer'
''
'HOBBY: Musician'
].join('\n')
it 'should support group subtitles', ->
output = table.vertical
name: '<NAME>'
age: 40
job: 'Developer'
hobby: 'Musician'
, [
'$summary$'
'name'
'age'
''
'$extras$'
'job'
'hobby'
]
m.chai.expect(output).to.equal [
'== SUMMARY'
'NAME: <NAME>'
'AGE: 40'
''
'== EXTRAS'
'JOB: Developer'
'HOBBY: Musician'
].join('\n')
it 'should support multi word group subtitles', ->
output = table.vertical
name: '<NAME>'
age: 40
job: 'Developer'
, [
'$person short summary$'
'name'
'age'
]
m.chai.expect(output).to.equal [
'== PERSON SHORT SUMMARY'
'NAME: <NAME>'
'AGE: 40'
].join('\n')
| true | m = require('mochainon')
table = require('../../lib/widgets/table')
describe 'Table:', ->
describe '.horizontal()', ->
it 'should return undefined if no data', ->
output = table.horizontal(null)
m.chai.expect(output).to.be.undefined
it 'should obey the imposed ordering', ->
output = table.horizontal [
name: 'PI:NAME:<NAME>END_PI'
age: 40
job: 'Developer'
,
name: 'PI:NAME:<NAME>END_PI'
age: 30
job: 'Designer'
], [ 'job', 'age', 'name' ]
m.chai.expect(output).to.equal [
'JOB AGE NAME'
'Developer 40 PI:NAME:<NAME>END_PI'
'Designer 30 PI:NAME:<NAME>END_PI'
].join('\n')
it 'should preserve new lines', ->
output = table.horizontal [
name: 'PI:NAME:<NAME>END_PI'
age: 40
job: 'Developer\nMusician'
,
name: 'PI:NAME:<NAME>END_PI'
age: 30
job: 'Designer\nActress'
], [ 'name', 'age', 'job' ]
m.chai.expect(output).to.equal [
'NAME AGE JOB'
'PI:NAME:<NAME>END_PI 40 Developer'
' Musician'
'PI:NAME:<NAME>END_PI 30 Designer'
' Actress'
].join('\n')
it 'should remove underscores from titles', ->
output = table.horizontal [
first_name: 'PI:NAME:<NAME>END_PI'
last_name: 'PI:NAME:<NAME>END_PI'
,
first_name: 'PI:NAME:<NAME>END_PI'
last_name: 'PI:NAME:<NAME>END_PI'
], [ 'first_name', 'last_name' ]
m.chai.expect(output).to.equal [
'FIRST NAME LAST NAME'
'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI'
].join('\n')
it 'should handle camel case titles', ->
output = table.horizontal [
firstName: 'PI:NAME:<NAME>END_PI'
lastName: 'PI:NAME:<NAME>END_PI'
,
firstName: 'PI:NAME:<NAME>END_PI'
lastName: 'PI:NAME:<NAME>END_PI'
], [ 'firstName', 'lastName' ]
m.chai.expect(output).to.equal [
'FIRST NAME LAST NAME'
'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI'
].join('\n')
it 'should print all data if no ordering', ->
output = table.horizontal [
name: 'PI:NAME:<NAME>END_PI'
age: 40
job: 'Developer'
,
name: 'PI:NAME:<NAME>END_PI'
age: 30
job: 'Designer'
]
m.chai.expect(output).to.equal [
'NAME AGE JOB'
'PI:NAME:<NAME>END_PI 40 Developer'
'PI:NAME:<NAME>END_PI 30 Designer'
].join('\n')
it 'should be able to dynamically rename columns', ->
output = table.horizontal [
name: 'PI:NAME:<NAME>END_PI'
age: 40
job: 'Developer'
,
name: 'PI:NAME:<NAME>END_PI'
age: 30
job: 'Designer'
], [
'name => The name'
'age => How old?'
'job => Life reason'
]
m.chai.expect(output).to.equal [
'THE NAME HOW OLD? LIFE REASON'
'PI:NAME:<NAME>END_PI 40 Developer'
'PI:NAME:<NAME>END_PI 30 Designer'
].join('\n')
describe '.vertical()', ->
it 'should output a vertical table', ->
output = table.vertical
name: 'PI:NAME:<NAME>END_PI'
age: 40
job: 'Developer'
, [ 'name', 'age', 'job' ]
m.chai.expect(output).to.equal [
'NAME: PI:NAME:<NAME>END_PI'
'AGE: 40'
'JOB: Developer'
].join('\n')
it 'should obey the imposed ordering', ->
output = table.vertical
name: 'PI:NAME:<NAME>END_PI'
age: 40
job: 'Developer'
, [ 'age', 'job', 'name' ]
m.chai.expect(output).to.equal [
'AGE: 40'
'JOB: Developer'
'NAME: PI:NAME:<NAME>END_PI'
].join('\n')
it 'should preserve new lines', ->
output = table.vertical
name: 'PI:NAME:<NAME>END_PI'
age: 40
job: 'Developer\nMusician'
, [ 'name', 'age', 'job' ]
m.chai.expect(output).to.equal [
'NAME: PI:NAME:<NAME>END_PI'
'AGE: 40'
'JOB: Developer'
' Musician'
].join('\n')
it 'should remove underscores from titles', ->
output = table.vertical
first_name: 'PI:NAME:<NAME>END_PI'
last_name: 'PI:NAME:<NAME>END_PI'
, [ 'first_name', 'last_name' ]
m.chai.expect(output).to.equal [
'FIRST NAME: PI:NAME:<NAME>END_PI'
'LAST NAME: PI:NAME:<NAME>END_PI'
].join('\n')
it 'should handle camel case titles', ->
output = table.vertical
firstName: 'PI:NAME:<NAME>END_PI'
lastName: 'PI:NAME:<NAME>END_PI'
, [ 'firstName', 'lastName' ]
m.chai.expect(output).to.equal [
'FIRST NAME: PI:NAME:<NAME>END_PI'
'LAST NAME: PI:NAME:<NAME>END_PI'
].join('\n')
it 'should print all data if no ordering', ->
output = table.vertical
name: 'PI:NAME:<NAME>END_PI'
age: 40
job: 'Developer'
m.chai.expect(output).to.equal [
'NAME: PI:NAME:<NAME>END_PI'
'AGE: 40'
'JOB: Developer'
].join('\n')
it 'should be able to dynamically rename columns', ->
output = table.vertical
name: 'PI:NAME:<NAME>END_PI'
age: 40
job: 'Developer'
, [
'name => The name'
'age => How old?'
'job => Life reason'
]
m.chai.expect(output).to.equal [
'THE NAME: PI:NAME:<NAME>END_PI'
'HOW OLD?: 40'
'LIFE REASON: Developer'
].join('\n')
it 'should support separators as empty string', ->
output = table.vertical
name: 'PI:NAME:<NAME>END_PI'
age: 40
job: 'Developer'
hobby: 'Musician'
, [
'name'
'age'
''
'job'
'hobby'
]
m.chai.expect(output).to.equal [
'NAME: PI:NAME:<NAME>END_PI'
'AGE: 40'
''
'JOB: Developer'
'HOBBY: Musician'
].join('\n')
it 'should support separators as null', ->
output = table.vertical
name: 'PI:NAME:<NAME>END_PI'
age: 40
job: 'Developer'
hobby: 'Musician'
, [
'name'
'age'
null
'job'
'hobby'
]
m.chai.expect(output).to.equal [
'NAME: PI:NAME:<NAME>END_PI'
'AGE: 40'
''
'JOB: Developer'
'HOBBY: Musician'
].join('\n')
it 'should support separators as blank strings', ->
output = table.vertical
name: 'PI:NAME:<NAME>END_PI'
age: 40
job: 'Developer'
hobby: 'Musician'
, [
'name'
'age'
' '
'job'
'hobby'
]
m.chai.expect(output).to.equal [
'NAME: PI:NAME:<NAME>END_PI'
'AGE: 40'
''
'JOB: Developer'
'HOBBY: Musician'
].join('\n')
it 'should support multiple separators', ->
output = table.vertical
name: 'PI:NAME:<NAME>END_PI'
age: 40
job: 'Developer'
hobby: 'Musician'
, [
'name'
''
'age'
''
'job'
''
'hobby'
]
m.chai.expect(output).to.equal [
'NAME: PI:NAME:<NAME>END_PI'
''
'AGE: 40'
''
'JOB: Developer'
''
'HOBBY: Musician'
].join('\n')
it 'should support group subtitles', ->
output = table.vertical
name: 'PI:NAME:<NAME>END_PI'
age: 40
job: 'Developer'
hobby: 'Musician'
, [
'$summary$'
'name'
'age'
''
'$extras$'
'job'
'hobby'
]
m.chai.expect(output).to.equal [
'== SUMMARY'
'NAME: PI:NAME:<NAME>END_PI'
'AGE: 40'
''
'== EXTRAS'
'JOB: Developer'
'HOBBY: Musician'
].join('\n')
it 'should support multi word group subtitles', ->
output = table.vertical
name: 'PI:NAME:<NAME>END_PI'
age: 40
job: 'Developer'
, [
'$person short summary$'
'name'
'age'
]
m.chai.expect(output).to.equal [
'== PERSON SHORT SUMMARY'
'NAME: PI:NAME:<NAME>END_PI'
'AGE: 40'
].join('\n')
|
[
{
"context": "templateData:\n site:\n title: \"Rob Loach\"\n url: \"http://github.com/robloach/slides\"\n ",
"end": 43,
"score": 0.9997386932373047,
"start": 34,
"tag": "NAME",
"value": "Rob Loach"
},
{
"context": " title: \"Rob Loach\"\n url: \"http://github.com/robloa... | docpad.cson | RobLoach/slides-docpad | 0 | templateData:
site:
title: "Rob Loach"
url: "http://github.com/robloach/slides"
description: """
A next generation web architecture allowing for content management via the
file system, rendering via plugins, and static site generation for
deployment anywhere.
"""
keywords: """
DocPad, openbar()
"""
# The website's styles
styles: [
'main.css'
]
# The website's scripts
scripts: [
'main.js'
]
| 71938 | templateData:
site:
title: "<NAME>"
url: "http://github.com/robloach/slides"
description: """
A next generation web architecture allowing for content management via the
file system, rendering via plugins, and static site generation for
deployment anywhere.
"""
keywords: """
DocPad, openbar()
"""
# The website's styles
styles: [
'main.css'
]
# The website's scripts
scripts: [
'main.js'
]
| true | templateData:
site:
title: "PI:NAME:<NAME>END_PI"
url: "http://github.com/robloach/slides"
description: """
A next generation web architecture allowing for content management via the
file system, rendering via plugins, and static site generation for
deployment anywhere.
"""
keywords: """
DocPad, openbar()
"""
# The website's styles
styles: [
'main.css'
]
# The website's scripts
scripts: [
'main.js'
]
|
[
{
"context": "eer\n @num: 1\n\n constructor: () ->\n @name = \"Seer\"\n\n # setAssignedMemberName: (@assignedMemberNa",
"end": 59,
"score": 0.8826694488525391,
"start": 57,
"tag": "NAME",
"value": "Se"
},
{
"context": "r\n @num: 1\n\n constructor: () ->\n @name = \"Seer\... | scripts/seer.coffee | mpppk/hubot-onenight-werewolf | 1 | class Seer
@num: 1
constructor: () ->
@name = "Seer"
# setAssignedMemberName: (@assignedMemberName) ->
# setMemberManager: (@memberManager) ->
# 夜の間に行う行動
workAtNight: () ->
# 夜に表示するメッセージ
getMessageAtNight: () ->
@messageAtNight
makeMessageAtNight: (@assignedMemberName, memberManager, messageManager) ->
msg = messageManager.youAre(messageManager.seerName)
maxIter = 1000 # 最大試行回数
for i in [0..maxIter]
otherMember = @memberManager.getMemberByRandom()
if otherMember.name != @assignedMemberName
roleName = otherMember.role.getName()
@messageAtNight = msg + "\n" +
messageManager.roleAndName( otherMember.name, roleName )
return
return "申し訳ありません。エラーが発生しました。ゲームをやり直してください。(Seer couldn't see other player)"
exports.Seer = Seer
| 8631 | class Seer
@num: 1
constructor: () ->
@name = "<NAME>er"
# setAssignedMemberName: (@assignedMemberName) ->
# setMemberManager: (@memberManager) ->
# 夜の間に行う行動
workAtNight: () ->
# 夜に表示するメッセージ
getMessageAtNight: () ->
@messageAtNight
makeMessageAtNight: (@assignedMemberName, memberManager, messageManager) ->
msg = messageManager.youAre(messageManager.seerName)
maxIter = 1000 # 最大試行回数
for i in [0..maxIter]
otherMember = @memberManager.getMemberByRandom()
if otherMember.name != @assignedMemberName
roleName = otherMember.role.getName()
@messageAtNight = msg + "\n" +
messageManager.roleAndName( otherMember.name, roleName )
return
return "申し訳ありません。エラーが発生しました。ゲームをやり直してください。(Seer couldn't see other player)"
exports.Seer = Seer
| true | class Seer
@num: 1
constructor: () ->
@name = "PI:NAME:<NAME>END_PIer"
# setAssignedMemberName: (@assignedMemberName) ->
# setMemberManager: (@memberManager) ->
# 夜の間に行う行動
workAtNight: () ->
# 夜に表示するメッセージ
getMessageAtNight: () ->
@messageAtNight
makeMessageAtNight: (@assignedMemberName, memberManager, messageManager) ->
msg = messageManager.youAre(messageManager.seerName)
maxIter = 1000 # 最大試行回数
for i in [0..maxIter]
otherMember = @memberManager.getMemberByRandom()
if otherMember.name != @assignedMemberName
roleName = otherMember.role.getName()
@messageAtNight = msg + "\n" +
messageManager.roleAndName( otherMember.name, roleName )
return
return "申し訳ありません。エラーが発生しました。ゲームをやり直してください。(Seer couldn't see other player)"
exports.Seer = Seer
|
[
{
"context": "class Plgs\n @name = \"Plgs\"\n\n constructor: ->\n @name = \"Plgs\"\n\nmodule.ex",
"end": 26,
"score": 0.7998771071434021,
"start": 22,
"tag": "NAME",
"value": "Plgs"
},
{
"context": "\n @name = \"Plgs\"\n\n constructor: ->\n @name = \"Plgs\"\n\nmodule.export... | src/index.coffee | seyself/plgs | 0 | class Plgs
@name = "Plgs"
constructor: ->
@name = "Plgs"
module.exports = Plgs
| 61312 | class Plgs
@name = "<NAME>"
constructor: ->
@name = "<NAME>"
module.exports = Plgs
| true | class Plgs
@name = "PI:NAME:<NAME>END_PI"
constructor: ->
@name = "PI:NAME:<NAME>END_PI"
module.exports = Plgs
|
[
{
"context": "roller = Ember.Controller.extend\n guy: \n id: \"harold\"\n name: \"harold chen\"\n title: \"the honorabl",
"end": 93,
"score": 0.9358696937561035,
"start": 87,
"tag": "NAME",
"value": "harold"
},
{
"context": "roller.extend\n guy: \n id: \"harold\"\n n... | tests/dummy/app/controllers/list.coffee | simwms/simwms-assets | 0 | `import Ember from 'ember'`
ListController = Ember.Controller.extend
guy:
id: "harold"
name: "harold chen"
title: "the honorable"
job: "gambler"
age: 44
martialStatus:
primary: "single"
secondary: "since 1995"
keys: Ember.A ["name", "title", "job", "age", "martialStatus", "nonfield"]
icons:
name: "fa fa-user fa-lg"
title: "fa fa-institution fa-lg"
job: "fa fa-gear fa-lg"
age: "fa fa-birthday-cake fa-lg"
martialStatus: "fa fa-heart-o fa-lg"
`export default ListController` | 187758 | `import Ember from 'ember'`
ListController = Ember.Controller.extend
guy:
id: "<NAME>"
name: "<NAME>"
title: "the honorable"
job: "gambler"
age: 44
martialStatus:
primary: "single"
secondary: "since 1995"
keys: Ember.A ["name", "title", "job", "age", "martialStatus", "nonfield"]
icons:
name: "fa fa-user fa-lg"
title: "fa fa-institution fa-lg"
job: "fa fa-gear fa-lg"
age: "fa fa-birthday-cake fa-lg"
martialStatus: "fa fa-heart-o fa-lg"
`export default ListController` | true | `import Ember from 'ember'`
ListController = Ember.Controller.extend
guy:
id: "PI:NAME:<NAME>END_PI"
name: "PI:NAME:<NAME>END_PI"
title: "the honorable"
job: "gambler"
age: 44
martialStatus:
primary: "single"
secondary: "since 1995"
keys: Ember.A ["name", "title", "job", "age", "martialStatus", "nonfield"]
icons:
name: "fa fa-user fa-lg"
title: "fa fa-institution fa-lg"
job: "fa fa-gear fa-lg"
age: "fa fa-birthday-cake fa-lg"
martialStatus: "fa fa-heart-o fa-lg"
`export default ListController` |
[
{
"context": "###\nCopyright (C) 2013, Bill Burdick, Tiny Concepts: https://github.com/zot/Leisure\n\n(",
"end": 36,
"score": 0.9998245239257812,
"start": 24,
"tag": "NAME",
"value": "Bill Burdick"
},
{
"context": ", Bill Burdick, Tiny Concepts: https://github.com/zot/Leisure\n\n(lic... | src/gen.coffee | zot/Leisure | 58 | ###
Copyright (C) 2013, Bill Burdick, Tiny Concepts: https://github.com/zot/Leisure
(licensed with ZLIB license)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
###
'use strict'
define ['./base', './ast', './runtime', 'lodash', 'lib/source-map', 'browser-source-map-support', 'lib/js-yaml'], (Base, Ast, Runtime, _, SourceMap, SourceMapSupport, Yaml)->
#SourceMapSupport?.install()
{
simpyCons
resolve
lazy
verboseMsg
nsLog
isResolved
addDebugType
getDebugType
setDebugType
} = Base
{
dump
} = Yaml
rz = resolve
lz = lazy
lc = Leisure_call
{
nameSub
getLitVal
getRefName
getLambdaVar
getLambdaBody
getApplyFunc
getApplyArg
getAnnoName
getAnnoData
getAnnoBody
getLetName
getLetValue
getLetBody
Leisure_lit
Leisure_ref
Leisure_lambda
Leisure_apply
Leisure_let
Leisure_anno
setType
setDataType
cons
Nil
define
functionInfo
getPos
isNil
getType
ast2Json
rangeToJson
getPos
} = root = Ast
{
Monad2
_true
_false
unit
left
right
booleanFor
newConsFrom
dumpMonadStack
} = Runtime
consFrom = newConsFrom
{
SourceNode
SourceMapConsumer
SourceMapGenerator
} = SourceMap
varNameSub = (n)-> "L_#{nameSub n}"
useArity = true
megaArity = false
curDef = null
#trace = false
trace = true
stackSize = 20
USE_STRICT = '"use strict";\n'
#USE_STRICT = ''
setMegaArity = (setting)-> megaArity = setting
setDebugType 'User'
#########
# Code
#########
setDebugType = (type)->
addDebugType type
Base.setDebugType type
collectArgs = (args, result)->
for i in args
if Array.isArray i then collectArgs i, result else result.push i
result
locateAst = (ast)->
[line, col] = pos = getPos(ast).toArray()
[line,col]
check = (bool, arg)->
if !bool then console.log new Error("Bad sourcemap arg: #{arg}").stack
checkChild = (child)->
if Array.isArray child
child.forEach checkChild
else check (typeof child == 'string') || (child instanceof SourceNode), child
currentFile = 'NEVERGIVENFILE.lsr'
currentFuncName = undefined
withFile = (file, name, block)->
oldFileName = currentFile
oldFuncName = currentFuncName
currentFile = file
currentFuncName = name
try
block()
finally
currentFile = oldFileName
currentFuncName = oldFuncName
sn = (ast, str...)->
[line, offset] = locateAst ast
check typeof line == 'number', 'line'
check typeof offset == 'number', 'offset'
checkChild str
if line < 1 then line = 1
if currentFile == 'NEVERGIVENFILE.lsr'
console.log new Error("SN CALLED WITHOUT FILE").stack
if currentFuncName?
new SourceNode(line, offset, currentFile, str, currentFuncName)
else new SourceNode(line, offset, currentFile, str)
jstr = (str)-> JSON.stringify str
jsCodeFor = (codeMap, mapType, externalMap)->
code = codeMap.code
if mapType == 'inline'
code = code.replace /map: '@SOURCEMAP@'/, 'inlineMap: ' + jstr codeMap.map.toJSON()
else if mapType == 'external'
code = code.replace /map: '@SOURCEMAP@'/, 'externalMap: ' + jstr externalMap
#"#{code}\n//# sourceMappingURL=data:application/json;base64,#{btoa jstr codeMap.map.toJSON()}\n"
"#{code}\n//# sourceMappingURL=data:application/json,#{jstr codeMap.map.toJSON()}\n"
functionId = 0
codeNum = 0
class CodeGenerator
constructor: (fileName, @useContext, @noFile, @suppressContextCreation, @source)->
@debugType = getDebugType()
@fileName = fileName ? "dynamic code with source #{++codeNum}"
@startId = functionId
@positions = []
@createContext = !@suppressContextCreation
@decls = []
@declStack = []
@funcInfo = []
@debug = false
contextInit: ->
if @useContext then '\n L$F.context = L_$context;'
else ''
funcVar: (index)-> "L$FUNC_#{index}"
addFuncInfo: (info)->
info.funcId = @funcInfo.length
@funcInfo.push info
@funcVar info.funcId
decl: (ast, dec)->
if @debug
dec.id = @decls.length
[line, col] = getPos(ast).toArray()
dec.line = line
dec.col = col
if @declStack.length then dec.parent = _.last(@declStack).id
@decls.push dec
@declStack.push dec
declLazy: (ast, arg)->
@decl ast, lazy: true
if arg?
result = arg()
@popDecl()
result
declLambda: (ast, name, args)->
@decl ast, dec = (lambda: name, args: args)
varName = @addFuncInfo info = {length:args.length, name, args, parent: dec.parent, id: dec.id}
dec.funcId = info.funcId
varName
popDecl: -> if @debug then @declStack.pop()
genSource: (source, ast)->
if @noFile
sm = @genNode(ast).prepend(USE_STRICT + '(').add(')').toStringWithSourceMap file: @fileName
map = JSON.parse sm.map.toString()
result = sm.code
else
funcName = if ast instanceof Leisure_anno && getAnnoName(ast) == 'leisureName'
getAnnoData ast
else null
#fileName = "dynamic code with source #{++codeNum}"
withFile @fileName, funcName, =>
try
sm = @genNode(ast).toStringWithSourceMap file: @fileName
map = JSON.parse sm.map.toString()
map.sourcesContent = [source]
result = sm.code
catch err
err.message = "Error generating code for:\n #{source.trim().replace /\n/g, '\n '}\n#{err.message}"
throw err
@endId = functionId
jsCodeFor sm, 'inline'
genNode: (ast)->
result = @genUniq ast, Nil, [Nil, 0]
@endId = functionId
@genTopLevel ast, result
genMap: (ast)->
hasFile = ast instanceof Leisure_anno && getAnnoName(ast) == 'filename'
#filename = if hasFile then getAnnoData ast else 'GENFORUNKNOWNFILE.lsr'
filename = if hasFile then getAnnoData ast else @fileName
nameAst = if hasFile then getAnnoBody ast else null
funcname = if nameAst instanceof Leisure_anno && getAnnoName(nameAst) == 'leisureName'
getAnnoData nameAst
else currentFuncName
sub = withFile filename, null, => @genNode(ast)
@endId = functionId
if !funcname then sub
else withFile filename, funcname, -> sn ast, sub
gen: (ast)->
result = @genMap(ast)
checkChild result
new SourceNode(1, 0, currentFile, ['(', result, ')']).toStringWithSourceMap(file: currentFile).code
genUniq: (ast, names, uniq)->
switch ast.constructor
when Leisure_lit then sn ast, jstr getLitVal ast
when Leisure_ref then sn ast, "resolve(", (@genRefName ast, uniq, names, true), ")"
when Leisure_lambda then @genLambda ast, names, uniq
when Leisure_apply
if useArity then @genArifiedApply ast, names, uniq
else sn ast, (@genUniq (getApplyFunc ast), names, uniq), "(", (@genApplyArg (getApplyArg ast), names, uniq), ")"
when Leisure_let then sn ast, "(function(){", (@genLets ast, names, uniq), "})()"
when Leisure_anno
name = getAnnoName ast
data = getAnnoData ast
if name == 'arity' && useArity && data > 1
@genArifiedLambda (getAnnoBody ast), names, uniq, data
else
try
switch name
when 'leisureName'
oldDef = curDef
curDef = data
when 'debug'
if Leisure_generateDebuggingCode
oldDebug = @debug
@debug = true
when 'define' then @declLazy getAnnoBody ast
genned = @genUniq (getAnnoBody ast), names, uniq
if name == 'debug' && Leisure_generateDebuggingCode then @debug = oldDebug
switch name
when 'type' then sn ast, "setType(", (genned), ", '", data, "')"
when 'dataType' then sn ast, "setDataType(", genned, ", '", data, "')"
when 'define'
[funcName, arity, src] = data.toArray()
@popDecl()
sn ast, "define('", funcName, "', ", lazify(ast, genned), ", ", arity, ", ", jstr(src), ")"
when 'leisureName' then genned
else genned
finally
if name == 'leisureName' then curDef = oldDef
else "CANNOT GENERATE CODE FOR UNKNOWN AST TYPE: #{ast}, #{ast.constructor} #{Leisure_lambda}"
genArifiedApply: (ast, names, uniq)->
args = []
func = ast
while dumpAnno(func) instanceof Leisure_apply
args.push getApplyArg dumpAnno func
func = getApplyFunc dumpAnno func
args.reverse()
defaultArity = false
if args.length > 1 && ((dmp = dumpAnno(func)) instanceof Leisure_ref) && (((info = functionInfo[funcName = getRefName dmp]) && ((info.newArity && (arity = info.arity) && arity <= args.length) || (!arity && megaArity))) || (!info && isNil names.find (el)-> el == funcName))
if defaultArity = !arity then arity = args.length
argCode = []
argCode.push ast
if defaultArity then argCode.push 'L$('
argCode.push @genUniq func, names, uniq
if defaultArity then argCode.push ')('
else argCode.push '('
for i in [0...arity]
if i > 0 then argCode.push ', '
argCode.push sn args[i], @genApplyArg args[i], names, uniq
argCode.push ')'
for i in [arity...args.length] by 1
argCode.push '(', (sn args[i], @genApplyArg args[i], names, uniq), ')'
sn argCode...
else
ast = dumpAnno ast
sn ast, (@genUniq (getApplyFunc ast), names, uniq), "(", (@genApplyArg (getApplyArg ast), names, uniq), ")"
genLambda: (ast, names, uniq)->
name = getLambdaVar ast
u = addUniq name, names, uniq
n = cons name, names
argName = (uniqName name, u)
defName = curDef
curDef = null
infoVar = @declLambda ast, defName, [name]
bodyCode = @genUniq (getLambdaBody ast), n, u
code = sn ast, "function(#{argName}){return ", @genTraceCall(ast, bodyCode, argName), ";}"
#addLambdaProperties ast, @genLambdaDecl ast, 'L$F.length', code
result = @genLambdaDecl ast, infoVar, defName, [name], 1, addLambdaProperties ast, code
@popDecl()
result
genArifiedLambda: (ast, names, uniq, arity)->
if arity < 2 then @genLambda ast, names, uniq, 0
else
args = getNArgs(arity, ast).toArray()
argList = _.map(args, ((x)-> 'L_' + x)).join ', '
defName = curDef
curDef = null
infoVar = @declLambda ast, defName, args
bodyCode = @genUniq(getNthLambdaBody(ast, arity), names, uniq)
if @debug then code = sn ast, """
function(#{argList}) {
return L_checkPartial(L$F, arguments, Leisure_traceCreatePartial#{@debugType}, Leisure_traceCallPartial#{@debugType}) || """, @genTraceCall(ast, bodyCode, argList), """;
};
"""
else code = sn ast, """
function(#{argList}) {
return L_checkPartial(L$F, arguments) || """, @genTraceCall(ast, bodyCode, argList), """;
};
"""
result = @genLambdaDecl ast, infoVar, defName, args, args.length, addLambdaProperties ast, code
annoAst = ast
while annoAst instanceof Leisure_anno
name = getAnnoName annoAst
data = getAnnoData annoAst
switch name
when 'type' then result = sn ast, "setType(", result, ", '", data, "')"
when 'dataType' then result = sn ast, "setDataType(", result, ", '", data, "')"
annoAst = getAnnoBody annoAst
@popDecl()
result
genRefName: (ref, uniq, names, checkMacro)->
name = getRefName ref
if isNil (val = names.find (el)-> el == name)
vname = varNameSub name
if !(window ? global)[vname] && Leisure.stateValues.macroDefs?.map.has name
throw new Error "Attempt to use a macro as a value: #{name}"
ns = findName nameSub name
if ns == root.currentNameSpace then nsLog "LOCAL NAME: #{name} FOR #{root.currentNameSpace} #{location ref}"
else if !ns then nsLog "GUESSING LOCAL NAME #{name} FOR #{root.currentNameSpace} #{location ref}"
vname
else uniqName name, uniq
genApplyArg: (arg, names, uniq)->
d = dumpAnno arg
if d instanceof Leisure_apply
@declLazy arg, => @lazify d, @genUniq arg, names, uniq
else if d instanceof Leisure_ref then @genRefName d, uniq, names
else if d instanceof Leisure_lit then sn arg, jstr getLitVal d
else if d instanceof Leisure_let
@declLazy arg, => @lazify arg, (@genUniq arg, names, uniq)
else if d instanceof Leisure_lambda then sn arg, 'lazy(', (@genUniq arg, names, uniq), ')'
else @declLazy arg, => @lazify arg, (@genUniq arg, names, uniq)
genLetAssign: (arg, names, uniq)->
@declLazy arg, => @lazify arg, (@genUniq arg, names, uniq)
lazify: (ast, body)->
lazify ast, body, (if @debug then _.last(@decls).id), @debug && @debugType
genLets: (ast, names, uniq)->
bindings = letList ast, []
[letUniq, decs, assigns, ln] = _.reduce bindings, ((result, l)=>
[u, code, assigns, ln] = result
newU = addUniq (getLetName l), ln, u
letName = uniqName (getLetName l), newU
newNames = cons (getLetName l), ln
[newU,
(cons (sn ast, letName + ' = ', @genLetAssign(getLetValue(l), newNames, u)), code),
(cons letName, assigns),
newNames]), [uniq, Nil, Nil, names]
sn ast, " var ", assigns.reverse().intersperse(', ').toArray(), ";\n ", decs.reverse().intersperse(';\n ').toArray(), ";\n\n return ", (@genUniq (getLastLetBody ast), ln, letUniq)
genTraceCall: (ast, code, argNames)->
if @debug then sn ast, """
(
Leisure_traceCall#{@debugType}(L$F, arguments),
Leisure_traceReturn#{@debugType}(L$F, (""", code, """))
)
"""
else code
genLambdaDecl: (ast, infoVar, name, args, length, code)->
if name then nameCode = jstr name
else nameCode = 'undefined'
infoVar = @addFuncInfo info = {length}
if @debug
info.id = _.last(@declStack).id
sn ast, """
(function(L$instance, L$parent){
var L$F = """, code, """;
L$F.L$info = #{infoVar};
L$F.L$instanceId = L$instance;
L$F.L$parentId = L$parent;
return Leisure_traceLambda#{@debugType}(L$F);
})(++Leisure_traceInstance, L$instance)
"""
else sn ast, """
(function(){
var L$F = """, code, """;
L$F.L$info = #{infoVar};
return L$F;
})()
"""
genAddSource: ->
if @source then "\n Leisure_addSourceFile(@fileName, #{jstr @source});"
else ''
genTraceMemos: ->
# memos for trace codes
''
genTopLevel: (ast, node)->
if dumpAnno(ast).constructor in [Leisure_lit, Leisure_ref] then node
else if @decls.length || @debug
header = "var L$ret;"
if @createContext then header += @genContext()
sn ast, """
(function(L$instance){
#{header}
return """, node, """;
})(++Leisure_traceInstance)
"""
else sn ast, """
(function(){
var L$context = null;
#{@genFuncInfo()}
return """, node, """;
})()
"""
genContext: ->
source = if @source || @noFile then """
source: Leisure_addSourceFile(#{jstr @fileName}, #{jstr @source}),
map: '@SOURCEMAP@'
"""
else if @sourceMap then """
source: #{jstr @fileName},
map: '@SOURCEMAP@'
"""
else """
source: #{jstr @fileName}
"""
decls = []
for decl in @decls
type = if decl.lazy then 'lazy' else 'lambda'
decls.push type, decl.line, decl.col, decl.parent
if type == 'lambda' then decls.push decl.lambda, decl.args.length, decl.args...
context = """
\n var L$context = Leisure_traceTopLevel#{@debugType}({
id: Leisure_traceContext++,
traceCreatePartial: function(){return Leisure_traceCreatePartial#{@debugType};},
traceCallPartial: function(){return Leisure_traceCallPartial#{@debugType};},
debugType: #{JSON.stringify @debugType},
#{source},
decls: #{JSON.stringify decls}
});
""" + @genFuncInfo()
genFuncInfo: ->
header = ''
if @decls.length
for info, i in @funcInfo
parent = info.parent? && @decls[info.parent]
while parent && parent.lazy
parent = @decls[parent.parent]
parent = if parent?.funcId then @funcVar parent.funcId
else 'null'
header += "\n var #{@funcVar i} = {name: #{JSON.stringify info.name}, args: #{JSON.stringify info.args}, id: #{info.id}, length: #{info.length}, parent: #{parent}, context: L$context};"
else
for info, i in @funcInfo
header += """
\n var #{@funcVar i} = {name: #{JSON.stringify info.name}, length: #{info.length}};
"""
header
lazify = (ast, body, id, debugType)->
if debugType
sn ast, """
(function(L$instance, L$parent) {
return Leisure_traceLazyValue#{debugType}(L$instance, L$context, #{id}, function(){
return Leisure_traceResolve#{debugType}(L$instance, """, body, """);
});
})(++Leisure_traceInstance, L$instance)
"""
else sn ast, """
function(){
return """, body, """;
}
"""
findName = (name)->
for i in [root.nameSpacePath.length - 1 .. 0]
if LeisureNameSpaces[root.nameSpacePath[i]]?[name] then return root.nameSpacePath[i]
if root.currentNameSpace && LeisureNameSpaces[root.currentNameSpace][name] then root.currentNameSpace
else null
location = (ast)->
[line, col] = locateAst ast
"#{line}:#{col}"
getLambdaArgs = (ast)->
args = []
while ast instanceof Leisure_lambda
args.push getLambdaVar ast
ast = getLambdaBody ast
[args, ast]
getNthLambdaBody = (ast, n)->
if n == 0 then ast
else if (d = dumpAnno ast) instanceof Leisure_lambda then getNthLambdaBody getLambdaBody(d), n - 1
else throw new Error "Expected lambda but got #{ast}"
(window ? global ? {}).curryCall = curryCall = (args, func)->
f = func args[0]
for i in [1...args.length]
f = f args[i]
f
getNArgs = (n, ast)->
d = dumpAnno ast
if !n then Nil else cons (getLambdaVar d), getNArgs n - 1, getLambdaBody d
specialAnnotations = ['type', 'dataType', 'define']
arrayify = (cons)->
if cons instanceof Leisure_cons then cons.map((el)-> arrayify el).toArray()
else cons
getLambdaProperties = (body, props)->
if body instanceof Leisure_anno
if !_.includes specialAnnotations, getAnnoName(body)
if !props then props = {}
value = getAnnoData body
props[getAnnoName body] = arrayify value
getLambdaProperties getAnnoBody(body), props
props
addLambdaProperties = (ast, def, extras)->
props = getLambdaProperties getLambdaBody ast
if props || extras
p = {}
if props then _.merge p, props
if extras then _.merge p, extras
sn ast, "setLambdaProperties(", def, ", ", (jstr p), ")"
else def
lcons = (a, b)-> rz(L_cons)(lz a)(lz b)
parseErr = (a, b)-> rz(L_parseErr)(a, b)
lconsFrom = (array)->
if array instanceof Array
p = rz L_nil
for el in array.reverse()
p = lcons lconsFrom(el), p
p
else array
assocListProps = null
getAssocListProps = ->
if !assocListProps
assocListProps = lcons lcons('assoc', 'true'), rz(L_nil)
assocListProps.properties = assocListProps
assocListProps
lacons = (key, value, list)->
alist = lcons lcons(key, value), list
alist.properties = getAssocListProps()
alist
(window ? global).setLambdaProperties = (def, props)->
p = rz L_nil
for k, v of props
p = lacons k, lconsFrom(v), p
def.properties = p
def
(global ? window).L$convertError = (err, args)->
if !err.L_stack
console.log 'CONVERTING ERROR:', err
(global ? window).ERR = err
err.L_stack = args.callee.L$stack
err.L_args = args
err
dumpAnno = (ast)-> if ast instanceof Leisure_anno then dumpAnno getAnnoBody ast else ast
addUniq = (name, names, uniq)->
if (names.find (el)-> el == name) != Nil
[overrides, num] = uniq
[(cons (cons name, "#{name}_#{num}"), overrides), num + 1]
else uniq
uniqName = (name, uniq)->
[uniq] = uniq
kv = uniq.find ((el)-> el.head() == name), uniq
varNameSub (if kv != Nil then kv.tail() else name)
letList = (ast, buf)->
if ast instanceof Leisure_let
buf.push ast
letList getLetBody(ast), buf
else buf
getLastLetBody = (ast)-> if ast instanceof Leisure_let then getLastLetBody getLetBody ast else ast
define 'debugType', (lvl)->
new Monad2 'debugType', (env, cont)->
setDebugType String rz lvl
cont unit()
define 'debugMessage', (type, msg)-> checkPartial(L_vectorRemove, arguments) || (
new Monad2 'debugMessage', (env, cont)->
count = (window ? global)["Leisure_traceMessage#{rz type}"] rz msg
env.writeTraceMessage count, rz msg
cont unit())
define 'traceOff', new Monad2 'traceOff', (env, cont)->
trace = false
cont unit()
define 'traceOn', new Monad2 'traceOn', (env, cont)->
trace = true
cont unit()
define 'runAst', ((code)->(ast)->
new Monad2 'runAst', (env, cont)->
#console.log "running code", code
jsCode = null
try
jsCode = if env.fileName then withFile env.fileName, null, =>
new CodeGenerator(env.fileName, false, true).genSource null, rz(ast)
else new CodeGenerator().genSource rz(code), rz(ast)
cont eval jsCode
catch err
dumpMonadStack err, env
codeMsg = (if jsCode then "CODE: \n#{jsCode}\n" else '')
baseMsg = "\n\nParse error: #{err.message}\n#{codeMsg}AST: "
err.message = "#{baseMsg}#{ast()}"
err.L$ast = ast
cont err), null, null, null, 'parser'
define 'genAst', ((ast)->
try
gen rz ast
catch err
parseErr (lz '\n\nParse error: ' + err.toString() + "AST: "), (ast)), null, null, null, 'parser'
#####
# TMP HOOKS
#####
#####
# END TMP HOOKS
#####
gen = (ast)-> new CodeGenerator().gen ast
genMap = (ast, fileName)->
new CodeGenerator(fileName, false, false, fileName).genMap ast
genSource = (source, ast)-> new CodeGenerator().genSource source, ast
{
gen
genMap
genSource
sourceNode: sn
withFile
curryCall
#useNameSpace: useNameSpace
#pushNameSpace: pushNameSpace
#getNameSpacePath: getNameSpacePath
#clearNameSpacePath: clearNameSpacePath
#saveNameSpace: saveNameSpace
#restoreNameSpace: restoreNameSpace
SourceNode
SourceMapConsumer
SourceMapGenerator
setMegaArity
CodeGenerator
setDebugType
jsCodeFor
}
| 172235 | ###
Copyright (C) 2013, <NAME>, Tiny Concepts: https://github.com/zot/Leisure
(licensed with ZLIB license)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
###
'use strict'
define ['./base', './ast', './runtime', 'lodash', 'lib/source-map', 'browser-source-map-support', 'lib/js-yaml'], (Base, Ast, Runtime, _, SourceMap, SourceMapSupport, Yaml)->
#SourceMapSupport?.install()
{
simpyCons
resolve
lazy
verboseMsg
nsLog
isResolved
addDebugType
getDebugType
setDebugType
} = Base
{
dump
} = Yaml
rz = resolve
lz = lazy
lc = Leisure_call
{
nameSub
getLitVal
getRefName
getLambdaVar
getLambdaBody
getApplyFunc
getApplyArg
getAnnoName
getAnnoData
getAnnoBody
getLetName
getLetValue
getLetBody
Leisure_lit
Leisure_ref
Leisure_lambda
Leisure_apply
Leisure_let
Leisure_anno
setType
setDataType
cons
Nil
define
functionInfo
getPos
isNil
getType
ast2Json
rangeToJson
getPos
} = root = Ast
{
Monad2
_true
_false
unit
left
right
booleanFor
newConsFrom
dumpMonadStack
} = Runtime
consFrom = newConsFrom
{
SourceNode
SourceMapConsumer
SourceMapGenerator
} = SourceMap
varNameSub = (n)-> "L_#{nameSub n}"
useArity = true
megaArity = false
curDef = null
#trace = false
trace = true
stackSize = 20
USE_STRICT = '"use strict";\n'
#USE_STRICT = ''
setMegaArity = (setting)-> megaArity = setting
setDebugType 'User'
#########
# Code
#########
setDebugType = (type)->
addDebugType type
Base.setDebugType type
collectArgs = (args, result)->
for i in args
if Array.isArray i then collectArgs i, result else result.push i
result
locateAst = (ast)->
[line, col] = pos = getPos(ast).toArray()
[line,col]
check = (bool, arg)->
if !bool then console.log new Error("Bad sourcemap arg: #{arg}").stack
checkChild = (child)->
if Array.isArray child
child.forEach checkChild
else check (typeof child == 'string') || (child instanceof SourceNode), child
currentFile = 'NEVERGIVENFILE.lsr'
currentFuncName = undefined
withFile = (file, name, block)->
oldFileName = currentFile
oldFuncName = currentFuncName
currentFile = file
currentFuncName = name
try
block()
finally
currentFile = oldFileName
currentFuncName = oldFuncName
sn = (ast, str...)->
[line, offset] = locateAst ast
check typeof line == 'number', 'line'
check typeof offset == 'number', 'offset'
checkChild str
if line < 1 then line = 1
if currentFile == 'NEVERGIVENFILE.lsr'
console.log new Error("SN CALLED WITHOUT FILE").stack
if currentFuncName?
new SourceNode(line, offset, currentFile, str, currentFuncName)
else new SourceNode(line, offset, currentFile, str)
jstr = (str)-> JSON.stringify str
jsCodeFor = (codeMap, mapType, externalMap)->
code = codeMap.code
if mapType == 'inline'
code = code.replace /map: '@SOURCEMAP@'/, 'inlineMap: ' + jstr codeMap.map.toJSON()
else if mapType == 'external'
code = code.replace /map: '@SOURCEMAP@'/, 'externalMap: ' + jstr externalMap
#"#{code}\n//# sourceMappingURL=data:application/json;base64,#{btoa jstr codeMap.map.toJSON()}\n"
"#{code}\n//# sourceMappingURL=data:application/json,#{jstr codeMap.map.toJSON()}\n"
functionId = 0
codeNum = 0
class CodeGenerator
constructor: (fileName, @useContext, @noFile, @suppressContextCreation, @source)->
@debugType = getDebugType()
@fileName = fileName ? "dynamic code with source #{++codeNum}"
@startId = functionId
@positions = []
@createContext = !@suppressContextCreation
@decls = []
@declStack = []
@funcInfo = []
@debug = false
contextInit: ->
if @useContext then '\n L$F.context = L_$context;'
else ''
funcVar: (index)-> "L$FUNC_#{index}"
addFuncInfo: (info)->
info.funcId = @funcInfo.length
@funcInfo.push info
@funcVar info.funcId
decl: (ast, dec)->
if @debug
dec.id = @decls.length
[line, col] = getPos(ast).toArray()
dec.line = line
dec.col = col
if @declStack.length then dec.parent = _.last(@declStack).id
@decls.push dec
@declStack.push dec
declLazy: (ast, arg)->
@decl ast, lazy: true
if arg?
result = arg()
@popDecl()
result
declLambda: (ast, name, args)->
@decl ast, dec = (lambda: name, args: args)
varName = @addFuncInfo info = {length:args.length, name, args, parent: dec.parent, id: dec.id}
dec.funcId = info.funcId
varName
popDecl: -> if @debug then @declStack.pop()
genSource: (source, ast)->
if @noFile
sm = @genNode(ast).prepend(USE_STRICT + '(').add(')').toStringWithSourceMap file: @fileName
map = JSON.parse sm.map.toString()
result = sm.code
else
funcName = if ast instanceof Leisure_anno && getAnnoName(ast) == 'leisureName'
getAnnoData ast
else null
#fileName = "dynamic code with source #{++codeNum}"
withFile @fileName, funcName, =>
try
sm = @genNode(ast).toStringWithSourceMap file: @fileName
map = JSON.parse sm.map.toString()
map.sourcesContent = [source]
result = sm.code
catch err
err.message = "Error generating code for:\n #{source.trim().replace /\n/g, '\n '}\n#{err.message}"
throw err
@endId = functionId
jsCodeFor sm, 'inline'
genNode: (ast)->
result = @genUniq ast, Nil, [Nil, 0]
@endId = functionId
@genTopLevel ast, result
genMap: (ast)->
hasFile = ast instanceof Leisure_anno && getAnnoName(ast) == 'filename'
#filename = if hasFile then getAnnoData ast else 'GENFORUNKNOWNFILE.lsr'
filename = if hasFile then getAnnoData ast else @fileName
nameAst = if hasFile then getAnnoBody ast else null
funcname = if nameAst instanceof Leisure_anno && getAnnoName(nameAst) == 'leisureName'
getAnnoData nameAst
else currentFuncName
sub = withFile filename, null, => @genNode(ast)
@endId = functionId
if !funcname then sub
else withFile filename, funcname, -> sn ast, sub
gen: (ast)->
result = @genMap(ast)
checkChild result
new SourceNode(1, 0, currentFile, ['(', result, ')']).toStringWithSourceMap(file: currentFile).code
genUniq: (ast, names, uniq)->
switch ast.constructor
when Leisure_lit then sn ast, jstr getLitVal ast
when Leisure_ref then sn ast, "resolve(", (@genRefName ast, uniq, names, true), ")"
when Leisure_lambda then @genLambda ast, names, uniq
when Leisure_apply
if useArity then @genArifiedApply ast, names, uniq
else sn ast, (@genUniq (getApplyFunc ast), names, uniq), "(", (@genApplyArg (getApplyArg ast), names, uniq), ")"
when Leisure_let then sn ast, "(function(){", (@genLets ast, names, uniq), "})()"
when Leisure_anno
name = getAnnoName ast
data = getAnnoData ast
if name == 'arity' && useArity && data > 1
@genArifiedLambda (getAnnoBody ast), names, uniq, data
else
try
switch name
when 'leisureName'
oldDef = curDef
curDef = data
when 'debug'
if Leisure_generateDebuggingCode
oldDebug = @debug
@debug = true
when 'define' then @declLazy getAnnoBody ast
genned = @genUniq (getAnnoBody ast), names, uniq
if name == 'debug' && Leisure_generateDebuggingCode then @debug = oldDebug
switch name
when 'type' then sn ast, "setType(", (genned), ", '", data, "')"
when 'dataType' then sn ast, "setDataType(", genned, ", '", data, "')"
when 'define'
[funcName, arity, src] = data.toArray()
@popDecl()
sn ast, "define('", funcName, "', ", lazify(ast, genned), ", ", arity, ", ", jstr(src), ")"
when 'leisureName' then genned
else genned
finally
if name == 'leisureName' then curDef = oldDef
else "CANNOT GENERATE CODE FOR UNKNOWN AST TYPE: #{ast}, #{ast.constructor} #{Leisure_lambda}"
genArifiedApply: (ast, names, uniq)->
args = []
func = ast
while dumpAnno(func) instanceof Leisure_apply
args.push getApplyArg dumpAnno func
func = getApplyFunc dumpAnno func
args.reverse()
defaultArity = false
if args.length > 1 && ((dmp = dumpAnno(func)) instanceof Leisure_ref) && (((info = functionInfo[funcName = getRefName dmp]) && ((info.newArity && (arity = info.arity) && arity <= args.length) || (!arity && megaArity))) || (!info && isNil names.find (el)-> el == funcName))
if defaultArity = !arity then arity = args.length
argCode = []
argCode.push ast
if defaultArity then argCode.push 'L$('
argCode.push @genUniq func, names, uniq
if defaultArity then argCode.push ')('
else argCode.push '('
for i in [0...arity]
if i > 0 then argCode.push ', '
argCode.push sn args[i], @genApplyArg args[i], names, uniq
argCode.push ')'
for i in [arity...args.length] by 1
argCode.push '(', (sn args[i], @genApplyArg args[i], names, uniq), ')'
sn argCode...
else
ast = dumpAnno ast
sn ast, (@genUniq (getApplyFunc ast), names, uniq), "(", (@genApplyArg (getApplyArg ast), names, uniq), ")"
genLambda: (ast, names, uniq)->
name = getLambdaVar ast
u = addUniq name, names, uniq
n = cons name, names
argName = (uniqName name, u)
defName = curDef
curDef = null
infoVar = @declLambda ast, defName, [name]
bodyCode = @genUniq (getLambdaBody ast), n, u
code = sn ast, "function(#{argName}){return ", @genTraceCall(ast, bodyCode, argName), ";}"
#addLambdaProperties ast, @genLambdaDecl ast, 'L$F.length', code
result = @genLambdaDecl ast, infoVar, defName, [name], 1, addLambdaProperties ast, code
@popDecl()
result
genArifiedLambda: (ast, names, uniq, arity)->
if arity < 2 then @genLambda ast, names, uniq, 0
else
args = getNArgs(arity, ast).toArray()
argList = _.map(args, ((x)-> 'L_' + x)).join ', '
defName = curDef
curDef = null
infoVar = @declLambda ast, defName, args
bodyCode = @genUniq(getNthLambdaBody(ast, arity), names, uniq)
if @debug then code = sn ast, """
function(#{argList}) {
return L_checkPartial(L$F, arguments, Leisure_traceCreatePartial#{@debugType}, Leisure_traceCallPartial#{@debugType}) || """, @genTraceCall(ast, bodyCode, argList), """;
};
"""
else code = sn ast, """
function(#{argList}) {
return L_checkPartial(L$F, arguments) || """, @genTraceCall(ast, bodyCode, argList), """;
};
"""
result = @genLambdaDecl ast, infoVar, defName, args, args.length, addLambdaProperties ast, code
annoAst = ast
while annoAst instanceof Leisure_anno
name = getAnnoName annoAst
data = getAnnoData annoAst
switch name
when 'type' then result = sn ast, "setType(", result, ", '", data, "')"
when 'dataType' then result = sn ast, "setDataType(", result, ", '", data, "')"
annoAst = getAnnoBody annoAst
@popDecl()
result
genRefName: (ref, uniq, names, checkMacro)->
name = getRefName ref
if isNil (val = names.find (el)-> el == name)
vname = varNameSub name
if !(window ? global)[vname] && Leisure.stateValues.macroDefs?.map.has name
throw new Error "Attempt to use a macro as a value: #{name}"
ns = findName nameSub name
if ns == root.currentNameSpace then nsLog "LOCAL NAME: #{name} FOR #{root.currentNameSpace} #{location ref}"
else if !ns then nsLog "GUESSING LOCAL NAME #{name} FOR #{root.currentNameSpace} #{location ref}"
vname
else uniqName name, uniq
genApplyArg: (arg, names, uniq)->
d = dumpAnno arg
if d instanceof Leisure_apply
@declLazy arg, => @lazify d, @genUniq arg, names, uniq
else if d instanceof Leisure_ref then @genRefName d, uniq, names
else if d instanceof Leisure_lit then sn arg, jstr getLitVal d
else if d instanceof Leisure_let
@declLazy arg, => @lazify arg, (@genUniq arg, names, uniq)
else if d instanceof Leisure_lambda then sn arg, 'lazy(', (@genUniq arg, names, uniq), ')'
else @declLazy arg, => @lazify arg, (@genUniq arg, names, uniq)
genLetAssign: (arg, names, uniq)->
@declLazy arg, => @lazify arg, (@genUniq arg, names, uniq)
lazify: (ast, body)->
lazify ast, body, (if @debug then _.last(@decls).id), @debug && @debugType
genLets: (ast, names, uniq)->
bindings = letList ast, []
[letUniq, decs, assigns, ln] = _.reduce bindings, ((result, l)=>
[u, code, assigns, ln] = result
newU = addUniq (getLetName l), ln, u
letName = uniqName (getLetName l), newU
newNames = cons (getLetName l), ln
[newU,
(cons (sn ast, letName + ' = ', @genLetAssign(getLetValue(l), newNames, u)), code),
(cons letName, assigns),
newNames]), [uniq, Nil, Nil, names]
sn ast, " var ", assigns.reverse().intersperse(', ').toArray(), ";\n ", decs.reverse().intersperse(';\n ').toArray(), ";\n\n return ", (@genUniq (getLastLetBody ast), ln, letUniq)
genTraceCall: (ast, code, argNames)->
if @debug then sn ast, """
(
Leisure_traceCall#{@debugType}(L$F, arguments),
Leisure_traceReturn#{@debugType}(L$F, (""", code, """))
)
"""
else code
genLambdaDecl: (ast, infoVar, name, args, length, code)->
if name then nameCode = jstr name
else nameCode = 'undefined'
infoVar = @addFuncInfo info = {length}
if @debug
info.id = _.last(@declStack).id
sn ast, """
(function(L$instance, L$parent){
var L$F = """, code, """;
L$F.L$info = #{infoVar};
L$F.L$instanceId = L$instance;
L$F.L$parentId = L$parent;
return Leisure_traceLambda#{@debugType}(L$F);
})(++Leisure_traceInstance, L$instance)
"""
else sn ast, """
(function(){
var L$F = """, code, """;
L$F.L$info = #{infoVar};
return L$F;
})()
"""
genAddSource: ->
if @source then "\n Leisure_addSourceFile(@fileName, #{jstr @source});"
else ''
genTraceMemos: ->
# memos for trace codes
''
genTopLevel: (ast, node)->
if dumpAnno(ast).constructor in [Leisure_lit, Leisure_ref] then node
else if @decls.length || @debug
header = "var L$ret;"
if @createContext then header += @genContext()
sn ast, """
(function(L$instance){
#{header}
return """, node, """;
})(++Leisure_traceInstance)
"""
else sn ast, """
(function(){
var L$context = null;
#{@genFuncInfo()}
return """, node, """;
})()
"""
genContext: ->
source = if @source || @noFile then """
source: Leisure_addSourceFile(#{jstr @fileName}, #{jstr @source}),
map: '@SOURCEMAP@'
"""
else if @sourceMap then """
source: #{jstr @fileName},
map: '@SOURCEMAP@'
"""
else """
source: #{jstr @fileName}
"""
decls = []
for decl in @decls
type = if decl.lazy then 'lazy' else 'lambda'
decls.push type, decl.line, decl.col, decl.parent
if type == 'lambda' then decls.push decl.lambda, decl.args.length, decl.args...
context = """
\n var L$context = Leisure_traceTopLevel#{@debugType}({
id: Leisure_traceContext++,
traceCreatePartial: function(){return Leisure_traceCreatePartial#{@debugType};},
traceCallPartial: function(){return Leisure_traceCallPartial#{@debugType};},
debugType: #{JSON.stringify @debugType},
#{source},
decls: #{JSON.stringify decls}
});
""" + @genFuncInfo()
genFuncInfo: ->
header = ''
if @decls.length
for info, i in @funcInfo
parent = info.parent? && @decls[info.parent]
while parent && parent.lazy
parent = @decls[parent.parent]
parent = if parent?.funcId then @funcVar parent.funcId
else 'null'
header += "\n var #{@funcVar i} = {name: #{JSON.stringify info.name}, args: #{JSON.stringify info.args}, id: #{info.id}, length: #{info.length}, parent: #{parent}, context: L$context};"
else
for info, i in @funcInfo
header += """
\n var #{@funcVar i} = {name: #{JSON.stringify info.name}, length: #{info.length}};
"""
header
lazify = (ast, body, id, debugType)->
if debugType
sn ast, """
(function(L$instance, L$parent) {
return Leisure_traceLazyValue#{debugType}(L$instance, L$context, #{id}, function(){
return Leisure_traceResolve#{debugType}(L$instance, """, body, """);
});
})(++Leisure_traceInstance, L$instance)
"""
else sn ast, """
function(){
return """, body, """;
}
"""
findName = (name)->
for i in [root.nameSpacePath.length - 1 .. 0]
if LeisureNameSpaces[root.nameSpacePath[i]]?[name] then return root.nameSpacePath[i]
if root.currentNameSpace && LeisureNameSpaces[root.currentNameSpace][name] then root.currentNameSpace
else null
location = (ast)->
[line, col] = locateAst ast
"#{line}:#{col}"
getLambdaArgs = (ast)->
args = []
while ast instanceof Leisure_lambda
args.push getLambdaVar ast
ast = getLambdaBody ast
[args, ast]
getNthLambdaBody = (ast, n)->
if n == 0 then ast
else if (d = dumpAnno ast) instanceof Leisure_lambda then getNthLambdaBody getLambdaBody(d), n - 1
else throw new Error "Expected lambda but got #{ast}"
(window ? global ? {}).curryCall = curryCall = (args, func)->
f = func args[0]
for i in [1...args.length]
f = f args[i]
f
getNArgs = (n, ast)->
d = dumpAnno ast
if !n then Nil else cons (getLambdaVar d), getNArgs n - 1, getLambdaBody d
specialAnnotations = ['type', 'dataType', 'define']
arrayify = (cons)->
if cons instanceof Leisure_cons then cons.map((el)-> arrayify el).toArray()
else cons
getLambdaProperties = (body, props)->
if body instanceof Leisure_anno
if !_.includes specialAnnotations, getAnnoName(body)
if !props then props = {}
value = getAnnoData body
props[getAnnoName body] = arrayify value
getLambdaProperties getAnnoBody(body), props
props
addLambdaProperties = (ast, def, extras)->
props = getLambdaProperties getLambdaBody ast
if props || extras
p = {}
if props then _.merge p, props
if extras then _.merge p, extras
sn ast, "setLambdaProperties(", def, ", ", (jstr p), ")"
else def
lcons = (a, b)-> rz(L_cons)(lz a)(lz b)
parseErr = (a, b)-> rz(L_parseErr)(a, b)
lconsFrom = (array)->
if array instanceof Array
p = rz L_nil
for el in array.reverse()
p = lcons lconsFrom(el), p
p
else array
assocListProps = null
getAssocListProps = ->
if !assocListProps
assocListProps = lcons lcons('assoc', 'true'), rz(L_nil)
assocListProps.properties = assocListProps
assocListProps
lacons = (key, value, list)->
alist = lcons lcons(key, value), list
alist.properties = getAssocListProps()
alist
(window ? global).setLambdaProperties = (def, props)->
p = rz L_nil
for k, v of props
p = lacons k, lconsFrom(v), p
def.properties = p
def
(global ? window).L$convertError = (err, args)->
if !err.L_stack
console.log 'CONVERTING ERROR:', err
(global ? window).ERR = err
err.L_stack = args.callee.L$stack
err.L_args = args
err
dumpAnno = (ast)-> if ast instanceof Leisure_anno then dumpAnno getAnnoBody ast else ast
addUniq = (name, names, uniq)->
if (names.find (el)-> el == name) != Nil
[overrides, num] = uniq
[(cons (cons name, "#{name}_#{num}"), overrides), num + 1]
else uniq
uniqName = (name, uniq)->
[uniq] = uniq
kv = uniq.find ((el)-> el.head() == name), uniq
varNameSub (if kv != Nil then kv.tail() else name)
letList = (ast, buf)->
if ast instanceof Leisure_let
buf.push ast
letList getLetBody(ast), buf
else buf
getLastLetBody = (ast)-> if ast instanceof Leisure_let then getLastLetBody getLetBody ast else ast
define 'debugType', (lvl)->
new Monad2 'debugType', (env, cont)->
setDebugType String rz lvl
cont unit()
define 'debugMessage', (type, msg)-> checkPartial(L_vectorRemove, arguments) || (
new Monad2 'debugMessage', (env, cont)->
count = (window ? global)["Leisure_traceMessage#{rz type}"] rz msg
env.writeTraceMessage count, rz msg
cont unit())
define 'traceOff', new Monad2 'traceOff', (env, cont)->
trace = false
cont unit()
define 'traceOn', new Monad2 'traceOn', (env, cont)->
trace = true
cont unit()
define 'runAst', ((code)->(ast)->
new Monad2 'runAst', (env, cont)->
#console.log "running code", code
jsCode = null
try
jsCode = if env.fileName then withFile env.fileName, null, =>
new CodeGenerator(env.fileName, false, true).genSource null, rz(ast)
else new CodeGenerator().genSource rz(code), rz(ast)
cont eval jsCode
catch err
dumpMonadStack err, env
codeMsg = (if jsCode then "CODE: \n#{jsCode}\n" else '')
baseMsg = "\n\nParse error: #{err.message}\n#{codeMsg}AST: "
err.message = "#{baseMsg}#{ast()}"
err.L$ast = ast
cont err), null, null, null, 'parser'
define 'genAst', ((ast)->
try
gen rz ast
catch err
parseErr (lz '\n\nParse error: ' + err.toString() + "AST: "), (ast)), null, null, null, 'parser'
#####
# TMP HOOKS
#####
#####
# END TMP HOOKS
#####
gen = (ast)-> new CodeGenerator().gen ast
genMap = (ast, fileName)->
new CodeGenerator(fileName, false, false, fileName).genMap ast
genSource = (source, ast)-> new CodeGenerator().genSource source, ast
{
gen
genMap
genSource
sourceNode: sn
withFile
curryCall
#useNameSpace: useNameSpace
#pushNameSpace: pushNameSpace
#getNameSpacePath: getNameSpacePath
#clearNameSpacePath: clearNameSpacePath
#saveNameSpace: saveNameSpace
#restoreNameSpace: restoreNameSpace
SourceNode
SourceMapConsumer
SourceMapGenerator
setMegaArity
CodeGenerator
setDebugType
jsCodeFor
}
| true | ###
Copyright (C) 2013, PI:NAME:<NAME>END_PI, Tiny Concepts: https://github.com/zot/Leisure
(licensed with ZLIB license)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
###
'use strict'
define ['./base', './ast', './runtime', 'lodash', 'lib/source-map', 'browser-source-map-support', 'lib/js-yaml'], (Base, Ast, Runtime, _, SourceMap, SourceMapSupport, Yaml)->
#SourceMapSupport?.install()
{
simpyCons
resolve
lazy
verboseMsg
nsLog
isResolved
addDebugType
getDebugType
setDebugType
} = Base
{
dump
} = Yaml
rz = resolve
lz = lazy
lc = Leisure_call
{
nameSub
getLitVal
getRefName
getLambdaVar
getLambdaBody
getApplyFunc
getApplyArg
getAnnoName
getAnnoData
getAnnoBody
getLetName
getLetValue
getLetBody
Leisure_lit
Leisure_ref
Leisure_lambda
Leisure_apply
Leisure_let
Leisure_anno
setType
setDataType
cons
Nil
define
functionInfo
getPos
isNil
getType
ast2Json
rangeToJson
getPos
} = root = Ast
{
Monad2
_true
_false
unit
left
right
booleanFor
newConsFrom
dumpMonadStack
} = Runtime
consFrom = newConsFrom
{
SourceNode
SourceMapConsumer
SourceMapGenerator
} = SourceMap
varNameSub = (n)-> "L_#{nameSub n}"
useArity = true
megaArity = false
curDef = null
#trace = false
trace = true
stackSize = 20
USE_STRICT = '"use strict";\n'
#USE_STRICT = ''
setMegaArity = (setting)-> megaArity = setting
setDebugType 'User'
#########
# Code
#########
setDebugType = (type)->
addDebugType type
Base.setDebugType type
collectArgs = (args, result)->
for i in args
if Array.isArray i then collectArgs i, result else result.push i
result
locateAst = (ast)->
[line, col] = pos = getPos(ast).toArray()
[line,col]
check = (bool, arg)->
if !bool then console.log new Error("Bad sourcemap arg: #{arg}").stack
checkChild = (child)->
if Array.isArray child
child.forEach checkChild
else check (typeof child == 'string') || (child instanceof SourceNode), child
currentFile = 'NEVERGIVENFILE.lsr'
currentFuncName = undefined
withFile = (file, name, block)->
oldFileName = currentFile
oldFuncName = currentFuncName
currentFile = file
currentFuncName = name
try
block()
finally
currentFile = oldFileName
currentFuncName = oldFuncName
sn = (ast, str...)->
[line, offset] = locateAst ast
check typeof line == 'number', 'line'
check typeof offset == 'number', 'offset'
checkChild str
if line < 1 then line = 1
if currentFile == 'NEVERGIVENFILE.lsr'
console.log new Error("SN CALLED WITHOUT FILE").stack
if currentFuncName?
new SourceNode(line, offset, currentFile, str, currentFuncName)
else new SourceNode(line, offset, currentFile, str)
jstr = (str)-> JSON.stringify str
jsCodeFor = (codeMap, mapType, externalMap)->
code = codeMap.code
if mapType == 'inline'
code = code.replace /map: '@SOURCEMAP@'/, 'inlineMap: ' + jstr codeMap.map.toJSON()
else if mapType == 'external'
code = code.replace /map: '@SOURCEMAP@'/, 'externalMap: ' + jstr externalMap
#"#{code}\n//# sourceMappingURL=data:application/json;base64,#{btoa jstr codeMap.map.toJSON()}\n"
"#{code}\n//# sourceMappingURL=data:application/json,#{jstr codeMap.map.toJSON()}\n"
functionId = 0
codeNum = 0
class CodeGenerator
constructor: (fileName, @useContext, @noFile, @suppressContextCreation, @source)->
@debugType = getDebugType()
@fileName = fileName ? "dynamic code with source #{++codeNum}"
@startId = functionId
@positions = []
@createContext = !@suppressContextCreation
@decls = []
@declStack = []
@funcInfo = []
@debug = false
contextInit: ->
if @useContext then '\n L$F.context = L_$context;'
else ''
funcVar: (index)-> "L$FUNC_#{index}"
addFuncInfo: (info)->
info.funcId = @funcInfo.length
@funcInfo.push info
@funcVar info.funcId
decl: (ast, dec)->
if @debug
dec.id = @decls.length
[line, col] = getPos(ast).toArray()
dec.line = line
dec.col = col
if @declStack.length then dec.parent = _.last(@declStack).id
@decls.push dec
@declStack.push dec
declLazy: (ast, arg)->
@decl ast, lazy: true
if arg?
result = arg()
@popDecl()
result
declLambda: (ast, name, args)->
@decl ast, dec = (lambda: name, args: args)
varName = @addFuncInfo info = {length:args.length, name, args, parent: dec.parent, id: dec.id}
dec.funcId = info.funcId
varName
popDecl: -> if @debug then @declStack.pop()
genSource: (source, ast)->
if @noFile
sm = @genNode(ast).prepend(USE_STRICT + '(').add(')').toStringWithSourceMap file: @fileName
map = JSON.parse sm.map.toString()
result = sm.code
else
funcName = if ast instanceof Leisure_anno && getAnnoName(ast) == 'leisureName'
getAnnoData ast
else null
#fileName = "dynamic code with source #{++codeNum}"
withFile @fileName, funcName, =>
try
sm = @genNode(ast).toStringWithSourceMap file: @fileName
map = JSON.parse sm.map.toString()
map.sourcesContent = [source]
result = sm.code
catch err
err.message = "Error generating code for:\n #{source.trim().replace /\n/g, '\n '}\n#{err.message}"
throw err
@endId = functionId
jsCodeFor sm, 'inline'
genNode: (ast)->
result = @genUniq ast, Nil, [Nil, 0]
@endId = functionId
@genTopLevel ast, result
genMap: (ast)->
hasFile = ast instanceof Leisure_anno && getAnnoName(ast) == 'filename'
#filename = if hasFile then getAnnoData ast else 'GENFORUNKNOWNFILE.lsr'
filename = if hasFile then getAnnoData ast else @fileName
nameAst = if hasFile then getAnnoBody ast else null
funcname = if nameAst instanceof Leisure_anno && getAnnoName(nameAst) == 'leisureName'
getAnnoData nameAst
else currentFuncName
sub = withFile filename, null, => @genNode(ast)
@endId = functionId
if !funcname then sub
else withFile filename, funcname, -> sn ast, sub
gen: (ast)->
result = @genMap(ast)
checkChild result
new SourceNode(1, 0, currentFile, ['(', result, ')']).toStringWithSourceMap(file: currentFile).code
genUniq: (ast, names, uniq)->
switch ast.constructor
when Leisure_lit then sn ast, jstr getLitVal ast
when Leisure_ref then sn ast, "resolve(", (@genRefName ast, uniq, names, true), ")"
when Leisure_lambda then @genLambda ast, names, uniq
when Leisure_apply
if useArity then @genArifiedApply ast, names, uniq
else sn ast, (@genUniq (getApplyFunc ast), names, uniq), "(", (@genApplyArg (getApplyArg ast), names, uniq), ")"
when Leisure_let then sn ast, "(function(){", (@genLets ast, names, uniq), "})()"
when Leisure_anno
name = getAnnoName ast
data = getAnnoData ast
if name == 'arity' && useArity && data > 1
@genArifiedLambda (getAnnoBody ast), names, uniq, data
else
try
switch name
when 'leisureName'
oldDef = curDef
curDef = data
when 'debug'
if Leisure_generateDebuggingCode
oldDebug = @debug
@debug = true
when 'define' then @declLazy getAnnoBody ast
genned = @genUniq (getAnnoBody ast), names, uniq
if name == 'debug' && Leisure_generateDebuggingCode then @debug = oldDebug
switch name
when 'type' then sn ast, "setType(", (genned), ", '", data, "')"
when 'dataType' then sn ast, "setDataType(", genned, ", '", data, "')"
when 'define'
[funcName, arity, src] = data.toArray()
@popDecl()
sn ast, "define('", funcName, "', ", lazify(ast, genned), ", ", arity, ", ", jstr(src), ")"
when 'leisureName' then genned
else genned
finally
if name == 'leisureName' then curDef = oldDef
else "CANNOT GENERATE CODE FOR UNKNOWN AST TYPE: #{ast}, #{ast.constructor} #{Leisure_lambda}"
genArifiedApply: (ast, names, uniq)->
args = []
func = ast
while dumpAnno(func) instanceof Leisure_apply
args.push getApplyArg dumpAnno func
func = getApplyFunc dumpAnno func
args.reverse()
defaultArity = false
if args.length > 1 && ((dmp = dumpAnno(func)) instanceof Leisure_ref) && (((info = functionInfo[funcName = getRefName dmp]) && ((info.newArity && (arity = info.arity) && arity <= args.length) || (!arity && megaArity))) || (!info && isNil names.find (el)-> el == funcName))
if defaultArity = !arity then arity = args.length
argCode = []
argCode.push ast
if defaultArity then argCode.push 'L$('
argCode.push @genUniq func, names, uniq
if defaultArity then argCode.push ')('
else argCode.push '('
for i in [0...arity]
if i > 0 then argCode.push ', '
argCode.push sn args[i], @genApplyArg args[i], names, uniq
argCode.push ')'
for i in [arity...args.length] by 1
argCode.push '(', (sn args[i], @genApplyArg args[i], names, uniq), ')'
sn argCode...
else
ast = dumpAnno ast
sn ast, (@genUniq (getApplyFunc ast), names, uniq), "(", (@genApplyArg (getApplyArg ast), names, uniq), ")"
genLambda: (ast, names, uniq)->
name = getLambdaVar ast
u = addUniq name, names, uniq
n = cons name, names
argName = (uniqName name, u)
defName = curDef
curDef = null
infoVar = @declLambda ast, defName, [name]
bodyCode = @genUniq (getLambdaBody ast), n, u
code = sn ast, "function(#{argName}){return ", @genTraceCall(ast, bodyCode, argName), ";}"
#addLambdaProperties ast, @genLambdaDecl ast, 'L$F.length', code
result = @genLambdaDecl ast, infoVar, defName, [name], 1, addLambdaProperties ast, code
@popDecl()
result
genArifiedLambda: (ast, names, uniq, arity)->
if arity < 2 then @genLambda ast, names, uniq, 0
else
args = getNArgs(arity, ast).toArray()
argList = _.map(args, ((x)-> 'L_' + x)).join ', '
defName = curDef
curDef = null
infoVar = @declLambda ast, defName, args
bodyCode = @genUniq(getNthLambdaBody(ast, arity), names, uniq)
if @debug then code = sn ast, """
function(#{argList}) {
return L_checkPartial(L$F, arguments, Leisure_traceCreatePartial#{@debugType}, Leisure_traceCallPartial#{@debugType}) || """, @genTraceCall(ast, bodyCode, argList), """;
};
"""
else code = sn ast, """
function(#{argList}) {
return L_checkPartial(L$F, arguments) || """, @genTraceCall(ast, bodyCode, argList), """;
};
"""
result = @genLambdaDecl ast, infoVar, defName, args, args.length, addLambdaProperties ast, code
annoAst = ast
while annoAst instanceof Leisure_anno
name = getAnnoName annoAst
data = getAnnoData annoAst
switch name
when 'type' then result = sn ast, "setType(", result, ", '", data, "')"
when 'dataType' then result = sn ast, "setDataType(", result, ", '", data, "')"
annoAst = getAnnoBody annoAst
@popDecl()
result
genRefName: (ref, uniq, names, checkMacro)->
name = getRefName ref
if isNil (val = names.find (el)-> el == name)
vname = varNameSub name
if !(window ? global)[vname] && Leisure.stateValues.macroDefs?.map.has name
throw new Error "Attempt to use a macro as a value: #{name}"
ns = findName nameSub name
if ns == root.currentNameSpace then nsLog "LOCAL NAME: #{name} FOR #{root.currentNameSpace} #{location ref}"
else if !ns then nsLog "GUESSING LOCAL NAME #{name} FOR #{root.currentNameSpace} #{location ref}"
vname
else uniqName name, uniq
genApplyArg: (arg, names, uniq)->
d = dumpAnno arg
if d instanceof Leisure_apply
@declLazy arg, => @lazify d, @genUniq arg, names, uniq
else if d instanceof Leisure_ref then @genRefName d, uniq, names
else if d instanceof Leisure_lit then sn arg, jstr getLitVal d
else if d instanceof Leisure_let
@declLazy arg, => @lazify arg, (@genUniq arg, names, uniq)
else if d instanceof Leisure_lambda then sn arg, 'lazy(', (@genUniq arg, names, uniq), ')'
else @declLazy arg, => @lazify arg, (@genUniq arg, names, uniq)
genLetAssign: (arg, names, uniq)->
@declLazy arg, => @lazify arg, (@genUniq arg, names, uniq)
lazify: (ast, body)->
lazify ast, body, (if @debug then _.last(@decls).id), @debug && @debugType
genLets: (ast, names, uniq)->
bindings = letList ast, []
[letUniq, decs, assigns, ln] = _.reduce bindings, ((result, l)=>
[u, code, assigns, ln] = result
newU = addUniq (getLetName l), ln, u
letName = uniqName (getLetName l), newU
newNames = cons (getLetName l), ln
[newU,
(cons (sn ast, letName + ' = ', @genLetAssign(getLetValue(l), newNames, u)), code),
(cons letName, assigns),
newNames]), [uniq, Nil, Nil, names]
sn ast, " var ", assigns.reverse().intersperse(', ').toArray(), ";\n ", decs.reverse().intersperse(';\n ').toArray(), ";\n\n return ", (@genUniq (getLastLetBody ast), ln, letUniq)
genTraceCall: (ast, code, argNames)->
if @debug then sn ast, """
(
Leisure_traceCall#{@debugType}(L$F, arguments),
Leisure_traceReturn#{@debugType}(L$F, (""", code, """))
)
"""
else code
genLambdaDecl: (ast, infoVar, name, args, length, code)->
if name then nameCode = jstr name
else nameCode = 'undefined'
infoVar = @addFuncInfo info = {length}
if @debug
info.id = _.last(@declStack).id
sn ast, """
(function(L$instance, L$parent){
var L$F = """, code, """;
L$F.L$info = #{infoVar};
L$F.L$instanceId = L$instance;
L$F.L$parentId = L$parent;
return Leisure_traceLambda#{@debugType}(L$F);
})(++Leisure_traceInstance, L$instance)
"""
else sn ast, """
(function(){
var L$F = """, code, """;
L$F.L$info = #{infoVar};
return L$F;
})()
"""
genAddSource: ->
if @source then "\n Leisure_addSourceFile(@fileName, #{jstr @source});"
else ''
genTraceMemos: ->
# memos for trace codes
''
genTopLevel: (ast, node)->
if dumpAnno(ast).constructor in [Leisure_lit, Leisure_ref] then node
else if @decls.length || @debug
header = "var L$ret;"
if @createContext then header += @genContext()
sn ast, """
(function(L$instance){
#{header}
return """, node, """;
})(++Leisure_traceInstance)
"""
else sn ast, """
(function(){
var L$context = null;
#{@genFuncInfo()}
return """, node, """;
})()
"""
genContext: ->
source = if @source || @noFile then """
source: Leisure_addSourceFile(#{jstr @fileName}, #{jstr @source}),
map: '@SOURCEMAP@'
"""
else if @sourceMap then """
source: #{jstr @fileName},
map: '@SOURCEMAP@'
"""
else """
source: #{jstr @fileName}
"""
decls = []
for decl in @decls
type = if decl.lazy then 'lazy' else 'lambda'
decls.push type, decl.line, decl.col, decl.parent
if type == 'lambda' then decls.push decl.lambda, decl.args.length, decl.args...
context = """
\n var L$context = Leisure_traceTopLevel#{@debugType}({
id: Leisure_traceContext++,
traceCreatePartial: function(){return Leisure_traceCreatePartial#{@debugType};},
traceCallPartial: function(){return Leisure_traceCallPartial#{@debugType};},
debugType: #{JSON.stringify @debugType},
#{source},
decls: #{JSON.stringify decls}
});
""" + @genFuncInfo()
genFuncInfo: ->
header = ''
if @decls.length
for info, i in @funcInfo
parent = info.parent? && @decls[info.parent]
while parent && parent.lazy
parent = @decls[parent.parent]
parent = if parent?.funcId then @funcVar parent.funcId
else 'null'
header += "\n var #{@funcVar i} = {name: #{JSON.stringify info.name}, args: #{JSON.stringify info.args}, id: #{info.id}, length: #{info.length}, parent: #{parent}, context: L$context};"
else
for info, i in @funcInfo
header += """
\n var #{@funcVar i} = {name: #{JSON.stringify info.name}, length: #{info.length}};
"""
header
lazify = (ast, body, id, debugType)->
if debugType
sn ast, """
(function(L$instance, L$parent) {
return Leisure_traceLazyValue#{debugType}(L$instance, L$context, #{id}, function(){
return Leisure_traceResolve#{debugType}(L$instance, """, body, """);
});
})(++Leisure_traceInstance, L$instance)
"""
else sn ast, """
function(){
return """, body, """;
}
"""
findName = (name)->
for i in [root.nameSpacePath.length - 1 .. 0]
if LeisureNameSpaces[root.nameSpacePath[i]]?[name] then return root.nameSpacePath[i]
if root.currentNameSpace && LeisureNameSpaces[root.currentNameSpace][name] then root.currentNameSpace
else null
location = (ast)->
[line, col] = locateAst ast
"#{line}:#{col}"
getLambdaArgs = (ast)->
args = []
while ast instanceof Leisure_lambda
args.push getLambdaVar ast
ast = getLambdaBody ast
[args, ast]
getNthLambdaBody = (ast, n)->
if n == 0 then ast
else if (d = dumpAnno ast) instanceof Leisure_lambda then getNthLambdaBody getLambdaBody(d), n - 1
else throw new Error "Expected lambda but got #{ast}"
(window ? global ? {}).curryCall = curryCall = (args, func)->
f = func args[0]
for i in [1...args.length]
f = f args[i]
f
getNArgs = (n, ast)->
d = dumpAnno ast
if !n then Nil else cons (getLambdaVar d), getNArgs n - 1, getLambdaBody d
specialAnnotations = ['type', 'dataType', 'define']
arrayify = (cons)->
if cons instanceof Leisure_cons then cons.map((el)-> arrayify el).toArray()
else cons
getLambdaProperties = (body, props)->
if body instanceof Leisure_anno
if !_.includes specialAnnotations, getAnnoName(body)
if !props then props = {}
value = getAnnoData body
props[getAnnoName body] = arrayify value
getLambdaProperties getAnnoBody(body), props
props
addLambdaProperties = (ast, def, extras)->
props = getLambdaProperties getLambdaBody ast
if props || extras
p = {}
if props then _.merge p, props
if extras then _.merge p, extras
sn ast, "setLambdaProperties(", def, ", ", (jstr p), ")"
else def
lcons = (a, b)-> rz(L_cons)(lz a)(lz b)
parseErr = (a, b)-> rz(L_parseErr)(a, b)
lconsFrom = (array)->
if array instanceof Array
p = rz L_nil
for el in array.reverse()
p = lcons lconsFrom(el), p
p
else array
assocListProps = null
getAssocListProps = ->
if !assocListProps
assocListProps = lcons lcons('assoc', 'true'), rz(L_nil)
assocListProps.properties = assocListProps
assocListProps
lacons = (key, value, list)->
alist = lcons lcons(key, value), list
alist.properties = getAssocListProps()
alist
(window ? global).setLambdaProperties = (def, props)->
p = rz L_nil
for k, v of props
p = lacons k, lconsFrom(v), p
def.properties = p
def
(global ? window).L$convertError = (err, args)->
if !err.L_stack
console.log 'CONVERTING ERROR:', err
(global ? window).ERR = err
err.L_stack = args.callee.L$stack
err.L_args = args
err
dumpAnno = (ast)-> if ast instanceof Leisure_anno then dumpAnno getAnnoBody ast else ast
addUniq = (name, names, uniq)->
if (names.find (el)-> el == name) != Nil
[overrides, num] = uniq
[(cons (cons name, "#{name}_#{num}"), overrides), num + 1]
else uniq
uniqName = (name, uniq)->
[uniq] = uniq
kv = uniq.find ((el)-> el.head() == name), uniq
varNameSub (if kv != Nil then kv.tail() else name)
letList = (ast, buf)->
if ast instanceof Leisure_let
buf.push ast
letList getLetBody(ast), buf
else buf
getLastLetBody = (ast)-> if ast instanceof Leisure_let then getLastLetBody getLetBody ast else ast
define 'debugType', (lvl)->
new Monad2 'debugType', (env, cont)->
setDebugType String rz lvl
cont unit()
define 'debugMessage', (type, msg)-> checkPartial(L_vectorRemove, arguments) || (
new Monad2 'debugMessage', (env, cont)->
count = (window ? global)["Leisure_traceMessage#{rz type}"] rz msg
env.writeTraceMessage count, rz msg
cont unit())
define 'traceOff', new Monad2 'traceOff', (env, cont)->
trace = false
cont unit()
define 'traceOn', new Monad2 'traceOn', (env, cont)->
trace = true
cont unit()
define 'runAst', ((code)->(ast)->
new Monad2 'runAst', (env, cont)->
#console.log "running code", code
jsCode = null
try
jsCode = if env.fileName then withFile env.fileName, null, =>
new CodeGenerator(env.fileName, false, true).genSource null, rz(ast)
else new CodeGenerator().genSource rz(code), rz(ast)
cont eval jsCode
catch err
dumpMonadStack err, env
codeMsg = (if jsCode then "CODE: \n#{jsCode}\n" else '')
baseMsg = "\n\nParse error: #{err.message}\n#{codeMsg}AST: "
err.message = "#{baseMsg}#{ast()}"
err.L$ast = ast
cont err), null, null, null, 'parser'
define 'genAst', ((ast)->
try
gen rz ast
catch err
parseErr (lz '\n\nParse error: ' + err.toString() + "AST: "), (ast)), null, null, null, 'parser'
#####
# TMP HOOKS
#####
#####
# END TMP HOOKS
#####
gen = (ast)-> new CodeGenerator().gen ast
genMap = (ast, fileName)->
new CodeGenerator(fileName, false, false, fileName).genMap ast
genSource = (source, ast)-> new CodeGenerator().genSource source, ast
{
gen
genMap
genSource
sourceNode: sn
withFile
curryCall
#useNameSpace: useNameSpace
#pushNameSpace: pushNameSpace
#getNameSpacePath: getNameSpacePath
#clearNameSpacePath: clearNameSpacePath
#saveNameSpace: saveNameSpace
#restoreNameSpace: restoreNameSpace
SourceNode
SourceMapConsumer
SourceMapGenerator
setMegaArity
CodeGenerator
setDebugType
jsCodeFor
}
|
[
{
"context": "]\n tasks.push ->\n parameters =\n field1: \"Javi\"\n field2: \"@soyjavi\"\n extra : true\n ",
"end": 141,
"score": 0.9997605681419373,
"start": 137,
"tag": "NAME",
"value": "Javi"
},
{
"context": " parameters =\n field1: \"Javi\"\n fie... | test/form.coffee | soyjavi/zen | 1 | "use strict"
Test = require("zenrequest").Test
module.exports = ->
tasks = []
tasks.push ->
parameters =
field1: "Javi"
field2: "@soyjavi"
extra : true
Test "POST", "form", parameters, null, "Send parameters via POST"
tasks
# Private methods
_appnima = (method, status) -> ->
parameters =
method : method
mail : "javi.jimenez.villar@gmail.com"
password: "password"
Test "GET", "appnima", parameters, null, "Request #{method } to Appnima", status
| 117391 | "use strict"
Test = require("zenrequest").Test
module.exports = ->
tasks = []
tasks.push ->
parameters =
field1: "<NAME>"
field2: "@soyjavi"
extra : true
Test "POST", "form", parameters, null, "Send parameters via POST"
tasks
# Private methods
_appnima = (method, status) -> ->
parameters =
method : method
mail : "<EMAIL>"
password: "<PASSWORD>"
Test "GET", "appnima", parameters, null, "Request #{method } to Appnima", status
| true | "use strict"
Test = require("zenrequest").Test
module.exports = ->
tasks = []
tasks.push ->
parameters =
field1: "PI:NAME:<NAME>END_PI"
field2: "@soyjavi"
extra : true
Test "POST", "form", parameters, null, "Send parameters via POST"
tasks
# Private methods
_appnima = (method, status) -> ->
parameters =
method : method
mail : "PI:EMAIL:<EMAIL>END_PI"
password: "PI:PASSWORD:<PASSWORD>END_PI"
Test "GET", "appnima", parameters, null, "Request #{method } to Appnima", status
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9950098395347595,
"start": 12,
"tag": "NAME",
"value": "Joyent"
},
{
"context": "IT_CODE\n return\n\n server.listen common.PORT, \"127.0.0.1\"\nelse if cluster.isMaster\n ... | test/simple/test-cluster-worker-exit.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.
# test-cluster-worker-exit.js
# verifies that, when a child process exits (by calling `process.exit(code)`)
# - the parent receives the proper events in the proper order, no duplicates
# - the exitCode and signalCode are correct in the 'exit' event
# - the worker.suicide flag, and worker.state are correct
# - the worker process actually goes away
# start worker
# the worker is up and running...
# Check cluster events
# Check worker events and properties
# Check that the worker died
# some helper functions ...
checkResults = (expected_results, results) ->
for k of expected_results
actual = results[k]
expected = expected_results[k]
if typeof expected is "function"
expected r[k]
else
msg = (expected[1] or "") + (" [expected: " + expected[0] + " / actual: " + actual + "]")
if expected and expected.length
assert.equal actual, expected[0], msg
else
assert.equal actual, expected, msg
return
alive = (pid) ->
try
process.kill pid, "SIGCONT"
return true
catch e
return false
return
common = require("../common")
assert = require("assert")
cluster = require("cluster")
EXIT_CODE = 42
if cluster.isWorker
http = require("http")
server = http.Server(->
)
server.once "listening", ->
process.exit EXIT_CODE
return
server.listen common.PORT, "127.0.0.1"
else if cluster.isMaster
expected_results =
cluster_emitDisconnect: [
1
"the cluster did not emit 'disconnect'"
]
cluster_emitExit: [
1
"the cluster did not emit 'exit'"
]
cluster_exitCode: [
EXIT_CODE
"the cluster exited w/ incorrect exitCode"
]
cluster_signalCode: [
null
"the cluster exited w/ incorrect signalCode"
]
worker_emitDisconnect: [
1
"the worker did not emit 'disconnect'"
]
worker_emitExit: [
1
"the worker did not emit 'exit'"
]
worker_state: [
"disconnected"
"the worker state is incorrect"
]
worker_suicideMode: [
false
"the worker.suicide flag is incorrect"
]
worker_died: [
true
"the worker is still running"
]
worker_exitCode: [
EXIT_CODE
"the worker exited w/ incorrect exitCode"
]
worker_signalCode: [
null
"the worker exited w/ incorrect signalCode"
]
results =
cluster_emitDisconnect: 0
cluster_emitExit: 0
worker_emitDisconnect: 0
worker_emitExit: 0
worker = cluster.fork()
worker.once "listening", ->
cluster.on "disconnect", ->
results.cluster_emitDisconnect += 1
return
cluster.on "exit", (worker) ->
results.cluster_exitCode = worker.process.exitCode
results.cluster_signalCode = worker.process.signalCode
results.cluster_emitExit += 1
assert.ok results.cluster_emitDisconnect, "cluster: 'exit' event before 'disconnect' event"
return
worker.on "disconnect", ->
results.worker_emitDisconnect += 1
results.worker_suicideMode = worker.suicide
results.worker_state = worker.state
return
worker.once "exit", (exitCode, signalCode) ->
results.worker_exitCode = exitCode
results.worker_signalCode = signalCode
results.worker_emitExit += 1
results.worker_died = not alive(worker.process.pid)
assert.ok results.worker_emitDisconnect, "worker: 'exit' event before 'disconnect' event"
process.nextTick ->
finish_test()
return
return
finish_test = ->
try
checkResults expected_results, results
catch exc
console.error "FAIL: " + exc.message
console.trace exc unless exc.name is "AssertionError"
process.exit 1
return
process.exit 0
return
| 84797 | # 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.
# test-cluster-worker-exit.js
# verifies that, when a child process exits (by calling `process.exit(code)`)
# - the parent receives the proper events in the proper order, no duplicates
# - the exitCode and signalCode are correct in the 'exit' event
# - the worker.suicide flag, and worker.state are correct
# - the worker process actually goes away
# start worker
# the worker is up and running...
# Check cluster events
# Check worker events and properties
# Check that the worker died
# some helper functions ...
checkResults = (expected_results, results) ->
for k of expected_results
actual = results[k]
expected = expected_results[k]
if typeof expected is "function"
expected r[k]
else
msg = (expected[1] or "") + (" [expected: " + expected[0] + " / actual: " + actual + "]")
if expected and expected.length
assert.equal actual, expected[0], msg
else
assert.equal actual, expected, msg
return
alive = (pid) ->
try
process.kill pid, "SIGCONT"
return true
catch e
return false
return
common = require("../common")
assert = require("assert")
cluster = require("cluster")
EXIT_CODE = 42
if cluster.isWorker
http = require("http")
server = http.Server(->
)
server.once "listening", ->
process.exit EXIT_CODE
return
server.listen common.PORT, "127.0.0.1"
else if cluster.isMaster
expected_results =
cluster_emitDisconnect: [
1
"the cluster did not emit 'disconnect'"
]
cluster_emitExit: [
1
"the cluster did not emit 'exit'"
]
cluster_exitCode: [
EXIT_CODE
"the cluster exited w/ incorrect exitCode"
]
cluster_signalCode: [
null
"the cluster exited w/ incorrect signalCode"
]
worker_emitDisconnect: [
1
"the worker did not emit 'disconnect'"
]
worker_emitExit: [
1
"the worker did not emit 'exit'"
]
worker_state: [
"disconnected"
"the worker state is incorrect"
]
worker_suicideMode: [
false
"the worker.suicide flag is incorrect"
]
worker_died: [
true
"the worker is still running"
]
worker_exitCode: [
EXIT_CODE
"the worker exited w/ incorrect exitCode"
]
worker_signalCode: [
null
"the worker exited w/ incorrect signalCode"
]
results =
cluster_emitDisconnect: 0
cluster_emitExit: 0
worker_emitDisconnect: 0
worker_emitExit: 0
worker = cluster.fork()
worker.once "listening", ->
cluster.on "disconnect", ->
results.cluster_emitDisconnect += 1
return
cluster.on "exit", (worker) ->
results.cluster_exitCode = worker.process.exitCode
results.cluster_signalCode = worker.process.signalCode
results.cluster_emitExit += 1
assert.ok results.cluster_emitDisconnect, "cluster: 'exit' event before 'disconnect' event"
return
worker.on "disconnect", ->
results.worker_emitDisconnect += 1
results.worker_suicideMode = worker.suicide
results.worker_state = worker.state
return
worker.once "exit", (exitCode, signalCode) ->
results.worker_exitCode = exitCode
results.worker_signalCode = signalCode
results.worker_emitExit += 1
results.worker_died = not alive(worker.process.pid)
assert.ok results.worker_emitDisconnect, "worker: 'exit' event before 'disconnect' event"
process.nextTick ->
finish_test()
return
return
finish_test = ->
try
checkResults expected_results, results
catch exc
console.error "FAIL: " + exc.message
console.trace exc unless exc.name is "AssertionError"
process.exit 1
return
process.exit 0
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.
# test-cluster-worker-exit.js
# verifies that, when a child process exits (by calling `process.exit(code)`)
# - the parent receives the proper events in the proper order, no duplicates
# - the exitCode and signalCode are correct in the 'exit' event
# - the worker.suicide flag, and worker.state are correct
# - the worker process actually goes away
# start worker
# the worker is up and running...
# Check cluster events
# Check worker events and properties
# Check that the worker died
# some helper functions ...
checkResults = (expected_results, results) ->
for k of expected_results
actual = results[k]
expected = expected_results[k]
if typeof expected is "function"
expected r[k]
else
msg = (expected[1] or "") + (" [expected: " + expected[0] + " / actual: " + actual + "]")
if expected and expected.length
assert.equal actual, expected[0], msg
else
assert.equal actual, expected, msg
return
alive = (pid) ->
try
process.kill pid, "SIGCONT"
return true
catch e
return false
return
common = require("../common")
assert = require("assert")
cluster = require("cluster")
EXIT_CODE = 42
if cluster.isWorker
http = require("http")
server = http.Server(->
)
server.once "listening", ->
process.exit EXIT_CODE
return
server.listen common.PORT, "127.0.0.1"
else if cluster.isMaster
expected_results =
cluster_emitDisconnect: [
1
"the cluster did not emit 'disconnect'"
]
cluster_emitExit: [
1
"the cluster did not emit 'exit'"
]
cluster_exitCode: [
EXIT_CODE
"the cluster exited w/ incorrect exitCode"
]
cluster_signalCode: [
null
"the cluster exited w/ incorrect signalCode"
]
worker_emitDisconnect: [
1
"the worker did not emit 'disconnect'"
]
worker_emitExit: [
1
"the worker did not emit 'exit'"
]
worker_state: [
"disconnected"
"the worker state is incorrect"
]
worker_suicideMode: [
false
"the worker.suicide flag is incorrect"
]
worker_died: [
true
"the worker is still running"
]
worker_exitCode: [
EXIT_CODE
"the worker exited w/ incorrect exitCode"
]
worker_signalCode: [
null
"the worker exited w/ incorrect signalCode"
]
results =
cluster_emitDisconnect: 0
cluster_emitExit: 0
worker_emitDisconnect: 0
worker_emitExit: 0
worker = cluster.fork()
worker.once "listening", ->
cluster.on "disconnect", ->
results.cluster_emitDisconnect += 1
return
cluster.on "exit", (worker) ->
results.cluster_exitCode = worker.process.exitCode
results.cluster_signalCode = worker.process.signalCode
results.cluster_emitExit += 1
assert.ok results.cluster_emitDisconnect, "cluster: 'exit' event before 'disconnect' event"
return
worker.on "disconnect", ->
results.worker_emitDisconnect += 1
results.worker_suicideMode = worker.suicide
results.worker_state = worker.state
return
worker.once "exit", (exitCode, signalCode) ->
results.worker_exitCode = exitCode
results.worker_signalCode = signalCode
results.worker_emitExit += 1
results.worker_died = not alive(worker.process.pid)
assert.ok results.worker_emitDisconnect, "worker: 'exit' event before 'disconnect' event"
process.nextTick ->
finish_test()
return
return
finish_test = ->
try
checkResults expected_results, results
catch exc
console.error "FAIL: " + exc.message
console.trace exc unless exc.name is "AssertionError"
process.exit 1
return
process.exit 0
return
|
[
{
"context": "# $('form').serializeObject()\n# => {name:'Craig', hobby:'Pro Pogo'}\n\n$.fn.serializeObject = ->\n ",
"end": 47,
"score": 0.9998032450675964,
"start": 42,
"tag": "NAME",
"value": "Craig"
}
] | lib/generators/backbone_generator/setup_generator/templates/app/assets/javascripts/shared/utils/serialize_object.coffee | chip-miller/rails-backbone-generator | 1 | # $('form').serializeObject()
# => {name:'Craig', hobby:'Pro Pogo'}
$.fn.serializeObject = ->
o = {}
a = @serializeArray()
$.each a, ->
if o[@name] isnt `undefined`
o[@name] = [o[@name]] unless o[@name].push
o[@name].push @value or ""
else
o[@name] = @value or ""
o | 81796 | # $('form').serializeObject()
# => {name:'<NAME>', hobby:'Pro Pogo'}
$.fn.serializeObject = ->
o = {}
a = @serializeArray()
$.each a, ->
if o[@name] isnt `undefined`
o[@name] = [o[@name]] unless o[@name].push
o[@name].push @value or ""
else
o[@name] = @value or ""
o | true | # $('form').serializeObject()
# => {name:'PI:NAME:<NAME>END_PI', hobby:'Pro Pogo'}
$.fn.serializeObject = ->
o = {}
a = @serializeArray()
$.each a, ->
if o[@name] isnt `undefined`
o[@name] = [o[@name]] unless o[@name].push
o[@name].push @value or ""
else
o[@name] = @value or ""
o |
[
{
"context": "y(\n usernameField: \"email\"\n passwordField: \"password\"\n , (email, password, done) ->\n User.findOne\n",
"end": 472,
"score": 0.9992923736572266,
"start": 464,
"tag": "PASSWORD",
"value": "password"
}
] | config/passport.coffee | gertu/gertu | 1 | mongoose = require("mongoose")
LocalStrategy = require("passport-local").Strategy
User = mongoose.model("User")
config = require("./config")
module.exports = (passport) ->
passport.serializeUser (user, done) ->
done null, user.id
passport.deserializeUser (email, done) ->
User.findOne
_id: email, (error, user) ->
done error, user
passport.use new LocalStrategy(
usernameField: "email"
passwordField: "password"
, (email, password, done) ->
User.findOne
email: email, (error, user) ->
return done(error) if error
unless user
return done(null, false, message: "Unknown user")
unless user.authenticate(password)
return done(null, false, message: "Invalid password")
done null, user
) | 42462 | mongoose = require("mongoose")
LocalStrategy = require("passport-local").Strategy
User = mongoose.model("User")
config = require("./config")
module.exports = (passport) ->
passport.serializeUser (user, done) ->
done null, user.id
passport.deserializeUser (email, done) ->
User.findOne
_id: email, (error, user) ->
done error, user
passport.use new LocalStrategy(
usernameField: "email"
passwordField: "<PASSWORD>"
, (email, password, done) ->
User.findOne
email: email, (error, user) ->
return done(error) if error
unless user
return done(null, false, message: "Unknown user")
unless user.authenticate(password)
return done(null, false, message: "Invalid password")
done null, user
) | true | mongoose = require("mongoose")
LocalStrategy = require("passport-local").Strategy
User = mongoose.model("User")
config = require("./config")
module.exports = (passport) ->
passport.serializeUser (user, done) ->
done null, user.id
passport.deserializeUser (email, done) ->
User.findOne
_id: email, (error, user) ->
done error, user
passport.use new LocalStrategy(
usernameField: "email"
passwordField: "PI:PASSWORD:<PASSWORD>END_PI"
, (email, password, done) ->
User.findOne
email: email, (error, user) ->
return done(error) if error
unless user
return done(null, false, message: "Unknown user")
unless user.authenticate(password)
return done(null, false, message: "Invalid password")
done null, user
) |
[
{
"context": "\t\t\tgauge:->\n\n\t\t@callback = sinon.stub()\n\t\t@key = \"lock:web:lockName:project-id}\"\n\t\t@namespace = 'lockName'\n\n\tdescribe \"when the lo",
"end": 588,
"score": 0.9962335824966431,
"start": 558,
"tag": "KEY",
"value": "lock:web:lockName:project-id}\""
}
] | test/unit/coffee/infrastructure/LockManager/getLockTests.coffee | shyoshyo/web-sharelatex | 1 | sinon = require('sinon')
chai = require('chai')
should = chai.should()
path = require('path')
modulePath = path.join __dirname, '../../../../../app/js/infrastructure/LockManager.js'
SandboxedModule = require('sandboxed-module')
describe 'LockManager - getting the lock', ->
beforeEach ->
@LockManager = SandboxedModule.require modulePath, requires:
"logger-sharelatex": log:->
"./RedisWrapper":
client: ()->
auth:->
"settings-sharelatex":{redis:{}}
"metrics-sharelatex":
inc:->
gauge:->
@callback = sinon.stub()
@key = "lock:web:lockName:project-id}"
@namespace = 'lockName'
describe "when the lock is not set", ->
beforeEach (done) ->
@LockManager._tryLock = sinon.stub().yields(null, true)
@LockManager._getLock @key, @namespace, (args...) =>
@callback(args...)
done()
it "should try to get the lock", ->
@LockManager._tryLock
.calledWith(@key, @namespace)
.should.equal true
it "should only need to try once", ->
@LockManager._tryLock.callCount.should.equal 1
it "should return the callback", ->
@callback.calledWith(null).should.equal true
describe "when the lock is initially set", ->
beforeEach (done) ->
startTime = Date.now()
tries = 0
@LockManager.LOCK_TEST_INTERVAL = 5
@LockManager._tryLock = (key, namespace, callback = (error, isFree) ->) ->
if (Date.now() - startTime < 20) or (tries < 2)
tries = tries + 1
callback null, false
else
callback null, true
sinon.spy @LockManager, "_tryLock"
@LockManager._getLock @key, @namespace, (args...) =>
@callback(args...)
done()
it "should call tryLock multiple times until free", ->
(@LockManager._tryLock.callCount > 1).should.equal true
it "should return the callback", ->
@callback.calledWith(null).should.equal true
describe "when the lock times out", ->
beforeEach (done) ->
time = Date.now()
@LockManager.MAX_LOCK_WAIT_TIME = 5
@LockManager._tryLock = sinon.stub().yields(null, false)
@LockManager._getLock @key, @namespace, (args...) =>
@callback(args...)
done()
it "should return the callback with an error", ->
@callback.calledWith(new Error("timeout")).should.equal true
describe "when there are multiple requests for the same lock", ->
beforeEach (done) ->
locked = false
@results = []
@LockManager.LOCK_TEST_INTERVAL = 1
@LockManager._tryLock = (key, namespace, callback = (error, gotLock, lockValue) ->) ->
if locked
callback null, false
else
locked = true # simulate getting the lock
callback null, true
# Start ten lock requests in order at 1ms 2ms 3ms...
# with them randomly holding the lock for 0-100ms.
# Use predefined values for the random delay to make the test
# deterministic.
randomDelays = [52, 45, 41, 84, 60, 81, 31, 46, 9, 43 ]
startTime = 0
for randomDelay, i in randomDelays
do (randomDelay, i) =>
startTime += 1
setTimeout () =>
# changing the next line to the old method of LockManager._getLockByPolling
# should give results in a random order and cause the test to fail.
@LockManager._getLock @key, @namespace, (args...) =>
setTimeout () ->
locked = false # release the lock after a random amount of time
, randomDelay
@results.push i
if @results.length is 10
done()
, startTime
it "should process the requests in order", ->
@results.should.deep.equal [0,1,2,3,4,5,6,7,8,9]
| 76489 | sinon = require('sinon')
chai = require('chai')
should = chai.should()
path = require('path')
modulePath = path.join __dirname, '../../../../../app/js/infrastructure/LockManager.js'
SandboxedModule = require('sandboxed-module')
describe 'LockManager - getting the lock', ->
beforeEach ->
@LockManager = SandboxedModule.require modulePath, requires:
"logger-sharelatex": log:->
"./RedisWrapper":
client: ()->
auth:->
"settings-sharelatex":{redis:{}}
"metrics-sharelatex":
inc:->
gauge:->
@callback = sinon.stub()
@key = "<KEY>
@namespace = 'lockName'
describe "when the lock is not set", ->
beforeEach (done) ->
@LockManager._tryLock = sinon.stub().yields(null, true)
@LockManager._getLock @key, @namespace, (args...) =>
@callback(args...)
done()
it "should try to get the lock", ->
@LockManager._tryLock
.calledWith(@key, @namespace)
.should.equal true
it "should only need to try once", ->
@LockManager._tryLock.callCount.should.equal 1
it "should return the callback", ->
@callback.calledWith(null).should.equal true
describe "when the lock is initially set", ->
beforeEach (done) ->
startTime = Date.now()
tries = 0
@LockManager.LOCK_TEST_INTERVAL = 5
@LockManager._tryLock = (key, namespace, callback = (error, isFree) ->) ->
if (Date.now() - startTime < 20) or (tries < 2)
tries = tries + 1
callback null, false
else
callback null, true
sinon.spy @LockManager, "_tryLock"
@LockManager._getLock @key, @namespace, (args...) =>
@callback(args...)
done()
it "should call tryLock multiple times until free", ->
(@LockManager._tryLock.callCount > 1).should.equal true
it "should return the callback", ->
@callback.calledWith(null).should.equal true
describe "when the lock times out", ->
beforeEach (done) ->
time = Date.now()
@LockManager.MAX_LOCK_WAIT_TIME = 5
@LockManager._tryLock = sinon.stub().yields(null, false)
@LockManager._getLock @key, @namespace, (args...) =>
@callback(args...)
done()
it "should return the callback with an error", ->
@callback.calledWith(new Error("timeout")).should.equal true
describe "when there are multiple requests for the same lock", ->
beforeEach (done) ->
locked = false
@results = []
@LockManager.LOCK_TEST_INTERVAL = 1
@LockManager._tryLock = (key, namespace, callback = (error, gotLock, lockValue) ->) ->
if locked
callback null, false
else
locked = true # simulate getting the lock
callback null, true
# Start ten lock requests in order at 1ms 2ms 3ms...
# with them randomly holding the lock for 0-100ms.
# Use predefined values for the random delay to make the test
# deterministic.
randomDelays = [52, 45, 41, 84, 60, 81, 31, 46, 9, 43 ]
startTime = 0
for randomDelay, i in randomDelays
do (randomDelay, i) =>
startTime += 1
setTimeout () =>
# changing the next line to the old method of LockManager._getLockByPolling
# should give results in a random order and cause the test to fail.
@LockManager._getLock @key, @namespace, (args...) =>
setTimeout () ->
locked = false # release the lock after a random amount of time
, randomDelay
@results.push i
if @results.length is 10
done()
, startTime
it "should process the requests in order", ->
@results.should.deep.equal [0,1,2,3,4,5,6,7,8,9]
| true | sinon = require('sinon')
chai = require('chai')
should = chai.should()
path = require('path')
modulePath = path.join __dirname, '../../../../../app/js/infrastructure/LockManager.js'
SandboxedModule = require('sandboxed-module')
describe 'LockManager - getting the lock', ->
beforeEach ->
@LockManager = SandboxedModule.require modulePath, requires:
"logger-sharelatex": log:->
"./RedisWrapper":
client: ()->
auth:->
"settings-sharelatex":{redis:{}}
"metrics-sharelatex":
inc:->
gauge:->
@callback = sinon.stub()
@key = "PI:KEY:<KEY>END_PI
@namespace = 'lockName'
describe "when the lock is not set", ->
beforeEach (done) ->
@LockManager._tryLock = sinon.stub().yields(null, true)
@LockManager._getLock @key, @namespace, (args...) =>
@callback(args...)
done()
it "should try to get the lock", ->
@LockManager._tryLock
.calledWith(@key, @namespace)
.should.equal true
it "should only need to try once", ->
@LockManager._tryLock.callCount.should.equal 1
it "should return the callback", ->
@callback.calledWith(null).should.equal true
describe "when the lock is initially set", ->
beforeEach (done) ->
startTime = Date.now()
tries = 0
@LockManager.LOCK_TEST_INTERVAL = 5
@LockManager._tryLock = (key, namespace, callback = (error, isFree) ->) ->
if (Date.now() - startTime < 20) or (tries < 2)
tries = tries + 1
callback null, false
else
callback null, true
sinon.spy @LockManager, "_tryLock"
@LockManager._getLock @key, @namespace, (args...) =>
@callback(args...)
done()
it "should call tryLock multiple times until free", ->
(@LockManager._tryLock.callCount > 1).should.equal true
it "should return the callback", ->
@callback.calledWith(null).should.equal true
describe "when the lock times out", ->
beforeEach (done) ->
time = Date.now()
@LockManager.MAX_LOCK_WAIT_TIME = 5
@LockManager._tryLock = sinon.stub().yields(null, false)
@LockManager._getLock @key, @namespace, (args...) =>
@callback(args...)
done()
it "should return the callback with an error", ->
@callback.calledWith(new Error("timeout")).should.equal true
describe "when there are multiple requests for the same lock", ->
beforeEach (done) ->
locked = false
@results = []
@LockManager.LOCK_TEST_INTERVAL = 1
@LockManager._tryLock = (key, namespace, callback = (error, gotLock, lockValue) ->) ->
if locked
callback null, false
else
locked = true # simulate getting the lock
callback null, true
# Start ten lock requests in order at 1ms 2ms 3ms...
# with them randomly holding the lock for 0-100ms.
# Use predefined values for the random delay to make the test
# deterministic.
randomDelays = [52, 45, 41, 84, 60, 81, 31, 46, 9, 43 ]
startTime = 0
for randomDelay, i in randomDelays
do (randomDelay, i) =>
startTime += 1
setTimeout () =>
# changing the next line to the old method of LockManager._getLockByPolling
# should give results in a random order and cause the test to fail.
@LockManager._getLock @key, @namespace, (args...) =>
setTimeout () ->
locked = false # release the lock after a random amount of time
, randomDelay
@results.push i
if @results.length is 10
done()
, startTime
it "should process the requests in order", ->
@results.should.deep.equal [0,1,2,3,4,5,6,7,8,9]
|
[
{
"context": "###\naboutCtrl.coffee\nCopyright (C) 2015 ender xu <xuender@gmail.com>\n\nDistributed under terms of t",
"end": 48,
"score": 0.9996992945671082,
"start": 40,
"tag": "NAME",
"value": "ender xu"
},
{
"context": "###\naboutCtrl.coffee\nCopyright (C) 2015 ender xu <xuender@... | ma/aboutCtrl.coffee | xuender/mgoAdmin | 0 | ###
aboutCtrl.coffee
Copyright (C) 2015 ender xu <xuender@gmail.com>
Distributed under terms of the MIT license.
###
AboutCtrl = ($scope, $log)->
$log.debug 'about'
AboutCtrl.$inject = [
'$scope'
'$log'
]
| 197929 | ###
aboutCtrl.coffee
Copyright (C) 2015 <NAME> <<EMAIL>>
Distributed under terms of the MIT license.
###
AboutCtrl = ($scope, $log)->
$log.debug 'about'
AboutCtrl.$inject = [
'$scope'
'$log'
]
| true | ###
aboutCtrl.coffee
Copyright (C) 2015 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
Distributed under terms of the MIT license.
###
AboutCtrl = ($scope, $log)->
$log.debug 'about'
AboutCtrl.$inject = [
'$scope'
'$log'
]
|
[
{
"context": "name: 'Default Theme'\nauthor: 'Alain Deschenes'\nfiles: [\n 'index.css'\n 'test.css'\n]\n",
"end": 46,
"score": 0.9998854398727417,
"start": 31,
"tag": "NAME",
"value": "Alain Deschenes"
}
] | user/themes/default/index.cson | kornalius/termos | 0 | name: 'Default Theme'
author: 'Alain Deschenes'
files: [
'index.css'
'test.css'
]
| 189988 | name: 'Default Theme'
author: '<NAME>'
files: [
'index.css'
'test.css'
]
| true | name: 'Default Theme'
author: 'PI:NAME:<NAME>END_PI'
files: [
'index.css'
'test.css'
]
|
[
{
"context": "e } = metric\n ws.write\n key: \"metrics:#{id}:#{timestamp}\"\n value: value\n ws.end(",
"end": 1246,
"score": 0.732399582862854,
"start": 1244,
"tag": "KEY",
"value": "#{"
},
{
"context": " metric\n ws.write\n key: \"metrics:#{id}:#{... | src/metrics.coffee | MegPau/testnode | 0 | level = require 'level'
levelws = require 'level-ws'
db = levelws level "#{__dirname}/../db"
module.exports =
# get(id, callback)
# Get metrics
# - id: metric's id, optional, if none all metrics are retrieved
# - callback: the callback function, callback(err, data)
get: (id, callback) ->
if callback == undefined
callback = id
id = null
values = []
opts = {}
if id != null then opts =
gt: "metrics:#{id}:"
lt: "metrics:#{ parseInt( id, 10 ) + 1}:"
rs = db.createReadStream(opts)
.on 'data', (data) ->
[ _, id, timestamp ] = data.key.split ":"
values.push
timestamp: timestamp
value: data.value
.on 'error', (err) ->
console.log "error"
callback err
.on 'close', () ->
console.log "closing"
callback null, values
# save(id, metrics, callback)
# Save given metrics
# - id: metric id
# - metrics: an array of { timestamp, value }
# - callback: the callback function
save: (id, metrics, callback) ->
ws = db.createWriteStream()
ws.on 'error', callback
ws.on 'close', callback
for metric in metrics
{ timestamp, value } = metric
ws.write
key: "metrics:#{id}:#{timestamp}"
value: value
ws.end()
remove: (key, callback) ->
db.del key, callback
| 218423 | level = require 'level'
levelws = require 'level-ws'
db = levelws level "#{__dirname}/../db"
module.exports =
# get(id, callback)
# Get metrics
# - id: metric's id, optional, if none all metrics are retrieved
# - callback: the callback function, callback(err, data)
get: (id, callback) ->
if callback == undefined
callback = id
id = null
values = []
opts = {}
if id != null then opts =
gt: "metrics:#{id}:"
lt: "metrics:#{ parseInt( id, 10 ) + 1}:"
rs = db.createReadStream(opts)
.on 'data', (data) ->
[ _, id, timestamp ] = data.key.split ":"
values.push
timestamp: timestamp
value: data.value
.on 'error', (err) ->
console.log "error"
callback err
.on 'close', () ->
console.log "closing"
callback null, values
# save(id, metrics, callback)
# Save given metrics
# - id: metric id
# - metrics: an array of { timestamp, value }
# - callback: the callback function
save: (id, metrics, callback) ->
ws = db.createWriteStream()
ws.on 'error', callback
ws.on 'close', callback
for metric in metrics
{ timestamp, value } = metric
ws.write
key: "metrics:<KEY>id}:<KEY>timestamp<KEY>}"
value: value
ws.end()
remove: (key, callback) ->
db.del key, callback
| true | level = require 'level'
levelws = require 'level-ws'
db = levelws level "#{__dirname}/../db"
module.exports =
# get(id, callback)
# Get metrics
# - id: metric's id, optional, if none all metrics are retrieved
# - callback: the callback function, callback(err, data)
get: (id, callback) ->
if callback == undefined
callback = id
id = null
values = []
opts = {}
if id != null then opts =
gt: "metrics:#{id}:"
lt: "metrics:#{ parseInt( id, 10 ) + 1}:"
rs = db.createReadStream(opts)
.on 'data', (data) ->
[ _, id, timestamp ] = data.key.split ":"
values.push
timestamp: timestamp
value: data.value
.on 'error', (err) ->
console.log "error"
callback err
.on 'close', () ->
console.log "closing"
callback null, values
# save(id, metrics, callback)
# Save given metrics
# - id: metric id
# - metrics: an array of { timestamp, value }
# - callback: the callback function
save: (id, metrics, callback) ->
ws = db.createWriteStream()
ws.on 'error', callback
ws.on 'close', callback
for metric in metrics
{ timestamp, value } = metric
ws.write
key: "metrics:PI:KEY:<KEY>END_PIid}:PI:KEY:<KEY>END_PItimestampPI:KEY:<KEY>END_PI}"
value: value
ws.end()
remove: (key, callback) ->
db.del key, callback
|
[
{
"context": "# Copyright (c) Konode. All rights reserved.\n# This source code is subje",
"end": 22,
"score": 0.9842329025268555,
"start": 16,
"tag": "NAME",
"value": "Konode"
}
] | src/utils/reactBootstrap.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
# Convenience method for turning
# TODO: Come up with better solution for requiring ReactBoostrap components as factories
load = (win, classNames...) ->
React = win.React
ReactBootstrap = win.ReactBootstrap
factories = {}
classNames.forEach (className) ->
unless ReactBootstrap[className]?
throw new Error "ReactBootstrap class '#{className}' is undefined"
factories[className] = React.createFactory ReactBootstrap[className]
return factories
module.exports = {load}
| 166856 | # 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
# Convenience method for turning
# TODO: Come up with better solution for requiring ReactBoostrap components as factories
load = (win, classNames...) ->
React = win.React
ReactBootstrap = win.ReactBootstrap
factories = {}
classNames.forEach (className) ->
unless ReactBootstrap[className]?
throw new Error "ReactBootstrap class '#{className}' is undefined"
factories[className] = React.createFactory ReactBootstrap[className]
return factories
module.exports = {load}
| 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
# Convenience method for turning
# TODO: Come up with better solution for requiring ReactBoostrap components as factories
load = (win, classNames...) ->
React = win.React
ReactBootstrap = win.ReactBootstrap
factories = {}
classNames.forEach (className) ->
unless ReactBootstrap[className]?
throw new Error "ReactBootstrap class '#{className}' is undefined"
factories[className] = React.createFactory ReactBootstrap[className]
return factories
module.exports = {load}
|
[
{
"context": " - <what the respond trigger does>\n#\n# Author:\n# Riccardo Magliocchetti <riccardo.magliocchetti@gmail.com>\n\n$ = require(\"",
"end": 212,
"score": 0.9998528361320496,
"start": 190,
"tag": "NAME",
"value": "Riccardo Magliocchetti"
},
{
"context": "ger does>\n#\n# A... | src/giffetteria.coffee | xrmx/hubot-giffetteria | 0 | # Description
# A hubot script to query giffetteria.it
#
# Configuration:
# LIST_OF_ENV_VARS_TO_SET
#
# Commands:
# hubot giffetteria - <what the respond trigger does>
#
# Author:
# Riccardo Magliocchetti <riccardo.magliocchetti@gmail.com>
$ = require("cheerio")
module.exports = (robot) ->
robot.hear /giffetteria (.*)/i, (res) ->
query = res.match[1]
robot.http("http://giffetteria.it/?s=" + encodeURIComponent(query))
.get() (err, r, body) ->
if err
return res.send "Epic fail!"
gifs = $('.gf-gif-link img', body)
if not gifs.length
return res.send "No gif found!"
gif = res.random gifs
src = $(gif).attr('data-gif')
res.send src
| 58464 | # Description
# A hubot script to query giffetteria.it
#
# Configuration:
# LIST_OF_ENV_VARS_TO_SET
#
# Commands:
# hubot giffetteria - <what the respond trigger does>
#
# Author:
# <NAME> <<EMAIL>>
$ = require("cheerio")
module.exports = (robot) ->
robot.hear /giffetteria (.*)/i, (res) ->
query = res.match[1]
robot.http("http://giffetteria.it/?s=" + encodeURIComponent(query))
.get() (err, r, body) ->
if err
return res.send "Epic fail!"
gifs = $('.gf-gif-link img', body)
if not gifs.length
return res.send "No gif found!"
gif = res.random gifs
src = $(gif).attr('data-gif')
res.send src
| true | # Description
# A hubot script to query giffetteria.it
#
# Configuration:
# LIST_OF_ENV_VARS_TO_SET
#
# Commands:
# hubot giffetteria - <what the respond trigger does>
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
$ = require("cheerio")
module.exports = (robot) ->
robot.hear /giffetteria (.*)/i, (res) ->
query = res.match[1]
robot.http("http://giffetteria.it/?s=" + encodeURIComponent(query))
.get() (err, r, body) ->
if err
return res.send "Epic fail!"
gifs = $('.gf-gif-link img', body)
if not gifs.length
return res.send "No gif found!"
gif = res.random gifs
src = $(gif).attr('data-gif')
res.send src
|
[
{
"context": "ikes when you yell all the time :(\n#\n# Author:\n# MattSJohnston\n\nmodule.exports = (robot) ->\n\n _ = require 'unde",
"end": 344,
"score": 0.7707864046096802,
"start": 331,
"tag": "NAME",
"value": "MattSJohnston"
}
] | src/scripts/yell.coffee | contolini/hubot-scripts | 1,450 | # Description
# Allows you to "yell" your message to everyone in the room
#
# Dependencies:
# "underscore": "1.3.3"
#
# Configuration:
# None
#
# Commands:
# hubot yell <message> - Sends your message and mentions everyone curently in the chat room.
#
# Notes:
# Nobody likes when you yell all the time :(
#
# Author:
# MattSJohnston
module.exports = (robot) ->
_ = require 'underscore'
robot.respond /yell (.*)/i, (msg) ->
users = _.reject((_.values _.pluck robot.brain.data.users, 'name'), (name) -> name == msg.message.user.name)
msg.send if users.length then users.join(', ') + ": #{msg.match[1]}" else "If a tree falls in a forest and no one is around to hear it, does it make a sound?"
toTitleCase = (str) ->
str.replace /\w\S*/g, (txt) -> txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()
| 138809 | # Description
# Allows you to "yell" your message to everyone in the room
#
# Dependencies:
# "underscore": "1.3.3"
#
# Configuration:
# None
#
# Commands:
# hubot yell <message> - Sends your message and mentions everyone curently in the chat room.
#
# Notes:
# Nobody likes when you yell all the time :(
#
# Author:
# <NAME>
module.exports = (robot) ->
_ = require 'underscore'
robot.respond /yell (.*)/i, (msg) ->
users = _.reject((_.values _.pluck robot.brain.data.users, 'name'), (name) -> name == msg.message.user.name)
msg.send if users.length then users.join(', ') + ": #{msg.match[1]}" else "If a tree falls in a forest and no one is around to hear it, does it make a sound?"
toTitleCase = (str) ->
str.replace /\w\S*/g, (txt) -> txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()
| true | # Description
# Allows you to "yell" your message to everyone in the room
#
# Dependencies:
# "underscore": "1.3.3"
#
# Configuration:
# None
#
# Commands:
# hubot yell <message> - Sends your message and mentions everyone curently in the chat room.
#
# Notes:
# Nobody likes when you yell all the time :(
#
# Author:
# PI:NAME:<NAME>END_PI
module.exports = (robot) ->
_ = require 'underscore'
robot.respond /yell (.*)/i, (msg) ->
users = _.reject((_.values _.pluck robot.brain.data.users, 'name'), (name) -> name == msg.message.user.name)
msg.send if users.length then users.join(', ') + ": #{msg.match[1]}" else "If a tree falls in a forest and no one is around to hear it, does it make a sound?"
toTitleCase = (str) ->
str.replace /\w\S*/g, (txt) -> txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9985063672065735,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-stream2-unpipe-leak.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.
TestWriter = ->
stream.Writable.call this
return
# Set this high so that we'd trigger a nextTick warning
# and/or RangeError if we do maybeReadMore wrong.
TestReader = ->
stream.Readable.call this,
highWaterMark: 0x10000
return
common = require("../common.js")
assert = require("assert")
stream = require("stream")
chunk = new Buffer("hallo")
util = require("util")
util.inherits TestWriter, stream.Writable
TestWriter::_write = (buffer, encoding, callback) ->
callback null
return
dest = new TestWriter()
util.inherits TestReader, stream.Readable
TestReader::_read = (size) ->
@push chunk
return
src = new TestReader()
i = 0
while i < 10
src.pipe dest
src.unpipe dest
i++
assert.equal src.listeners("end").length, 0
assert.equal src.listeners("readable").length, 0
assert.equal dest.listeners("unpipe").length, 0
assert.equal dest.listeners("drain").length, 0
assert.equal dest.listeners("error").length, 0
assert.equal dest.listeners("close").length, 0
assert.equal dest.listeners("finish").length, 0
console.error src._readableState
process.on "exit", ->
src._readableState.buffer.length = 0
console.error src._readableState
assert src._readableState.length >= src._readableState.highWaterMark
console.log "ok"
return
| 174520 | # 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.
TestWriter = ->
stream.Writable.call this
return
# Set this high so that we'd trigger a nextTick warning
# and/or RangeError if we do maybeReadMore wrong.
TestReader = ->
stream.Readable.call this,
highWaterMark: 0x10000
return
common = require("../common.js")
assert = require("assert")
stream = require("stream")
chunk = new Buffer("hallo")
util = require("util")
util.inherits TestWriter, stream.Writable
TestWriter::_write = (buffer, encoding, callback) ->
callback null
return
dest = new TestWriter()
util.inherits TestReader, stream.Readable
TestReader::_read = (size) ->
@push chunk
return
src = new TestReader()
i = 0
while i < 10
src.pipe dest
src.unpipe dest
i++
assert.equal src.listeners("end").length, 0
assert.equal src.listeners("readable").length, 0
assert.equal dest.listeners("unpipe").length, 0
assert.equal dest.listeners("drain").length, 0
assert.equal dest.listeners("error").length, 0
assert.equal dest.listeners("close").length, 0
assert.equal dest.listeners("finish").length, 0
console.error src._readableState
process.on "exit", ->
src._readableState.buffer.length = 0
console.error src._readableState
assert src._readableState.length >= src._readableState.highWaterMark
console.log "ok"
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.
TestWriter = ->
stream.Writable.call this
return
# Set this high so that we'd trigger a nextTick warning
# and/or RangeError if we do maybeReadMore wrong.
TestReader = ->
stream.Readable.call this,
highWaterMark: 0x10000
return
common = require("../common.js")
assert = require("assert")
stream = require("stream")
chunk = new Buffer("hallo")
util = require("util")
util.inherits TestWriter, stream.Writable
TestWriter::_write = (buffer, encoding, callback) ->
callback null
return
dest = new TestWriter()
util.inherits TestReader, stream.Readable
TestReader::_read = (size) ->
@push chunk
return
src = new TestReader()
i = 0
while i < 10
src.pipe dest
src.unpipe dest
i++
assert.equal src.listeners("end").length, 0
assert.equal src.listeners("readable").length, 0
assert.equal dest.listeners("unpipe").length, 0
assert.equal dest.listeners("drain").length, 0
assert.equal dest.listeners("error").length, 0
assert.equal dest.listeners("close").length, 0
assert.equal dest.listeners("finish").length, 0
console.error src._readableState
process.on "exit", ->
src._readableState.buffer.length = 0
console.error src._readableState
assert src._readableState.length >= src._readableState.highWaterMark
console.log "ok"
return
|
[
{
"context": "al skin and brown eyes.\n '''\n\n scientificName: 'Bucorvus leadbeateri'\n mainImage: 'assets/fieldguide-content/birds/gr",
"end": 728,
"score": 0.999875545501709,
"start": 708,
"tag": "NAME",
"value": "Bucorvus leadbeateri"
}
] | app/lib/field-guide-content/ground_hornbill.coffee | zooniverse/wildcam-gorongosa | 7 | module.exports =
label: 'Southern Ground Hornbill'
description: '''
The southern ground hornbill is the largest hornbill in the world. It is a large, black, turkeylike bird with striking red skin around its eyes and down its foreneck, forming a pouch. The female has a violet patch on the throat rather than just the pure red coloration of the male. The bill is long, thick, and downward-curving, with a small protuberance on the top. Their eyes are pale yellow and their legs and plumage are black, except for a few white wing feathers, which can only be seen when in flight. Juveniles are duller in coloration, appearing browner with yellowish facial skin and brown eyes.
'''
scientificName: 'Bucorvus leadbeateri'
mainImage: 'assets/fieldguide-content/birds/ground_hornbill/hornbill-feature.jpg'
conservationStatus: 'Vulnerable' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well.
information: [{
label: 'Length'
value: '1.05 m'
}, {
label: 'Weight'
value: '2.2-6.2 kg'
}, {
label: 'Lifespan'
value: 'Up to 70 years'
}, {
label: 'Gestation'
value: '40 days'
}, {
label: 'Avg. number of offspring'
value: '2 eggs are usually laid; only one chick will generally survive'
}]
sections: [{
title: 'Habitat'
content: 'Woodland, grassland, and savanna. '
}, {
title: 'Diet'
content: 'Arthropods, snails, frogs, toads, snakes, hares, and tortoises; also sometimes feeds on carrion, fruits, and seeds'
}, {
title: 'Predators'
content: 'Large predators, such as leopards and crocodiles'
}, {
title: 'Behavior'
content: '''
<p>The southern ground hornbills can live as single breeding pairs but are often seen in cooperative breeding groups. These groups contain between two and eight individuals, with the dominant pair assisted by adult and immature helpers to defend a territory and rear young.</p>
'''
}, {
title: 'Breeding'
content: '''
<p>Southern ground hornbills generally mate between September and December. Females will lay two eggs in a tree or cliff hollow. The first egg is generally laid three to five days before the second, and the eggs will hatch after an incubation period of about 40 days. The first chick regularly outcompetes its younger sibling, as only one chick usually survives. Chicks fledge at around 85 days old. </p>
'''
}, {
title: 'Fun Facts'
style: 'focus-box'
content: '''
<ol>
<li>The southern ground hornbill is the largest hornbill in the world.</li>
<li>The southern ground hornbill is long-lived, reaching 50 or even 60 years old.</li>
</ol>
'''
},{
title: 'Distribution'
content: '<img src="assets/fieldguide-content/birds/ground_hornbill/hornbill-map.jpg"/>'
}]
| 160700 | module.exports =
label: 'Southern Ground Hornbill'
description: '''
The southern ground hornbill is the largest hornbill in the world. It is a large, black, turkeylike bird with striking red skin around its eyes and down its foreneck, forming a pouch. The female has a violet patch on the throat rather than just the pure red coloration of the male. The bill is long, thick, and downward-curving, with a small protuberance on the top. Their eyes are pale yellow and their legs and plumage are black, except for a few white wing feathers, which can only be seen when in flight. Juveniles are duller in coloration, appearing browner with yellowish facial skin and brown eyes.
'''
scientificName: '<NAME>'
mainImage: 'assets/fieldguide-content/birds/ground_hornbill/hornbill-feature.jpg'
conservationStatus: 'Vulnerable' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well.
information: [{
label: 'Length'
value: '1.05 m'
}, {
label: 'Weight'
value: '2.2-6.2 kg'
}, {
label: 'Lifespan'
value: 'Up to 70 years'
}, {
label: 'Gestation'
value: '40 days'
}, {
label: 'Avg. number of offspring'
value: '2 eggs are usually laid; only one chick will generally survive'
}]
sections: [{
title: 'Habitat'
content: 'Woodland, grassland, and savanna. '
}, {
title: 'Diet'
content: 'Arthropods, snails, frogs, toads, snakes, hares, and tortoises; also sometimes feeds on carrion, fruits, and seeds'
}, {
title: 'Predators'
content: 'Large predators, such as leopards and crocodiles'
}, {
title: 'Behavior'
content: '''
<p>The southern ground hornbills can live as single breeding pairs but are often seen in cooperative breeding groups. These groups contain between two and eight individuals, with the dominant pair assisted by adult and immature helpers to defend a territory and rear young.</p>
'''
}, {
title: 'Breeding'
content: '''
<p>Southern ground hornbills generally mate between September and December. Females will lay two eggs in a tree or cliff hollow. The first egg is generally laid three to five days before the second, and the eggs will hatch after an incubation period of about 40 days. The first chick regularly outcompetes its younger sibling, as only one chick usually survives. Chicks fledge at around 85 days old. </p>
'''
}, {
title: 'Fun Facts'
style: 'focus-box'
content: '''
<ol>
<li>The southern ground hornbill is the largest hornbill in the world.</li>
<li>The southern ground hornbill is long-lived, reaching 50 or even 60 years old.</li>
</ol>
'''
},{
title: 'Distribution'
content: '<img src="assets/fieldguide-content/birds/ground_hornbill/hornbill-map.jpg"/>'
}]
| true | module.exports =
label: 'Southern Ground Hornbill'
description: '''
The southern ground hornbill is the largest hornbill in the world. It is a large, black, turkeylike bird with striking red skin around its eyes and down its foreneck, forming a pouch. The female has a violet patch on the throat rather than just the pure red coloration of the male. The bill is long, thick, and downward-curving, with a small protuberance on the top. Their eyes are pale yellow and their legs and plumage are black, except for a few white wing feathers, which can only be seen when in flight. Juveniles are duller in coloration, appearing browner with yellowish facial skin and brown eyes.
'''
scientificName: 'PI:NAME:<NAME>END_PI'
mainImage: 'assets/fieldguide-content/birds/ground_hornbill/hornbill-feature.jpg'
conservationStatus: 'Vulnerable' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well.
information: [{
label: 'Length'
value: '1.05 m'
}, {
label: 'Weight'
value: '2.2-6.2 kg'
}, {
label: 'Lifespan'
value: 'Up to 70 years'
}, {
label: 'Gestation'
value: '40 days'
}, {
label: 'Avg. number of offspring'
value: '2 eggs are usually laid; only one chick will generally survive'
}]
sections: [{
title: 'Habitat'
content: 'Woodland, grassland, and savanna. '
}, {
title: 'Diet'
content: 'Arthropods, snails, frogs, toads, snakes, hares, and tortoises; also sometimes feeds on carrion, fruits, and seeds'
}, {
title: 'Predators'
content: 'Large predators, such as leopards and crocodiles'
}, {
title: 'Behavior'
content: '''
<p>The southern ground hornbills can live as single breeding pairs but are often seen in cooperative breeding groups. These groups contain between two and eight individuals, with the dominant pair assisted by adult and immature helpers to defend a territory and rear young.</p>
'''
}, {
title: 'Breeding'
content: '''
<p>Southern ground hornbills generally mate between September and December. Females will lay two eggs in a tree or cliff hollow. The first egg is generally laid three to five days before the second, and the eggs will hatch after an incubation period of about 40 days. The first chick regularly outcompetes its younger sibling, as only one chick usually survives. Chicks fledge at around 85 days old. </p>
'''
}, {
title: 'Fun Facts'
style: 'focus-box'
content: '''
<ol>
<li>The southern ground hornbill is the largest hornbill in the world.</li>
<li>The southern ground hornbill is long-lived, reaching 50 or even 60 years old.</li>
</ol>
'''
},{
title: 'Distribution'
content: '<img src="assets/fieldguide-content/birds/ground_hornbill/hornbill-map.jpg"/>'
}]
|
[
{
"context": " setNewData: (id, index, type, input) ->\n key = cacheKey id, index, type\n data = cache[key] = @decod",
"end": 3675,
"score": 0.815451979637146,
"start": 3670,
"tag": "KEY",
"value": "cache"
}
] | src/TrendController.coffee | higuma/tenki-data-map | 11 | ceil = Math.ceil
floor = Math.floor
limitMin = MiscUtils.limitMin
limitMax = MiscUtils.limitMax
limitMinMax = MiscUtils.limitMinMax
CACHE_LIMIT = 50
cache = {}
queue = []
cacheKey = (id, index, type) ->
if type == 'a'
"#{id}-all"
else
"#{id}-#{index}#{TYPE_POSTFIX[type]}"
TYPE_POSTFIX = TrendModel.TYPE_POSTFIX
DELTA_TIME = TrendDecoder.DELTA_TIME
class TrendController
constructor: (view = null) ->
@model = new TrendModel @
@views = []
@decoder = new TrendDecoder
UpdateChecker.add => @onUpdateData()
@addView view if view?
addView: (v) -> @views.push v if @views.indexOf(v) == -1
removeView: (v) -> @views.splice i, 1 if (i = @views.indexOf v) != -1
# <- View
requestData: (id, tL, tR, nData) ->
tL = new Date(tL) if $.type(tL) == 'number'
tR = new Date(tR) if $.type(tR) == 'number'
@pending = p =
id: id
tL: tL
tR: tR
dt = (tR - tL) / nData
level = DELTA_TIME.length - 1
while level != 0 && DELTA_TIME[level] > dt
--level
p.level = level
tL = tL.ceilHour().prevHour() # ceil and adjust hour offset
tR = tR.ceilHour().prevHour() # (daily data ranges from 01:00 to 24:00)
if level < 4 # 0-3: full data
p.ty = 'y'
p.iL = tL.year()
p.iR = tR.year()
else if level < 7 # 4-6: 12h step
p.ty = 'd'
p.iL = (tL.year() / 10) >> 0
p.iR = (tR.year() / 10) >> 0
else if level < 10 # 7-9: 4d step
p.ty = 'c'
p.iL = (tL.year() / 100) >> 0
p.iR = (tR.year() / 100) >> 0
else # 10-12: 64d step (top level)
p.ty = 'a'
p.iL = p.iR = 0 # (not used)
@resolvePending()
# <- Model
xhrDone: (id, index, type, data) ->
@setNewData id, index, type, data
@resolvePending()
return
xhrFail: (id, index, type, xhrObj) ->
if xhrObj.status == 404
@rescuePending id, index, type
else
@updateViews false
return
# <- Update Checker
onUpdateData: ->
v.onUpdateData() for v in @views
return
# internal
resolvePending: (p = @pending) ->
if p? && (dL = @getData p.id, p.iL, p.ty)?
dR = if p.iL == p.iR then dL else @getData p.id, p.iR, p.ty
@setIterator dL, dR if dR?
return
rescuePending: (id, index, type, p = @pending) ->
if p? && id == p.id && type == p.ty
if index == p.iL
if p.iL == p.iR
@setIterator null
else
p.iL = p.iR
@resolvePending()
else if index == p.iR
p.iR = p.iL
@resolvePending()
return
getData: (id, index, type) ->
key = cacheKey id, index, type
if (data = cache[key])?
queue.splice queue.indexOf(key), 1
queue.push key
else if (input = @model.getData id, index, type)?
data = @setNewData id, index, type, input if @model.isData input
else
@model.xhr id, index, type
data
setIterator: (dL, dR, p = @pending) ->
@iterator = if dL?
tLL = limitMin p.tL, DataInfo.timeMin()
tRR = limitMax p.tR, DataInfo.timeMax()
dL = dL[p.level]
jL = limitMinMax ceil((tLL - dL.t0) / dL.dt), 0, dL.length - 1
if p.iL == p.iR
jR = limitMinMax ceil((tRR - dL.t0) / dL.dt), 0, dL.length - 1
new TrendIterator1 p.id, p.level, p.tL, p.tR, dL, jL, jR
else
dR = dR[p.level]
jR = limitMinMax ceil((tRR - dR.t0) / dR.dt), 0, dR.length - 1
new TrendIterator2 p.id, p.level, p.tL, p.tR, dL, jL, dR, jR
else
new TrendIterator0 p.id, p.level, p.tL, p.tR # data not exist
@pending = null
@updateViews true
return
setNewData: (id, index, type, input) ->
key = cacheKey id, index, type
data = cache[key] = @decoder.decode index, type, input
delete cache[queue.shift()] if queue.length >= CACHE_LIMIT
queue.push key
data
updateViews: (success) ->
v.update @, success for v in @views
return
window.TrendController = TrendController
| 133061 | ceil = Math.ceil
floor = Math.floor
limitMin = MiscUtils.limitMin
limitMax = MiscUtils.limitMax
limitMinMax = MiscUtils.limitMinMax
CACHE_LIMIT = 50
cache = {}
queue = []
cacheKey = (id, index, type) ->
if type == 'a'
"#{id}-all"
else
"#{id}-#{index}#{TYPE_POSTFIX[type]}"
TYPE_POSTFIX = TrendModel.TYPE_POSTFIX
DELTA_TIME = TrendDecoder.DELTA_TIME
class TrendController
constructor: (view = null) ->
@model = new TrendModel @
@views = []
@decoder = new TrendDecoder
UpdateChecker.add => @onUpdateData()
@addView view if view?
addView: (v) -> @views.push v if @views.indexOf(v) == -1
removeView: (v) -> @views.splice i, 1 if (i = @views.indexOf v) != -1
# <- View
requestData: (id, tL, tR, nData) ->
tL = new Date(tL) if $.type(tL) == 'number'
tR = new Date(tR) if $.type(tR) == 'number'
@pending = p =
id: id
tL: tL
tR: tR
dt = (tR - tL) / nData
level = DELTA_TIME.length - 1
while level != 0 && DELTA_TIME[level] > dt
--level
p.level = level
tL = tL.ceilHour().prevHour() # ceil and adjust hour offset
tR = tR.ceilHour().prevHour() # (daily data ranges from 01:00 to 24:00)
if level < 4 # 0-3: full data
p.ty = 'y'
p.iL = tL.year()
p.iR = tR.year()
else if level < 7 # 4-6: 12h step
p.ty = 'd'
p.iL = (tL.year() / 10) >> 0
p.iR = (tR.year() / 10) >> 0
else if level < 10 # 7-9: 4d step
p.ty = 'c'
p.iL = (tL.year() / 100) >> 0
p.iR = (tR.year() / 100) >> 0
else # 10-12: 64d step (top level)
p.ty = 'a'
p.iL = p.iR = 0 # (not used)
@resolvePending()
# <- Model
xhrDone: (id, index, type, data) ->
@setNewData id, index, type, data
@resolvePending()
return
xhrFail: (id, index, type, xhrObj) ->
if xhrObj.status == 404
@rescuePending id, index, type
else
@updateViews false
return
# <- Update Checker
onUpdateData: ->
v.onUpdateData() for v in @views
return
# internal
resolvePending: (p = @pending) ->
if p? && (dL = @getData p.id, p.iL, p.ty)?
dR = if p.iL == p.iR then dL else @getData p.id, p.iR, p.ty
@setIterator dL, dR if dR?
return
rescuePending: (id, index, type, p = @pending) ->
if p? && id == p.id && type == p.ty
if index == p.iL
if p.iL == p.iR
@setIterator null
else
p.iL = p.iR
@resolvePending()
else if index == p.iR
p.iR = p.iL
@resolvePending()
return
getData: (id, index, type) ->
key = cacheKey id, index, type
if (data = cache[key])?
queue.splice queue.indexOf(key), 1
queue.push key
else if (input = @model.getData id, index, type)?
data = @setNewData id, index, type, input if @model.isData input
else
@model.xhr id, index, type
data
setIterator: (dL, dR, p = @pending) ->
@iterator = if dL?
tLL = limitMin p.tL, DataInfo.timeMin()
tRR = limitMax p.tR, DataInfo.timeMax()
dL = dL[p.level]
jL = limitMinMax ceil((tLL - dL.t0) / dL.dt), 0, dL.length - 1
if p.iL == p.iR
jR = limitMinMax ceil((tRR - dL.t0) / dL.dt), 0, dL.length - 1
new TrendIterator1 p.id, p.level, p.tL, p.tR, dL, jL, jR
else
dR = dR[p.level]
jR = limitMinMax ceil((tRR - dR.t0) / dR.dt), 0, dR.length - 1
new TrendIterator2 p.id, p.level, p.tL, p.tR, dL, jL, dR, jR
else
new TrendIterator0 p.id, p.level, p.tL, p.tR # data not exist
@pending = null
@updateViews true
return
setNewData: (id, index, type, input) ->
key = <KEY>Key id, index, type
data = cache[key] = @decoder.decode index, type, input
delete cache[queue.shift()] if queue.length >= CACHE_LIMIT
queue.push key
data
updateViews: (success) ->
v.update @, success for v in @views
return
window.TrendController = TrendController
| true | ceil = Math.ceil
floor = Math.floor
limitMin = MiscUtils.limitMin
limitMax = MiscUtils.limitMax
limitMinMax = MiscUtils.limitMinMax
CACHE_LIMIT = 50
cache = {}
queue = []
cacheKey = (id, index, type) ->
if type == 'a'
"#{id}-all"
else
"#{id}-#{index}#{TYPE_POSTFIX[type]}"
TYPE_POSTFIX = TrendModel.TYPE_POSTFIX
DELTA_TIME = TrendDecoder.DELTA_TIME
class TrendController
constructor: (view = null) ->
@model = new TrendModel @
@views = []
@decoder = new TrendDecoder
UpdateChecker.add => @onUpdateData()
@addView view if view?
addView: (v) -> @views.push v if @views.indexOf(v) == -1
removeView: (v) -> @views.splice i, 1 if (i = @views.indexOf v) != -1
# <- View
requestData: (id, tL, tR, nData) ->
tL = new Date(tL) if $.type(tL) == 'number'
tR = new Date(tR) if $.type(tR) == 'number'
@pending = p =
id: id
tL: tL
tR: tR
dt = (tR - tL) / nData
level = DELTA_TIME.length - 1
while level != 0 && DELTA_TIME[level] > dt
--level
p.level = level
tL = tL.ceilHour().prevHour() # ceil and adjust hour offset
tR = tR.ceilHour().prevHour() # (daily data ranges from 01:00 to 24:00)
if level < 4 # 0-3: full data
p.ty = 'y'
p.iL = tL.year()
p.iR = tR.year()
else if level < 7 # 4-6: 12h step
p.ty = 'd'
p.iL = (tL.year() / 10) >> 0
p.iR = (tR.year() / 10) >> 0
else if level < 10 # 7-9: 4d step
p.ty = 'c'
p.iL = (tL.year() / 100) >> 0
p.iR = (tR.year() / 100) >> 0
else # 10-12: 64d step (top level)
p.ty = 'a'
p.iL = p.iR = 0 # (not used)
@resolvePending()
# <- Model
xhrDone: (id, index, type, data) ->
@setNewData id, index, type, data
@resolvePending()
return
xhrFail: (id, index, type, xhrObj) ->
if xhrObj.status == 404
@rescuePending id, index, type
else
@updateViews false
return
# <- Update Checker
onUpdateData: ->
v.onUpdateData() for v in @views
return
# internal
resolvePending: (p = @pending) ->
if p? && (dL = @getData p.id, p.iL, p.ty)?
dR = if p.iL == p.iR then dL else @getData p.id, p.iR, p.ty
@setIterator dL, dR if dR?
return
rescuePending: (id, index, type, p = @pending) ->
if p? && id == p.id && type == p.ty
if index == p.iL
if p.iL == p.iR
@setIterator null
else
p.iL = p.iR
@resolvePending()
else if index == p.iR
p.iR = p.iL
@resolvePending()
return
getData: (id, index, type) ->
key = cacheKey id, index, type
if (data = cache[key])?
queue.splice queue.indexOf(key), 1
queue.push key
else if (input = @model.getData id, index, type)?
data = @setNewData id, index, type, input if @model.isData input
else
@model.xhr id, index, type
data
setIterator: (dL, dR, p = @pending) ->
@iterator = if dL?
tLL = limitMin p.tL, DataInfo.timeMin()
tRR = limitMax p.tR, DataInfo.timeMax()
dL = dL[p.level]
jL = limitMinMax ceil((tLL - dL.t0) / dL.dt), 0, dL.length - 1
if p.iL == p.iR
jR = limitMinMax ceil((tRR - dL.t0) / dL.dt), 0, dL.length - 1
new TrendIterator1 p.id, p.level, p.tL, p.tR, dL, jL, jR
else
dR = dR[p.level]
jR = limitMinMax ceil((tRR - dR.t0) / dR.dt), 0, dR.length - 1
new TrendIterator2 p.id, p.level, p.tL, p.tR, dL, jL, dR, jR
else
new TrendIterator0 p.id, p.level, p.tL, p.tR # data not exist
@pending = null
@updateViews true
return
setNewData: (id, index, type, input) ->
key = PI:KEY:<KEY>END_PIKey id, index, type
data = cache[key] = @decoder.decode index, type, input
delete cache[queue.shift()] if queue.length >= CACHE_LIMIT
queue.push key
data
updateViews: (success) ->
v.update @, success for v in @views
return
window.TrendController = TrendController
|
[
{
"context": "map (d) -> vars.format.value d * 100,\n key: \"share\"\n vars: vars\n else if vars.y.value is vars.",
"end": 3601,
"score": 0.5017815828323364,
"start": 3596,
"tag": "KEY",
"value": "share"
}
] | src/viz/types/helpers/graph/includes/plot.coffee | jspeis/d3plus | 0 | buckets = require "../../../../../util/buckets.coffee"
buffer = require "./buffer.coffee"
fetchValue = require "../../../../../core/fetch/value.coffee"
fontSizes = require "../../../../../font/sizes.coffee"
textwrap = require "../../../../../textwrap/textwrap.coffee"
timeDetect = require "../../../../../core/data/time.coffee"
uniques = require "../../../../../util/uniques.coffee"
module.exports = (vars, opts) ->
# Reset margins
vars.axes.margin = resetMargins vars
vars.axes.height = vars.height.viz
vars.axes.width = vars.width.viz
# Set ticks, if not previously set
for axis in ["x","y"]
if vars[axis].ticks.values is false
if vars[axis].value is vars.time.value
ticks = vars.time.solo.value
if ticks.length
ticks = ticks.map (d) ->
if d.constructor isnt Date
d = new Date(d.toString())
d.setTime( d.getTime() + d.getTimezoneOffset() * 60 * 1000 )
d
else
ticks = vars.data.time.values
extent = d3.extent ticks
step = vars.data.time.stepType
ticks = [extent[0]]
tick = extent[0]
while tick < extent[1]
newtick = new Date tick
tick = new Date newtick["set"+step](newtick["get"+step]()+1)
ticks.push tick
vars[axis].ticks.values = ticks
else
vars[axis].ticks.values = vars[axis].scale.viz.ticks()
unless vars[axis].ticks.values.length
values = fetchValue vars, vars.data.viz, vars[axis].value
values = [values] unless values instanceof Array
vars[axis].ticks.values = values
opp = if axis is "x" then "y" else "x"
if vars[axis].ticks.values.length is 1 or
(opts.buffer and opts.buffer isnt opp and
axis is vars.axes.discrete and vars[axis].reset is true)
buffer vars, axis, opts.buffer
vars[axis].reset = false
if vars[axis].value is vars.time.value
axisStyle =
"font-family": vars[axis].ticks.font.family.value
"font-weight": vars[axis].ticks.font.weight
"font-size": vars[axis].ticks.font.size+"px"
timeReturn = timeDetect vars,
values: vars[axis].ticks.values
limit: vars.width.viz
style: axisStyle
vars[axis].ticks.visible = timeReturn.values.map Number
vars[axis].ticks.format = timeReturn.format
else if vars[axis].scale.value is "log"
ticks = vars[axis].ticks.values
tens = ticks.filter (t) -> Math.abs(t).toString().charAt(0) is "1"
if tens.length < 3
vars[axis].ticks.visible = ticks
else
vars[axis].ticks.visible = tens
else
vars[axis].ticks.visible = vars[axis].ticks.values
# Calculate padding for tick labels
labelPadding vars unless vars.small
# Create SVG Axes
for axis in ["x","y"]
vars[axis].axis.svg = createAxis(vars, axis)
return
resetMargins = (vars) ->
if vars.small
# return
top: 0
right: 0
bottom: 0
left: 0
else
# return
top: 10
right: 10
bottom: 10
left: 10
labelPadding = (vars) ->
xDomain = vars.x.scale.viz.domain()
yDomain = vars.y.scale.viz.domain()
# Calculate Y axis padding
yAttrs =
"font-size": vars.y.ticks.font.size+"px"
"font-family": vars.y.ticks.font.family.value
"font-weight": vars.y.ticks.font.weight
yValues = vars.y.ticks.visible
if vars.y.scale.value is "log"
yText = yValues.map (d) -> formatPower d
else if vars.y.scale.value is "share"
yText = yValues.map (d) -> vars.format.value d * 100,
key: "share"
vars: vars
else if vars.y.value is vars.time.value
yText = yValues.map (d, i) ->
vars.y.ticks.format new Date(d)
else
if typeof yValues[0] is "string"
yValues = vars.y.scale.viz.domain().filter (d) ->
d.indexOf("d3plus_buffer_") isnt 0
yText = yValues.map (d) ->
vars.format.value d,
key: vars.y.value
vars: vars
labels: vars.y.affixes.value
yAxisWidth = d3.max fontSizes(yText,yAttrs), (d) -> d.width
yAxisWidth = Math.ceil yAxisWidth + vars.labels.padding
vars.axes.margin.left += yAxisWidth
yLabel = vars.y.label.fetch vars
if yLabel
yLabelAttrs =
"font-family": vars.y.label.font.family.value
"font-weight": vars.y.label.font.weight
"font-size": vars.y.label.font.size+"px"
vars.y.label.height = fontSizes([yLabel], yLabelAttrs)[0].height
else
vars.y.label.height = 0
if vars.y.label.value
vars.axes.margin.left += vars.y.label.height
vars.axes.margin.left += vars.y.label.padding * 2
vars.axes.width -= (vars.axes.margin.left + vars.axes.margin.right)
vars.x.scale.viz.range buckets([0,vars.axes.width], xDomain.length)
# Calculate X axis padding
xAttrs =
"font-size": vars.x.ticks.font.size+"px"
"font-family": vars.x.ticks.font.family.value
"font-weight": vars.x.ticks.font.weight
xValues = vars.x.ticks.visible
if vars.x.scale.value is "log"
xText = xValues.map (d) -> formatPower d
else if vars.x.scale.value is "share"
xText = xValues.map (d) -> vars.format.value d * 100,
key: "share"
vars: vars
else if vars.x.value is vars.time.value
xText = xValues.map (d, i) ->
vars.x.ticks.format new Date(d)
else
if typeof xValues[0] is "string"
xValues = vars.x.scale.viz.domain().filter (d) ->
d.indexOf("d3plus_buffer_") isnt 0
xText = xValues.map (d) ->
vars.format.value d,
key: vars.x.value
vars: vars
labels: vars.x.affixes.value
xSizes = fontSizes(xText,xAttrs)
xAxisWidth = d3.max xSizes, (d) -> d.width
xAxisHeight = d3.max xSizes, (d) -> d.height
if xValues.length is 1
xMaxWidth = vars.axes.width
else
xMaxWidth = vars.x.scale.viz(xValues[1]) - vars.x.scale.viz(xValues[0])
xMaxWidth = Math.abs xMaxWidth
xMaxWidth -= vars.labels.padding * 2
if xAxisWidth > xMaxWidth and xText.join("").indexOf(" ") > 0
vars.x.ticks.wrap = true
xSizes = fontSizes xText, xAttrs,
mod: (elem) ->
textwrap().container d3.select(elem)
.height(vars.axes.height/2)
.width(xMaxWidth).draw()
xAxisWidth = d3.max xSizes, (d) -> d.width
xAxisHeight = d3.max xSizes, (d) -> d.height
else
vars.x.ticks.wrap = false
vars.x.ticks.hidden = false
vars.x.ticks.baseline = "auto"
if xAxisWidth <= xMaxWidth
vars.x.ticks.rotate = 0
else if xAxisWidth < vars.axes.height/2
xSizes = fontSizes xText, xAttrs,
mod: (elem) ->
textwrap().container d3.select(elem)
.width(vars.axes.height/2)
.height(xMaxWidth).draw()
xAxisHeight = d3.max xSizes, (d) -> d.width
xAxisWidth = d3.max xSizes, (d) -> d.height
vars.x.ticks.rotate = -90
else
vars.x.ticks.hidden = true
vars.x.ticks.rotate = 0
xAxisWidth = 0
xAxisHeight = 0
xAxisHeight = Math.ceil xAxisHeight
xAxisWidth = Math.ceil xAxisWidth
vars.x.ticks.maxHeight = xAxisHeight
vars.x.ticks.maxWidth = xAxisWidth
vars.axes.margin.bottom += xAxisHeight + vars.labels.padding
lastTick = vars.x.ticks.visible[vars.x.ticks.visible.length - 1]
rightLabel = vars.x.scale.viz lastTick
rightLabel += xAxisWidth/2 + vars.axes.margin.left
if rightLabel > vars.width.value
rightMod = rightLabel - vars.width.value + vars.axes.margin.right
vars.axes.width -= rightMod
vars.axes.margin.right += rightMod
xLabel = vars.x.label.fetch vars
if xLabel
xLabelAttrs =
"font-family": vars.x.label.font.family.value
"font-weight": vars.x.label.font.weight
"font-size": vars.x.label.font.size+"px"
vars.x.label.height = fontSizes([xLabel], xLabelAttrs)[0].height
else
vars.x.label.height = 0
if vars.x.label.value
vars.axes.margin.bottom += vars.x.label.height
vars.axes.margin.bottom += vars.x.label.padding * 2
vars.axes.height -= (vars.axes.margin.top + vars.axes.margin.bottom)
vars.x.scale.viz.range buckets([0,vars.axes.width], xDomain.length)
vars.y.scale.viz.range buckets([0,vars.axes.height], yDomain.length)
createAxis = (vars, axis) ->
d3.svg.axis()
.tickSize vars[axis].ticks.size
.tickPadding 5
.orient if axis is "x" then "bottom" else "left"
.scale vars[axis].scale.viz
.tickValues vars[axis].ticks.values
.tickFormat (d, i) ->
return null if vars[axis].ticks.hidden
scale = vars[axis].scale.value
c = if d.constructor is Date then +d else d
if vars[axis].ticks.visible.indexOf(c) >= 0
if scale is "share"
vars.format.value d * 100,
key: "share", vars: vars, labels: vars[axis].affixes.value
else if d.constructor is Date
vars[axis].ticks.format d
else if scale is "log"
formatPower d
else
vars.format.value d,
key: vars[axis].value, vars: vars, labels: vars[axis].affixes.value
else
null
superscript = "⁰¹²³⁴⁵⁶⁷⁸⁹"
formatPower = (d) ->
p = Math.round(Math.log(Math.abs(d)) / Math.LN10)
t = Math.abs(d).toString().charAt(0)
n = 10 + " " + (p + "").split("").map((c) -> superscript[c]).join("")
if t isnt "1"
n = t + " x " + n
if d < 0 then "-"+n else n
| 182188 | buckets = require "../../../../../util/buckets.coffee"
buffer = require "./buffer.coffee"
fetchValue = require "../../../../../core/fetch/value.coffee"
fontSizes = require "../../../../../font/sizes.coffee"
textwrap = require "../../../../../textwrap/textwrap.coffee"
timeDetect = require "../../../../../core/data/time.coffee"
uniques = require "../../../../../util/uniques.coffee"
module.exports = (vars, opts) ->
# Reset margins
vars.axes.margin = resetMargins vars
vars.axes.height = vars.height.viz
vars.axes.width = vars.width.viz
# Set ticks, if not previously set
for axis in ["x","y"]
if vars[axis].ticks.values is false
if vars[axis].value is vars.time.value
ticks = vars.time.solo.value
if ticks.length
ticks = ticks.map (d) ->
if d.constructor isnt Date
d = new Date(d.toString())
d.setTime( d.getTime() + d.getTimezoneOffset() * 60 * 1000 )
d
else
ticks = vars.data.time.values
extent = d3.extent ticks
step = vars.data.time.stepType
ticks = [extent[0]]
tick = extent[0]
while tick < extent[1]
newtick = new Date tick
tick = new Date newtick["set"+step](newtick["get"+step]()+1)
ticks.push tick
vars[axis].ticks.values = ticks
else
vars[axis].ticks.values = vars[axis].scale.viz.ticks()
unless vars[axis].ticks.values.length
values = fetchValue vars, vars.data.viz, vars[axis].value
values = [values] unless values instanceof Array
vars[axis].ticks.values = values
opp = if axis is "x" then "y" else "x"
if vars[axis].ticks.values.length is 1 or
(opts.buffer and opts.buffer isnt opp and
axis is vars.axes.discrete and vars[axis].reset is true)
buffer vars, axis, opts.buffer
vars[axis].reset = false
if vars[axis].value is vars.time.value
axisStyle =
"font-family": vars[axis].ticks.font.family.value
"font-weight": vars[axis].ticks.font.weight
"font-size": vars[axis].ticks.font.size+"px"
timeReturn = timeDetect vars,
values: vars[axis].ticks.values
limit: vars.width.viz
style: axisStyle
vars[axis].ticks.visible = timeReturn.values.map Number
vars[axis].ticks.format = timeReturn.format
else if vars[axis].scale.value is "log"
ticks = vars[axis].ticks.values
tens = ticks.filter (t) -> Math.abs(t).toString().charAt(0) is "1"
if tens.length < 3
vars[axis].ticks.visible = ticks
else
vars[axis].ticks.visible = tens
else
vars[axis].ticks.visible = vars[axis].ticks.values
# Calculate padding for tick labels
labelPadding vars unless vars.small
# Create SVG Axes
for axis in ["x","y"]
vars[axis].axis.svg = createAxis(vars, axis)
return
resetMargins = (vars) ->
if vars.small
# return
top: 0
right: 0
bottom: 0
left: 0
else
# return
top: 10
right: 10
bottom: 10
left: 10
labelPadding = (vars) ->
xDomain = vars.x.scale.viz.domain()
yDomain = vars.y.scale.viz.domain()
# Calculate Y axis padding
yAttrs =
"font-size": vars.y.ticks.font.size+"px"
"font-family": vars.y.ticks.font.family.value
"font-weight": vars.y.ticks.font.weight
yValues = vars.y.ticks.visible
if vars.y.scale.value is "log"
yText = yValues.map (d) -> formatPower d
else if vars.y.scale.value is "share"
yText = yValues.map (d) -> vars.format.value d * 100,
key: "<KEY>"
vars: vars
else if vars.y.value is vars.time.value
yText = yValues.map (d, i) ->
vars.y.ticks.format new Date(d)
else
if typeof yValues[0] is "string"
yValues = vars.y.scale.viz.domain().filter (d) ->
d.indexOf("d3plus_buffer_") isnt 0
yText = yValues.map (d) ->
vars.format.value d,
key: vars.y.value
vars: vars
labels: vars.y.affixes.value
yAxisWidth = d3.max fontSizes(yText,yAttrs), (d) -> d.width
yAxisWidth = Math.ceil yAxisWidth + vars.labels.padding
vars.axes.margin.left += yAxisWidth
yLabel = vars.y.label.fetch vars
if yLabel
yLabelAttrs =
"font-family": vars.y.label.font.family.value
"font-weight": vars.y.label.font.weight
"font-size": vars.y.label.font.size+"px"
vars.y.label.height = fontSizes([yLabel], yLabelAttrs)[0].height
else
vars.y.label.height = 0
if vars.y.label.value
vars.axes.margin.left += vars.y.label.height
vars.axes.margin.left += vars.y.label.padding * 2
vars.axes.width -= (vars.axes.margin.left + vars.axes.margin.right)
vars.x.scale.viz.range buckets([0,vars.axes.width], xDomain.length)
# Calculate X axis padding
xAttrs =
"font-size": vars.x.ticks.font.size+"px"
"font-family": vars.x.ticks.font.family.value
"font-weight": vars.x.ticks.font.weight
xValues = vars.x.ticks.visible
if vars.x.scale.value is "log"
xText = xValues.map (d) -> formatPower d
else if vars.x.scale.value is "share"
xText = xValues.map (d) -> vars.format.value d * 100,
key: "share"
vars: vars
else if vars.x.value is vars.time.value
xText = xValues.map (d, i) ->
vars.x.ticks.format new Date(d)
else
if typeof xValues[0] is "string"
xValues = vars.x.scale.viz.domain().filter (d) ->
d.indexOf("d3plus_buffer_") isnt 0
xText = xValues.map (d) ->
vars.format.value d,
key: vars.x.value
vars: vars
labels: vars.x.affixes.value
xSizes = fontSizes(xText,xAttrs)
xAxisWidth = d3.max xSizes, (d) -> d.width
xAxisHeight = d3.max xSizes, (d) -> d.height
if xValues.length is 1
xMaxWidth = vars.axes.width
else
xMaxWidth = vars.x.scale.viz(xValues[1]) - vars.x.scale.viz(xValues[0])
xMaxWidth = Math.abs xMaxWidth
xMaxWidth -= vars.labels.padding * 2
if xAxisWidth > xMaxWidth and xText.join("").indexOf(" ") > 0
vars.x.ticks.wrap = true
xSizes = fontSizes xText, xAttrs,
mod: (elem) ->
textwrap().container d3.select(elem)
.height(vars.axes.height/2)
.width(xMaxWidth).draw()
xAxisWidth = d3.max xSizes, (d) -> d.width
xAxisHeight = d3.max xSizes, (d) -> d.height
else
vars.x.ticks.wrap = false
vars.x.ticks.hidden = false
vars.x.ticks.baseline = "auto"
if xAxisWidth <= xMaxWidth
vars.x.ticks.rotate = 0
else if xAxisWidth < vars.axes.height/2
xSizes = fontSizes xText, xAttrs,
mod: (elem) ->
textwrap().container d3.select(elem)
.width(vars.axes.height/2)
.height(xMaxWidth).draw()
xAxisHeight = d3.max xSizes, (d) -> d.width
xAxisWidth = d3.max xSizes, (d) -> d.height
vars.x.ticks.rotate = -90
else
vars.x.ticks.hidden = true
vars.x.ticks.rotate = 0
xAxisWidth = 0
xAxisHeight = 0
xAxisHeight = Math.ceil xAxisHeight
xAxisWidth = Math.ceil xAxisWidth
vars.x.ticks.maxHeight = xAxisHeight
vars.x.ticks.maxWidth = xAxisWidth
vars.axes.margin.bottom += xAxisHeight + vars.labels.padding
lastTick = vars.x.ticks.visible[vars.x.ticks.visible.length - 1]
rightLabel = vars.x.scale.viz lastTick
rightLabel += xAxisWidth/2 + vars.axes.margin.left
if rightLabel > vars.width.value
rightMod = rightLabel - vars.width.value + vars.axes.margin.right
vars.axes.width -= rightMod
vars.axes.margin.right += rightMod
xLabel = vars.x.label.fetch vars
if xLabel
xLabelAttrs =
"font-family": vars.x.label.font.family.value
"font-weight": vars.x.label.font.weight
"font-size": vars.x.label.font.size+"px"
vars.x.label.height = fontSizes([xLabel], xLabelAttrs)[0].height
else
vars.x.label.height = 0
if vars.x.label.value
vars.axes.margin.bottom += vars.x.label.height
vars.axes.margin.bottom += vars.x.label.padding * 2
vars.axes.height -= (vars.axes.margin.top + vars.axes.margin.bottom)
vars.x.scale.viz.range buckets([0,vars.axes.width], xDomain.length)
vars.y.scale.viz.range buckets([0,vars.axes.height], yDomain.length)
createAxis = (vars, axis) ->
d3.svg.axis()
.tickSize vars[axis].ticks.size
.tickPadding 5
.orient if axis is "x" then "bottom" else "left"
.scale vars[axis].scale.viz
.tickValues vars[axis].ticks.values
.tickFormat (d, i) ->
return null if vars[axis].ticks.hidden
scale = vars[axis].scale.value
c = if d.constructor is Date then +d else d
if vars[axis].ticks.visible.indexOf(c) >= 0
if scale is "share"
vars.format.value d * 100,
key: "share", vars: vars, labels: vars[axis].affixes.value
else if d.constructor is Date
vars[axis].ticks.format d
else if scale is "log"
formatPower d
else
vars.format.value d,
key: vars[axis].value, vars: vars, labels: vars[axis].affixes.value
else
null
superscript = "⁰¹²³⁴⁵⁶⁷⁸⁹"
formatPower = (d) ->
p = Math.round(Math.log(Math.abs(d)) / Math.LN10)
t = Math.abs(d).toString().charAt(0)
n = 10 + " " + (p + "").split("").map((c) -> superscript[c]).join("")
if t isnt "1"
n = t + " x " + n
if d < 0 then "-"+n else n
| true | buckets = require "../../../../../util/buckets.coffee"
buffer = require "./buffer.coffee"
fetchValue = require "../../../../../core/fetch/value.coffee"
fontSizes = require "../../../../../font/sizes.coffee"
textwrap = require "../../../../../textwrap/textwrap.coffee"
timeDetect = require "../../../../../core/data/time.coffee"
uniques = require "../../../../../util/uniques.coffee"
module.exports = (vars, opts) ->
# Reset margins
vars.axes.margin = resetMargins vars
vars.axes.height = vars.height.viz
vars.axes.width = vars.width.viz
# Set ticks, if not previously set
for axis in ["x","y"]
if vars[axis].ticks.values is false
if vars[axis].value is vars.time.value
ticks = vars.time.solo.value
if ticks.length
ticks = ticks.map (d) ->
if d.constructor isnt Date
d = new Date(d.toString())
d.setTime( d.getTime() + d.getTimezoneOffset() * 60 * 1000 )
d
else
ticks = vars.data.time.values
extent = d3.extent ticks
step = vars.data.time.stepType
ticks = [extent[0]]
tick = extent[0]
while tick < extent[1]
newtick = new Date tick
tick = new Date newtick["set"+step](newtick["get"+step]()+1)
ticks.push tick
vars[axis].ticks.values = ticks
else
vars[axis].ticks.values = vars[axis].scale.viz.ticks()
unless vars[axis].ticks.values.length
values = fetchValue vars, vars.data.viz, vars[axis].value
values = [values] unless values instanceof Array
vars[axis].ticks.values = values
opp = if axis is "x" then "y" else "x"
if vars[axis].ticks.values.length is 1 or
(opts.buffer and opts.buffer isnt opp and
axis is vars.axes.discrete and vars[axis].reset is true)
buffer vars, axis, opts.buffer
vars[axis].reset = false
if vars[axis].value is vars.time.value
axisStyle =
"font-family": vars[axis].ticks.font.family.value
"font-weight": vars[axis].ticks.font.weight
"font-size": vars[axis].ticks.font.size+"px"
timeReturn = timeDetect vars,
values: vars[axis].ticks.values
limit: vars.width.viz
style: axisStyle
vars[axis].ticks.visible = timeReturn.values.map Number
vars[axis].ticks.format = timeReturn.format
else if vars[axis].scale.value is "log"
ticks = vars[axis].ticks.values
tens = ticks.filter (t) -> Math.abs(t).toString().charAt(0) is "1"
if tens.length < 3
vars[axis].ticks.visible = ticks
else
vars[axis].ticks.visible = tens
else
vars[axis].ticks.visible = vars[axis].ticks.values
# Calculate padding for tick labels
labelPadding vars unless vars.small
# Create SVG Axes
for axis in ["x","y"]
vars[axis].axis.svg = createAxis(vars, axis)
return
resetMargins = (vars) ->
if vars.small
# return
top: 0
right: 0
bottom: 0
left: 0
else
# return
top: 10
right: 10
bottom: 10
left: 10
labelPadding = (vars) ->
xDomain = vars.x.scale.viz.domain()
yDomain = vars.y.scale.viz.domain()
# Calculate Y axis padding
yAttrs =
"font-size": vars.y.ticks.font.size+"px"
"font-family": vars.y.ticks.font.family.value
"font-weight": vars.y.ticks.font.weight
yValues = vars.y.ticks.visible
if vars.y.scale.value is "log"
yText = yValues.map (d) -> formatPower d
else if vars.y.scale.value is "share"
yText = yValues.map (d) -> vars.format.value d * 100,
key: "PI:KEY:<KEY>END_PI"
vars: vars
else if vars.y.value is vars.time.value
yText = yValues.map (d, i) ->
vars.y.ticks.format new Date(d)
else
if typeof yValues[0] is "string"
yValues = vars.y.scale.viz.domain().filter (d) ->
d.indexOf("d3plus_buffer_") isnt 0
yText = yValues.map (d) ->
vars.format.value d,
key: vars.y.value
vars: vars
labels: vars.y.affixes.value
yAxisWidth = d3.max fontSizes(yText,yAttrs), (d) -> d.width
yAxisWidth = Math.ceil yAxisWidth + vars.labels.padding
vars.axes.margin.left += yAxisWidth
yLabel = vars.y.label.fetch vars
if yLabel
yLabelAttrs =
"font-family": vars.y.label.font.family.value
"font-weight": vars.y.label.font.weight
"font-size": vars.y.label.font.size+"px"
vars.y.label.height = fontSizes([yLabel], yLabelAttrs)[0].height
else
vars.y.label.height = 0
if vars.y.label.value
vars.axes.margin.left += vars.y.label.height
vars.axes.margin.left += vars.y.label.padding * 2
vars.axes.width -= (vars.axes.margin.left + vars.axes.margin.right)
vars.x.scale.viz.range buckets([0,vars.axes.width], xDomain.length)
# Calculate X axis padding
xAttrs =
"font-size": vars.x.ticks.font.size+"px"
"font-family": vars.x.ticks.font.family.value
"font-weight": vars.x.ticks.font.weight
xValues = vars.x.ticks.visible
if vars.x.scale.value is "log"
xText = xValues.map (d) -> formatPower d
else if vars.x.scale.value is "share"
xText = xValues.map (d) -> vars.format.value d * 100,
key: "share"
vars: vars
else if vars.x.value is vars.time.value
xText = xValues.map (d, i) ->
vars.x.ticks.format new Date(d)
else
if typeof xValues[0] is "string"
xValues = vars.x.scale.viz.domain().filter (d) ->
d.indexOf("d3plus_buffer_") isnt 0
xText = xValues.map (d) ->
vars.format.value d,
key: vars.x.value
vars: vars
labels: vars.x.affixes.value
xSizes = fontSizes(xText,xAttrs)
xAxisWidth = d3.max xSizes, (d) -> d.width
xAxisHeight = d3.max xSizes, (d) -> d.height
if xValues.length is 1
xMaxWidth = vars.axes.width
else
xMaxWidth = vars.x.scale.viz(xValues[1]) - vars.x.scale.viz(xValues[0])
xMaxWidth = Math.abs xMaxWidth
xMaxWidth -= vars.labels.padding * 2
if xAxisWidth > xMaxWidth and xText.join("").indexOf(" ") > 0
vars.x.ticks.wrap = true
xSizes = fontSizes xText, xAttrs,
mod: (elem) ->
textwrap().container d3.select(elem)
.height(vars.axes.height/2)
.width(xMaxWidth).draw()
xAxisWidth = d3.max xSizes, (d) -> d.width
xAxisHeight = d3.max xSizes, (d) -> d.height
else
vars.x.ticks.wrap = false
vars.x.ticks.hidden = false
vars.x.ticks.baseline = "auto"
if xAxisWidth <= xMaxWidth
vars.x.ticks.rotate = 0
else if xAxisWidth < vars.axes.height/2
xSizes = fontSizes xText, xAttrs,
mod: (elem) ->
textwrap().container d3.select(elem)
.width(vars.axes.height/2)
.height(xMaxWidth).draw()
xAxisHeight = d3.max xSizes, (d) -> d.width
xAxisWidth = d3.max xSizes, (d) -> d.height
vars.x.ticks.rotate = -90
else
vars.x.ticks.hidden = true
vars.x.ticks.rotate = 0
xAxisWidth = 0
xAxisHeight = 0
xAxisHeight = Math.ceil xAxisHeight
xAxisWidth = Math.ceil xAxisWidth
vars.x.ticks.maxHeight = xAxisHeight
vars.x.ticks.maxWidth = xAxisWidth
vars.axes.margin.bottom += xAxisHeight + vars.labels.padding
lastTick = vars.x.ticks.visible[vars.x.ticks.visible.length - 1]
rightLabel = vars.x.scale.viz lastTick
rightLabel += xAxisWidth/2 + vars.axes.margin.left
if rightLabel > vars.width.value
rightMod = rightLabel - vars.width.value + vars.axes.margin.right
vars.axes.width -= rightMod
vars.axes.margin.right += rightMod
xLabel = vars.x.label.fetch vars
if xLabel
xLabelAttrs =
"font-family": vars.x.label.font.family.value
"font-weight": vars.x.label.font.weight
"font-size": vars.x.label.font.size+"px"
vars.x.label.height = fontSizes([xLabel], xLabelAttrs)[0].height
else
vars.x.label.height = 0
if vars.x.label.value
vars.axes.margin.bottom += vars.x.label.height
vars.axes.margin.bottom += vars.x.label.padding * 2
vars.axes.height -= (vars.axes.margin.top + vars.axes.margin.bottom)
vars.x.scale.viz.range buckets([0,vars.axes.width], xDomain.length)
vars.y.scale.viz.range buckets([0,vars.axes.height], yDomain.length)
createAxis = (vars, axis) ->
d3.svg.axis()
.tickSize vars[axis].ticks.size
.tickPadding 5
.orient if axis is "x" then "bottom" else "left"
.scale vars[axis].scale.viz
.tickValues vars[axis].ticks.values
.tickFormat (d, i) ->
return null if vars[axis].ticks.hidden
scale = vars[axis].scale.value
c = if d.constructor is Date then +d else d
if vars[axis].ticks.visible.indexOf(c) >= 0
if scale is "share"
vars.format.value d * 100,
key: "share", vars: vars, labels: vars[axis].affixes.value
else if d.constructor is Date
vars[axis].ticks.format d
else if scale is "log"
formatPower d
else
vars.format.value d,
key: vars[axis].value, vars: vars, labels: vars[axis].affixes.value
else
null
superscript = "⁰¹²³⁴⁵⁶⁷⁸⁹"
formatPower = (d) ->
p = Math.round(Math.log(Math.abs(d)) / Math.LN10)
t = Math.abs(d).toString().charAt(0)
n = 10 + " " + (p + "").split("").map((c) -> superscript[c]).join("")
if t isnt "1"
n = t + " x " + n
if d < 0 then "-"+n else n
|
[
{
"context": "# Copyright (c) 2015 Jesse Grosjean. All rights reserved.\n\nFoldingTextService = requi",
"end": 35,
"score": 0.9997032880783081,
"start": 21,
"tag": "NAME",
"value": "Jesse Grosjean"
}
] | atom/packages/foldingtext-for-atom/lib/extensions/ui/token-input-element.coffee | prookie/dotfiles-1 | 0 | # Copyright (c) 2015 Jesse Grosjean. All rights reserved.
FoldingTextService = require '../../foldingtext-service'
{Disposable, CompositeDisposable} = require 'atom'
TextInputElement = require './text-input-element'
class TokenInputElement extends HTMLElement
textInputElement: null
createdCallback: ->
@tokenzieRegex = /\s|,|#/
@list = document.createElement 'ol'
@appendChild @list
@textInputElement = document.createElement 'ft-text-input'
@textEditorElement = @textInputElement.textEditorElement
@textEditor = @textInputElement.textEditor
@appendChild @textInputElement
@updateLayout()
attachedCallback: ->
@updateLayout()
setTimeout =>
@updateLayout()
detachedCallback: ->
attributeChangedCallback: (attrName, oldVal, newVal) ->
###
Section: Messages to the user
###
getPlaceholderText: ->
@textInputElement.getPlaceholderText()
setPlaceholderText: (placeholderText) ->
@textInputElement.setPlaceholderText placeholderText
setMessage: (message='') ->
@textInputElement.setMessage message
setHTMLMessage: (htmlMessage='') ->
@textInputElement.setHTMLMessage htmlMessage
###
Section: Accessory Elements
###
addAccessoryElement: (element) ->
@textInputElement.addAccessoryElement element
###
Section: Text
###
getText: ->
@textInputElement.getText()
setText: (text) ->
@textInputElement.setText text
###
Section: Delegate
###
getDelegate: ->
@textInputElement.getDelegate()
setDelegate: (delegate) ->
originalDidInsertText = delegate.didInsertText?.bind(delegate)
delegate.didInsertText = (e) =>
@setSelectedToken(null)
if e.text.match(@tokenzieRegex)
@setSelectedToken(null)
@tokenizeText()
originalDidInsertText?(e)
@textInputElement.setDelegate(delegate)
###
Section: Tokens
###
getTokens: ->
tokens = []
for each in @list.children
tokens.push each.textContent
tokens
hasToken: (token) ->
!! @getElementForToken token
toggleToken: (token) ->
if @hasToken token
@deleteToken token
else
@tokenizeText token
deleteToken: (token) ->
@deleteTokenElement @getElementForToken token
getSelectedToken: ->
@getSelectedTokenElement()?._token
setSelectedToken: (token) ->
@selectTokenElement @getElementForToken token
tokenizeText: (text) ->
text ?= @getText() or ''
if text
delegate = @getDelegate()
tokens = (token for token in text.split(/\s|,|#/) when token.length > 0)
for each in tokens
delegate?.willAddToken?(each)
tokenElement = document.createElement 'li'
tokenElement.textContent = each
tokenElement._token = each
@list.appendChild(tokenElement)
delegate?.didAddToken?(each)
@setText('')
@updateLayout()
###
Section: Element Actions
###
focusTextEditor: ->
@textInputElement.focusTextEditor()
###
Section: Private
###
moveToStart: (e) ->
@tokenizeText()
@selectTokenElement @list.firstChild
moveToEnd: (e) ->
@setSelectedToken null
moveBackward: (e) ->
if @textInputElement.isCursorAtStart()
@selectPreviousTokenElement()
@tokenizeText()
moveForward: (e) ->
if @textInputElement.isCursorAtStart()
@selectNextTokenElement()
deleteTokenElement: (element) ->
return unless element
token = element.textContent
delegate = @getDelegate()
delegate?.willDeleteToken?(token)
element.parentElement.removeChild element
delegate?.didDeleteToken?(token)
@updateLayout()
delete: (e, backspace) ->
if backspace and not @textInputElement.isCursorAtStart()
return
if selected = @getSelectedTokenElement()
if backspace
@selectTokenElement(selected.previousSibling or selected.nextSibling)
else
@selectTokenElement(selected.nextSibling or selected.previousSibling)
@deleteTokenElement selected
else if backspace
@selectPreviousTokenElement()
@tokenizeText()
selectPreviousTokenElement: ->
current = @getSelectedTokenElement()
previous = current?.previousSibling
if not previous and not current
previous = @list.lastChild
if previous
@selectTokenElement(previous)
selectNextTokenElement: ->
current = @getSelectedTokenElement()
next = current?.nextSibling
@selectTokenElement(next)
selectTokenElement: (element) ->
oldSelected = @getSelectedTokenElement()
unless element is oldSelected
token = element?.textContent
delegate = @getDelegate()
delegate?.willSelectToken?(token)
oldSelected?.classList.remove 'selected'
if element
element.classList.add('selected')
@classList.add 'has-token-selected'
else
@classList.remove 'has-token-selected'
@textEditorElement.component?.presenter?.pauseCursorBlinking?() # Hack
delegate?.didSelectToken?(token)
getSelectedTokenElement: ->
for each in @list.children
if each.classList.contains 'selected'
return each
getElementForToken: (token) ->
for each in @list.children
if each._token is token
return each
updateLayout: ->
@list.style.top = null
@list.style.left = null
@list.style.width = null
@textEditorElement.style.paddingTop = null
@textEditorElement.style.paddingLeft = null
textEditorComputedStyle = window.getComputedStyle(@textEditorElement)
defaultPaddingLeft = parseFloat(textEditorComputedStyle.paddingLeft, 10)
defaultPaddingTop = parseFloat(textEditorComputedStyle.paddingTop, 10)
editorRect = @textEditorElement.getBoundingClientRect()
tokensRect = @list.getBoundingClientRect()
padTop = false
if tokensRect.width > editorRect.width
@list.style.width = editorRect.width + 'px'
tokensRect = @list.getBoundingClientRect()
padTop = true
# Vertical Align
topOffset = editorRect.top - tokensRect.top
if padTop
@textEditorElement.style.paddingTop = (tokensRect.height) + 'px'
else
topOffset += ((editorRect.height / 2) - (tokensRect.height / 2))
@list.style.top = topOffset + 'px'
# Horizontal Align
@list.style.left = defaultPaddingLeft + 'px'
if tokensRect.width
@textEditorElement.style.paddingLeft = (tokensRect.width + (defaultPaddingLeft * 1.25)) + 'px'
FoldingTextService.eventRegistery.listen 'ft-token-input > ol > li',
mousedown: (e) ->
tokenInput = @parentElement.parentElement
tokenInput.tokenizeText()
tokenInput.selectTokenElement this
e.stopImmediatePropagation()
e.stopPropagation()
e.preventDefault()
click: (e) ->
e.stopImmediatePropagation()
e.stopPropagation()
e.preventDefault()
FoldingTextService.eventRegistery.listen 'ft-token-input > ft-text-input > atom-text-editor[mini]',
mousedown: (e) ->
@parentElement.parentElement.setSelectedToken null
atom.commands.add 'ft-token-input > ft-text-input > atom-text-editor[mini]',
'editor:move-to-first-character-of-line': (e) -> @parentElement.parentElement.moveToStart(e)
'editor:move-to-beginning-of-line': (e) -> @parentElement.parentElement.moveToStart(e)
'editor:move-to-beginning-of-paragraph': (e) -> @parentElement.parentElement.moveToStart(e)
'editor:move-to-beginning-of-word': (e) -> @parentElement.parentElement.moveBackward(e)
'core:move-backward': (e) -> @parentElement.parentElement.moveBackward(e)
'core:move-left': (e) -> @parentElement.parentElement.moveBackward(e)
'editor:move-to-end-of-word': (e) -> @parentElement.parentElement.moveForward(e)
'core:move-forward': (e) -> @parentElement.parentElement.moveForward(e)
'core:move-right': (e) -> @parentElement.parentElement.moveForward(e)
'editor:move-to-end-of-screen-line': (e) -> @parentElement.parentElement.moveToEnd(e)
'editor:move-to-end-of-line': (e) -> @parentElement.parentElement.moveToEnd(e)
'editor:move-to-end-of-paragraph': (e) -> @parentElement.parentElement.moveToEnd(e)
'core:move-up': (e) -> @parentElement.parentElement.moveToStart(e)
'core:move-to-top': (e) -> @parentElement.parentElement.moveToStart()
'core:move-down': (e) -> @parentElement.parentElement.moveToEnd(e)
'core:move-to-bottom': (e) -> @parentElement.parentElement.moveToEnd(e)
'core:delete': (e) -> @parentElement.parentElement.delete(e, false)
'core:backspace': (e) -> @parentElement.parentElement.delete(e, true)
module.exports = document.registerElement 'ft-token-input', prototype: TokenInputElement.prototype | 103848 | # Copyright (c) 2015 <NAME>. All rights reserved.
FoldingTextService = require '../../foldingtext-service'
{Disposable, CompositeDisposable} = require 'atom'
TextInputElement = require './text-input-element'
class TokenInputElement extends HTMLElement
textInputElement: null
createdCallback: ->
@tokenzieRegex = /\s|,|#/
@list = document.createElement 'ol'
@appendChild @list
@textInputElement = document.createElement 'ft-text-input'
@textEditorElement = @textInputElement.textEditorElement
@textEditor = @textInputElement.textEditor
@appendChild @textInputElement
@updateLayout()
attachedCallback: ->
@updateLayout()
setTimeout =>
@updateLayout()
detachedCallback: ->
attributeChangedCallback: (attrName, oldVal, newVal) ->
###
Section: Messages to the user
###
getPlaceholderText: ->
@textInputElement.getPlaceholderText()
setPlaceholderText: (placeholderText) ->
@textInputElement.setPlaceholderText placeholderText
setMessage: (message='') ->
@textInputElement.setMessage message
setHTMLMessage: (htmlMessage='') ->
@textInputElement.setHTMLMessage htmlMessage
###
Section: Accessory Elements
###
addAccessoryElement: (element) ->
@textInputElement.addAccessoryElement element
###
Section: Text
###
getText: ->
@textInputElement.getText()
setText: (text) ->
@textInputElement.setText text
###
Section: Delegate
###
getDelegate: ->
@textInputElement.getDelegate()
setDelegate: (delegate) ->
originalDidInsertText = delegate.didInsertText?.bind(delegate)
delegate.didInsertText = (e) =>
@setSelectedToken(null)
if e.text.match(@tokenzieRegex)
@setSelectedToken(null)
@tokenizeText()
originalDidInsertText?(e)
@textInputElement.setDelegate(delegate)
###
Section: Tokens
###
getTokens: ->
tokens = []
for each in @list.children
tokens.push each.textContent
tokens
hasToken: (token) ->
!! @getElementForToken token
toggleToken: (token) ->
if @hasToken token
@deleteToken token
else
@tokenizeText token
deleteToken: (token) ->
@deleteTokenElement @getElementForToken token
getSelectedToken: ->
@getSelectedTokenElement()?._token
setSelectedToken: (token) ->
@selectTokenElement @getElementForToken token
tokenizeText: (text) ->
text ?= @getText() or ''
if text
delegate = @getDelegate()
tokens = (token for token in text.split(/\s|,|#/) when token.length > 0)
for each in tokens
delegate?.willAddToken?(each)
tokenElement = document.createElement 'li'
tokenElement.textContent = each
tokenElement._token = each
@list.appendChild(tokenElement)
delegate?.didAddToken?(each)
@setText('')
@updateLayout()
###
Section: Element Actions
###
focusTextEditor: ->
@textInputElement.focusTextEditor()
###
Section: Private
###
moveToStart: (e) ->
@tokenizeText()
@selectTokenElement @list.firstChild
moveToEnd: (e) ->
@setSelectedToken null
moveBackward: (e) ->
if @textInputElement.isCursorAtStart()
@selectPreviousTokenElement()
@tokenizeText()
moveForward: (e) ->
if @textInputElement.isCursorAtStart()
@selectNextTokenElement()
deleteTokenElement: (element) ->
return unless element
token = element.textContent
delegate = @getDelegate()
delegate?.willDeleteToken?(token)
element.parentElement.removeChild element
delegate?.didDeleteToken?(token)
@updateLayout()
delete: (e, backspace) ->
if backspace and not @textInputElement.isCursorAtStart()
return
if selected = @getSelectedTokenElement()
if backspace
@selectTokenElement(selected.previousSibling or selected.nextSibling)
else
@selectTokenElement(selected.nextSibling or selected.previousSibling)
@deleteTokenElement selected
else if backspace
@selectPreviousTokenElement()
@tokenizeText()
selectPreviousTokenElement: ->
current = @getSelectedTokenElement()
previous = current?.previousSibling
if not previous and not current
previous = @list.lastChild
if previous
@selectTokenElement(previous)
selectNextTokenElement: ->
current = @getSelectedTokenElement()
next = current?.nextSibling
@selectTokenElement(next)
selectTokenElement: (element) ->
oldSelected = @getSelectedTokenElement()
unless element is oldSelected
token = element?.textContent
delegate = @getDelegate()
delegate?.willSelectToken?(token)
oldSelected?.classList.remove 'selected'
if element
element.classList.add('selected')
@classList.add 'has-token-selected'
else
@classList.remove 'has-token-selected'
@textEditorElement.component?.presenter?.pauseCursorBlinking?() # Hack
delegate?.didSelectToken?(token)
getSelectedTokenElement: ->
for each in @list.children
if each.classList.contains 'selected'
return each
getElementForToken: (token) ->
for each in @list.children
if each._token is token
return each
updateLayout: ->
@list.style.top = null
@list.style.left = null
@list.style.width = null
@textEditorElement.style.paddingTop = null
@textEditorElement.style.paddingLeft = null
textEditorComputedStyle = window.getComputedStyle(@textEditorElement)
defaultPaddingLeft = parseFloat(textEditorComputedStyle.paddingLeft, 10)
defaultPaddingTop = parseFloat(textEditorComputedStyle.paddingTop, 10)
editorRect = @textEditorElement.getBoundingClientRect()
tokensRect = @list.getBoundingClientRect()
padTop = false
if tokensRect.width > editorRect.width
@list.style.width = editorRect.width + 'px'
tokensRect = @list.getBoundingClientRect()
padTop = true
# Vertical Align
topOffset = editorRect.top - tokensRect.top
if padTop
@textEditorElement.style.paddingTop = (tokensRect.height) + 'px'
else
topOffset += ((editorRect.height / 2) - (tokensRect.height / 2))
@list.style.top = topOffset + 'px'
# Horizontal Align
@list.style.left = defaultPaddingLeft + 'px'
if tokensRect.width
@textEditorElement.style.paddingLeft = (tokensRect.width + (defaultPaddingLeft * 1.25)) + 'px'
FoldingTextService.eventRegistery.listen 'ft-token-input > ol > li',
mousedown: (e) ->
tokenInput = @parentElement.parentElement
tokenInput.tokenizeText()
tokenInput.selectTokenElement this
e.stopImmediatePropagation()
e.stopPropagation()
e.preventDefault()
click: (e) ->
e.stopImmediatePropagation()
e.stopPropagation()
e.preventDefault()
FoldingTextService.eventRegistery.listen 'ft-token-input > ft-text-input > atom-text-editor[mini]',
mousedown: (e) ->
@parentElement.parentElement.setSelectedToken null
atom.commands.add 'ft-token-input > ft-text-input > atom-text-editor[mini]',
'editor:move-to-first-character-of-line': (e) -> @parentElement.parentElement.moveToStart(e)
'editor:move-to-beginning-of-line': (e) -> @parentElement.parentElement.moveToStart(e)
'editor:move-to-beginning-of-paragraph': (e) -> @parentElement.parentElement.moveToStart(e)
'editor:move-to-beginning-of-word': (e) -> @parentElement.parentElement.moveBackward(e)
'core:move-backward': (e) -> @parentElement.parentElement.moveBackward(e)
'core:move-left': (e) -> @parentElement.parentElement.moveBackward(e)
'editor:move-to-end-of-word': (e) -> @parentElement.parentElement.moveForward(e)
'core:move-forward': (e) -> @parentElement.parentElement.moveForward(e)
'core:move-right': (e) -> @parentElement.parentElement.moveForward(e)
'editor:move-to-end-of-screen-line': (e) -> @parentElement.parentElement.moveToEnd(e)
'editor:move-to-end-of-line': (e) -> @parentElement.parentElement.moveToEnd(e)
'editor:move-to-end-of-paragraph': (e) -> @parentElement.parentElement.moveToEnd(e)
'core:move-up': (e) -> @parentElement.parentElement.moveToStart(e)
'core:move-to-top': (e) -> @parentElement.parentElement.moveToStart()
'core:move-down': (e) -> @parentElement.parentElement.moveToEnd(e)
'core:move-to-bottom': (e) -> @parentElement.parentElement.moveToEnd(e)
'core:delete': (e) -> @parentElement.parentElement.delete(e, false)
'core:backspace': (e) -> @parentElement.parentElement.delete(e, true)
module.exports = document.registerElement 'ft-token-input', prototype: TokenInputElement.prototype | true | # Copyright (c) 2015 PI:NAME:<NAME>END_PI. All rights reserved.
FoldingTextService = require '../../foldingtext-service'
{Disposable, CompositeDisposable} = require 'atom'
TextInputElement = require './text-input-element'
class TokenInputElement extends HTMLElement
textInputElement: null
createdCallback: ->
@tokenzieRegex = /\s|,|#/
@list = document.createElement 'ol'
@appendChild @list
@textInputElement = document.createElement 'ft-text-input'
@textEditorElement = @textInputElement.textEditorElement
@textEditor = @textInputElement.textEditor
@appendChild @textInputElement
@updateLayout()
attachedCallback: ->
@updateLayout()
setTimeout =>
@updateLayout()
detachedCallback: ->
attributeChangedCallback: (attrName, oldVal, newVal) ->
###
Section: Messages to the user
###
getPlaceholderText: ->
@textInputElement.getPlaceholderText()
setPlaceholderText: (placeholderText) ->
@textInputElement.setPlaceholderText placeholderText
setMessage: (message='') ->
@textInputElement.setMessage message
setHTMLMessage: (htmlMessage='') ->
@textInputElement.setHTMLMessage htmlMessage
###
Section: Accessory Elements
###
addAccessoryElement: (element) ->
@textInputElement.addAccessoryElement element
###
Section: Text
###
getText: ->
@textInputElement.getText()
setText: (text) ->
@textInputElement.setText text
###
Section: Delegate
###
getDelegate: ->
@textInputElement.getDelegate()
setDelegate: (delegate) ->
originalDidInsertText = delegate.didInsertText?.bind(delegate)
delegate.didInsertText = (e) =>
@setSelectedToken(null)
if e.text.match(@tokenzieRegex)
@setSelectedToken(null)
@tokenizeText()
originalDidInsertText?(e)
@textInputElement.setDelegate(delegate)
###
Section: Tokens
###
getTokens: ->
tokens = []
for each in @list.children
tokens.push each.textContent
tokens
hasToken: (token) ->
!! @getElementForToken token
toggleToken: (token) ->
if @hasToken token
@deleteToken token
else
@tokenizeText token
deleteToken: (token) ->
@deleteTokenElement @getElementForToken token
getSelectedToken: ->
@getSelectedTokenElement()?._token
setSelectedToken: (token) ->
@selectTokenElement @getElementForToken token
tokenizeText: (text) ->
text ?= @getText() or ''
if text
delegate = @getDelegate()
tokens = (token for token in text.split(/\s|,|#/) when token.length > 0)
for each in tokens
delegate?.willAddToken?(each)
tokenElement = document.createElement 'li'
tokenElement.textContent = each
tokenElement._token = each
@list.appendChild(tokenElement)
delegate?.didAddToken?(each)
@setText('')
@updateLayout()
###
Section: Element Actions
###
focusTextEditor: ->
@textInputElement.focusTextEditor()
###
Section: Private
###
moveToStart: (e) ->
@tokenizeText()
@selectTokenElement @list.firstChild
moveToEnd: (e) ->
@setSelectedToken null
moveBackward: (e) ->
if @textInputElement.isCursorAtStart()
@selectPreviousTokenElement()
@tokenizeText()
moveForward: (e) ->
if @textInputElement.isCursorAtStart()
@selectNextTokenElement()
deleteTokenElement: (element) ->
return unless element
token = element.textContent
delegate = @getDelegate()
delegate?.willDeleteToken?(token)
element.parentElement.removeChild element
delegate?.didDeleteToken?(token)
@updateLayout()
delete: (e, backspace) ->
if backspace and not @textInputElement.isCursorAtStart()
return
if selected = @getSelectedTokenElement()
if backspace
@selectTokenElement(selected.previousSibling or selected.nextSibling)
else
@selectTokenElement(selected.nextSibling or selected.previousSibling)
@deleteTokenElement selected
else if backspace
@selectPreviousTokenElement()
@tokenizeText()
selectPreviousTokenElement: ->
current = @getSelectedTokenElement()
previous = current?.previousSibling
if not previous and not current
previous = @list.lastChild
if previous
@selectTokenElement(previous)
selectNextTokenElement: ->
current = @getSelectedTokenElement()
next = current?.nextSibling
@selectTokenElement(next)
selectTokenElement: (element) ->
oldSelected = @getSelectedTokenElement()
unless element is oldSelected
token = element?.textContent
delegate = @getDelegate()
delegate?.willSelectToken?(token)
oldSelected?.classList.remove 'selected'
if element
element.classList.add('selected')
@classList.add 'has-token-selected'
else
@classList.remove 'has-token-selected'
@textEditorElement.component?.presenter?.pauseCursorBlinking?() # Hack
delegate?.didSelectToken?(token)
getSelectedTokenElement: ->
for each in @list.children
if each.classList.contains 'selected'
return each
getElementForToken: (token) ->
for each in @list.children
if each._token is token
return each
updateLayout: ->
@list.style.top = null
@list.style.left = null
@list.style.width = null
@textEditorElement.style.paddingTop = null
@textEditorElement.style.paddingLeft = null
textEditorComputedStyle = window.getComputedStyle(@textEditorElement)
defaultPaddingLeft = parseFloat(textEditorComputedStyle.paddingLeft, 10)
defaultPaddingTop = parseFloat(textEditorComputedStyle.paddingTop, 10)
editorRect = @textEditorElement.getBoundingClientRect()
tokensRect = @list.getBoundingClientRect()
padTop = false
if tokensRect.width > editorRect.width
@list.style.width = editorRect.width + 'px'
tokensRect = @list.getBoundingClientRect()
padTop = true
# Vertical Align
topOffset = editorRect.top - tokensRect.top
if padTop
@textEditorElement.style.paddingTop = (tokensRect.height) + 'px'
else
topOffset += ((editorRect.height / 2) - (tokensRect.height / 2))
@list.style.top = topOffset + 'px'
# Horizontal Align
@list.style.left = defaultPaddingLeft + 'px'
if tokensRect.width
@textEditorElement.style.paddingLeft = (tokensRect.width + (defaultPaddingLeft * 1.25)) + 'px'
FoldingTextService.eventRegistery.listen 'ft-token-input > ol > li',
mousedown: (e) ->
tokenInput = @parentElement.parentElement
tokenInput.tokenizeText()
tokenInput.selectTokenElement this
e.stopImmediatePropagation()
e.stopPropagation()
e.preventDefault()
click: (e) ->
e.stopImmediatePropagation()
e.stopPropagation()
e.preventDefault()
FoldingTextService.eventRegistery.listen 'ft-token-input > ft-text-input > atom-text-editor[mini]',
mousedown: (e) ->
@parentElement.parentElement.setSelectedToken null
atom.commands.add 'ft-token-input > ft-text-input > atom-text-editor[mini]',
'editor:move-to-first-character-of-line': (e) -> @parentElement.parentElement.moveToStart(e)
'editor:move-to-beginning-of-line': (e) -> @parentElement.parentElement.moveToStart(e)
'editor:move-to-beginning-of-paragraph': (e) -> @parentElement.parentElement.moveToStart(e)
'editor:move-to-beginning-of-word': (e) -> @parentElement.parentElement.moveBackward(e)
'core:move-backward': (e) -> @parentElement.parentElement.moveBackward(e)
'core:move-left': (e) -> @parentElement.parentElement.moveBackward(e)
'editor:move-to-end-of-word': (e) -> @parentElement.parentElement.moveForward(e)
'core:move-forward': (e) -> @parentElement.parentElement.moveForward(e)
'core:move-right': (e) -> @parentElement.parentElement.moveForward(e)
'editor:move-to-end-of-screen-line': (e) -> @parentElement.parentElement.moveToEnd(e)
'editor:move-to-end-of-line': (e) -> @parentElement.parentElement.moveToEnd(e)
'editor:move-to-end-of-paragraph': (e) -> @parentElement.parentElement.moveToEnd(e)
'core:move-up': (e) -> @parentElement.parentElement.moveToStart(e)
'core:move-to-top': (e) -> @parentElement.parentElement.moveToStart()
'core:move-down': (e) -> @parentElement.parentElement.moveToEnd(e)
'core:move-to-bottom': (e) -> @parentElement.parentElement.moveToEnd(e)
'core:delete': (e) -> @parentElement.parentElement.delete(e, false)
'core:backspace': (e) -> @parentElement.parentElement.delete(e, true)
module.exports = document.registerElement 'ft-token-input', prototype: TokenInputElement.prototype |
[
{
"context": "ta.com/captionerjs/\\n\n *\\n\n * Copyright 2013-2014, Nuno Costa <nuno@francodacosta.com>\\n\n * Released under the ",
"end": 227,
"score": 0.999891459941864,
"start": 217,
"tag": "NAME",
"value": "Nuno Costa"
},
{
"context": "nerjs/\\n\n *\\n\n * Copyright 2013-2014, ... | Gruntfile.coffee | francodacosta/CaptionerJs | 4 | module.exports = (grunt) ->
grunt.initConfig
meta:
banner: '
/*!\n
* CaptionerJs | Beautiful and semantically correct captions\n
* http://francodacosta.com/captionerjs/\n
*\n
* Copyright 2013-2014, Nuno Costa <nuno@francodacosta.com>\n
* Released under the MIT license\n
* https://github.com/francodacosta/CaptionerJs/blob/master/LICENSE\n
*\n
*/'
usebanner:
dist:
options:
position: 'top',
banner: '<%= meta.banner %>'
files:
src: [ 'dist/*.js', 'dist/*.css' ]
coffee:
compileJoined:
banner: '<%= meta.banner %>'
options:
join: true
files:
'dist/CaptionerJs.js': [
'src/*.coffee'
# 'otherdirectory/*.coffee'
]
watch:
files: [ 'src/*.coffee', 'src/css/*.less' ]
tasks:
[
'default'
]
jasmine_node:
options:
forceExit: true,
match: '.',
matchall: false,
extensions: 'js',
specNameMatcher: 'Spec',
jUnit:
report: true,
savePath : "./src/test/reports/jasmine/",
useDotNotation: true,
consolidate: true
all: ['./src/test/']
less:
build:
options:
paths: ["src/css"]
banner: '<%= meta.banner %>'
files:
"dist/CaptionerJs.css": "src/css/*"
uglify:
options:
mangle:
except: ['jQuery', '$']
dist:
files:
'dist/CaptionerJs.min.js': ['dist/CaptionerJs.js']
cssmin:
combine:
files:
'dist/CaptionerJs.min.css': ['dist/CaptionerJs.css']
grunt.loadNpmTasks 'grunt-contrib-coffee'
grunt.loadNpmTasks 'grunt-contrib-watch'
grunt.loadNpmTasks 'grunt-jasmine-node'
grunt.loadNpmTasks 'grunt-contrib-less'
grunt.loadNpmTasks 'grunt-banner'
grunt.loadNpmTasks 'grunt-contrib-uglify'
grunt.loadNpmTasks 'grunt-contrib-cssmin'
grunt.registerTask 'default', ['less', 'coffee']
grunt.registerTask 'dist', ['default', 'uglify', 'cssmin','usebanner']
grunt.registerTask 'tests', 'compile and run tests', ->
grunt.config.set('coffee', grunt.config.get('coffee_tests'))
grunt.task.run('coffee')
grunt.task.run('jasmine_node')
| 111833 | module.exports = (grunt) ->
grunt.initConfig
meta:
banner: '
/*!\n
* CaptionerJs | Beautiful and semantically correct captions\n
* http://francodacosta.com/captionerjs/\n
*\n
* Copyright 2013-2014, <NAME> <<EMAIL>>\n
* Released under the MIT license\n
* https://github.com/francodacosta/CaptionerJs/blob/master/LICENSE\n
*\n
*/'
usebanner:
dist:
options:
position: 'top',
banner: '<%= meta.banner %>'
files:
src: [ 'dist/*.js', 'dist/*.css' ]
coffee:
compileJoined:
banner: '<%= meta.banner %>'
options:
join: true
files:
'dist/CaptionerJs.js': [
'src/*.coffee'
# 'otherdirectory/*.coffee'
]
watch:
files: [ 'src/*.coffee', 'src/css/*.less' ]
tasks:
[
'default'
]
jasmine_node:
options:
forceExit: true,
match: '.',
matchall: false,
extensions: 'js',
specNameMatcher: 'Spec',
jUnit:
report: true,
savePath : "./src/test/reports/jasmine/",
useDotNotation: true,
consolidate: true
all: ['./src/test/']
less:
build:
options:
paths: ["src/css"]
banner: '<%= meta.banner %>'
files:
"dist/CaptionerJs.css": "src/css/*"
uglify:
options:
mangle:
except: ['jQuery', '$']
dist:
files:
'dist/CaptionerJs.min.js': ['dist/CaptionerJs.js']
cssmin:
combine:
files:
'dist/CaptionerJs.min.css': ['dist/CaptionerJs.css']
grunt.loadNpmTasks 'grunt-contrib-coffee'
grunt.loadNpmTasks 'grunt-contrib-watch'
grunt.loadNpmTasks 'grunt-jasmine-node'
grunt.loadNpmTasks 'grunt-contrib-less'
grunt.loadNpmTasks 'grunt-banner'
grunt.loadNpmTasks 'grunt-contrib-uglify'
grunt.loadNpmTasks 'grunt-contrib-cssmin'
grunt.registerTask 'default', ['less', 'coffee']
grunt.registerTask 'dist', ['default', 'uglify', 'cssmin','usebanner']
grunt.registerTask 'tests', 'compile and run tests', ->
grunt.config.set('coffee', grunt.config.get('coffee_tests'))
grunt.task.run('coffee')
grunt.task.run('jasmine_node')
| true | module.exports = (grunt) ->
grunt.initConfig
meta:
banner: '
/*!\n
* CaptionerJs | Beautiful and semantically correct captions\n
* http://francodacosta.com/captionerjs/\n
*\n
* Copyright 2013-2014, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>\n
* Released under the MIT license\n
* https://github.com/francodacosta/CaptionerJs/blob/master/LICENSE\n
*\n
*/'
usebanner:
dist:
options:
position: 'top',
banner: '<%= meta.banner %>'
files:
src: [ 'dist/*.js', 'dist/*.css' ]
coffee:
compileJoined:
banner: '<%= meta.banner %>'
options:
join: true
files:
'dist/CaptionerJs.js': [
'src/*.coffee'
# 'otherdirectory/*.coffee'
]
watch:
files: [ 'src/*.coffee', 'src/css/*.less' ]
tasks:
[
'default'
]
jasmine_node:
options:
forceExit: true,
match: '.',
matchall: false,
extensions: 'js',
specNameMatcher: 'Spec',
jUnit:
report: true,
savePath : "./src/test/reports/jasmine/",
useDotNotation: true,
consolidate: true
all: ['./src/test/']
less:
build:
options:
paths: ["src/css"]
banner: '<%= meta.banner %>'
files:
"dist/CaptionerJs.css": "src/css/*"
uglify:
options:
mangle:
except: ['jQuery', '$']
dist:
files:
'dist/CaptionerJs.min.js': ['dist/CaptionerJs.js']
cssmin:
combine:
files:
'dist/CaptionerJs.min.css': ['dist/CaptionerJs.css']
grunt.loadNpmTasks 'grunt-contrib-coffee'
grunt.loadNpmTasks 'grunt-contrib-watch'
grunt.loadNpmTasks 'grunt-jasmine-node'
grunt.loadNpmTasks 'grunt-contrib-less'
grunt.loadNpmTasks 'grunt-banner'
grunt.loadNpmTasks 'grunt-contrib-uglify'
grunt.loadNpmTasks 'grunt-contrib-cssmin'
grunt.registerTask 'default', ['less', 'coffee']
grunt.registerTask 'dist', ['default', 'uglify', 'cssmin','usebanner']
grunt.registerTask 'tests', 'compile and run tests', ->
grunt.config.set('coffee', grunt.config.get('coffee_tests'))
grunt.task.run('coffee')
grunt.task.run('jasmine_node')
|
[
{
"context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistri",
"end": 42,
"score": 0.9998484253883362,
"start": 24,
"tag": "NAME",
"value": "Alexander Cherniuk"
},
{
"context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmai... | library/nucleus/scaled.coffee | ts33kr/granite | 6 | ###
Copyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
asciify = require "asciify"
connect = require "connect"
seaport = require "seaport"
Keygrip = require "keygrip"
Cookies = require "cookies"
logger = require "winston"
uuid = require "node-uuid"
moment = require "moment"
colors = require "colors"
assert = require "assert"
async = require "async"
nconf = require "nconf"
https = require "https"
paths = require "path"
http = require "http"
util = require "util"
fs = require "fs"
{format} = require "util"
{ServerResponse} = require "http"
{GraniteKernel} = require "./kernel"
{HttpProxy} = require "http-proxy"
# This is the descendant of the generic kernel that implements the
# scaling of the framework across an arbitrary clustered processes
# or even machines. It is built on top of a set of the Node.js based
# technologies, such as service discovery library alongside with a
# library that allows for effective proxying of the HTTP requests.
# Normally this kernel should always be preferred over Generic one!
module.exports.ScaledKernel = class ScaledKernel extends GraniteKernel
# Prepare and setup an HTTPS master server. This server is the
# proxy server that is going to consume all the HTTPS requests
# and load balance the request to some of the instances. Please
# refer to the `node-http-proxy` library for info on the proxy.
# Also see `makeForward` method for details on load balancing!
startupHttpsMaster: ->
assert _.isArray q = @queueOfHttps ?= Array()
assert _.isObject options = @resolveSslDetails()
assert _.isString host = nconf.get "master:host"
assert _.isNumber port = nconf.get "master:https"
assert registr = @makeRegistrar q, "https", undefined
assert selectr = @makeSelectors q, "https", undefined
assert forward = @makeForwarder q, "https", selectr
assert upgrade = @makeUpgraders q, "https", selectr
remove = (s) -> _.remove q, (x) -> s.uuid is x.uuid
@secureProxy = https.createServer options, forward
assert _.isObject @domain; @domain.add @secureProxy
assert @secureProxy; @secureProxy.listen port, host
@secureProxy.on "upgrade", -> upgrade arguments...
assert running = "Master HTTPS server at %s".bold
location = "#{host}:#{port}".toString().underline
logger.info running.underline.magenta, location
@spserver.on "free", (service) -> remove service
@spserver.on "register", registr; return this
# Prepare and setup an HTTP master server. This server is the
# proxy server that is going to consume all the HTTP requests
# and load balance the request to some of the instances. Please
# refer to the `node-http-proxy` library for info on the proxy.
# Also see `makeForward` method for details on load balancing!
startupHttpMaster: ->
assert _.isArray q = @queueOfHttp ?= Array()
assert _.isString host = nconf.get "master:host"
assert _.isNumber port = nconf.get "master:http"
assert registr = @makeRegistrar q, "http", undefined
assert selectr = @makeSelectors q, "http", undefined
assert forward = @makeForwarder q, "http", selectr
assert upgrade = @makeUpgraders q, "http", selectr
remove = (s) -> _.remove q, (x) -> s.uuid is x.uuid
assert @serverProxy = http.createServer forward
assert _.isObject @domain; @domain.add @serverProxy
assert @serverProxy; @serverProxy.listen port, host
@serverProxy.on "upgrade", -> upgrade arguments...
assert running = "Master HTTP server at %s".bold
location = "#{host}:#{port}".toString().underline
logger.info running.underline.magenta, location
@spserver.on "free", (service) -> remove service
@spserver.on "register", registr; return this
# This is a factory method that produces handlers invoked on
# discovering a new service on the Seaport hub. This handler
# examines the service to decide if it suits the parameters
# passed to the factory, and if so - add it to the registry
# of available services that are rotated using round-robin.
makeRegistrar: (queue, kind) -> (service) =>
config = Object https: kind is "https"
assert ids = try @constructor.identica()
compile = (s) -> "#{s.role}@#{s.version}"
return undefined unless service.kind is kind
return undefined unless compile(service) is ids
options = @resolveSslDetails() if config.https
_.extend config, https: options if config.https
where = host: service.host, port: service.port
assert merged = _.extend config, target: where
merged.target.https = service.kind is "https"
merged.target.rejectUnauthorized = false
queue.push proxy = new HttpProxy merged
assert _.isString proxy.uuid = service.uuid
proxy.on "proxyError", (err, req, res) =>
msg = "got an error talking to backend: %s"
res.writeHead 500, "a proxy backend error"
res.end format msg, err.toString(); this
# This is a factory method that produces methods that dispatch
# requests to the corresponding backend proxied server. It is
# the direct implementor of the round-robin rotation algorithm.
# Beware howeber that is also implements the sticky session algo
# based on setting and getting the correctly signed req cookies.
makeSelectors: (queue, kind) -> (request, response) =>
encrypted = request.connection.encrypted or no
assert _.isNumber ttl = nconf.get "balancer:ttl"
response.set = yes # a hack for `cookies` module
response.getHeader = (key) -> [key.toLowerCase()]
ltp = (u) -> _.find queue, (srv) -> srv.uuid is u
rrb = -> assert p = queue.shift(); queue.push p; p
sticky = "Sticky %s request %s of %s".toString()
assert url = "#{request.url}".underline.yellow
assert x = (encrypted and "HTTPS" or "HTTP").bold
assert secret = nconf.get "session:secret" or null
keygrip = new Keygrip [secret], "sha256", "hex"
cookies = new Cookies request, response, keygrip
xbackend = cookies.get "xbackend", signed: yes
return rrb() unless nconf.get "balancer:sticky"
assert _.isObject proxy = ltp(xbackend) or rrb()
configure = signed: yes, overwrite: yes, httpOnly: no
configure.expires = moment().add("s", ttl).toDate()
s = cookies.set "xbackend", proxy.uuid, configure
a = "#{proxy.target.host}:#{proxy.target.port}"
assert a = "#{a.toLowerCase().underline.yellow}"
logger.debug sticky, x.bold, url, a if xbackend
assert s.response is response; return proxy
# This is a factory method that produces request forwarders.
# These are directly responsible for proxying an HTTP request
# from the master server (frontend) to actual server (backend)
# that does the job of handling the request. The forwarder is
# also responsible for rotating (round-robin) servers queue!
makeForwarder: (queue, kind, select) -> (xrequest, xresponse) =>
assert request = _.find arguments, "connection"
assert response = _.find arguments, "writeHead"
encrypted = request.connection.encrypted or false
assert u = try "#{request.url}".underline.yellow
assert x = (encrypted and "HTTPS" or "HTTP").bold
reason = "no instances found behind a frontend"
msg = "the frontend has no instances to talk to"
assert _.isArray(queue), "got invalid proxy queue"
response.writeHead 504, reason if _.isEmpty queue
return response.end(msg) and no if _.isEmpty queue
assert proxy = try select.apply this, arguments
a = "#{proxy.target.host}:#{proxy.target.port}"
assert a = "#{a.toLowerCase().underline.yellow}"
logger.debug "Proxy %s request %s to %s", x, u, a
return proxy.proxyRequest arguments...
# This is a factory method that that produces the specialized
# request handler that is fired when an `upgrade` is requested
# on one of the master servers. This is the functionality that
# is required for WebSockets and other similar transports to
# perform its operation correctly in a distributed environment.
makeUpgraders: (queue, kind, select) -> (xrequest, xsocket) =>
assert request = _.find arguments, "connection"
response = (try _.find arguments, "localAddress")
response?.writeHead = (ServerResponse::writeHead)
encrypted = request.connection.encrypted or false
assert u = try "#{request.url}".underline.yellow
assert x = (encrypted and "HTTPS" or "HTTP").bold
msg = "the frontend has no instances to talk to"
assert _.isArray(queue), "got invalid proxy queue"
reason = r = "no instances found behind a frontend"
try response?.writeHead 504, r if _.isEmpty queue
return response?.end(msg) and no if _.isEmpty queue
assert proxy = try select.apply this, arguments
a = "#{proxy.target.host}:#{proxy.target.port}"
assert a = "#{a.toLowerCase().underline.yellow}"
logger.debug "Proxy %s upgrade %s to %s", x, u, a
return proxy.proxyWebSocketRequest arguments...
# Create and launch a Seaport server in the current kernel. It
# draws the configuration from the same key as Seaport client
# uses. This routine should only be invoked when the kernel is
# launched in the master mode, generally. The method wires in
# some handlers into the Seaport to track hosts come and go.
createSeaportServer: ->
assert r = "New %s service %s at %s".green
assert f = "No %s service %s at %s".yellow
create = "Created the Seaport server at %s"
assert identica = try @constructor.identica()
assert _.isString host = nconf.get "hub:host"
assert _.isNumber port = nconf.get "hub:port"
assert _.isObject opts = nconf.get "hub:opts"
k = (srv) -> "#{srv.kind}".toUpperCase().bold
c = (srv) -> "#{srv.role}@#{srv.version}".bold
l = (srv) -> "#{srv.host}:#{srv.port}".underline
log = (m, s) -> logger.info m, k(s), c(s), l(s)
match = (s) -> "#{s.role}@#{s.version}" is identica
assert @spserver = seaport.createServer opts or {}
assert _.isObject @domain; try @domain.add @spserver
logger.info create.magenta, l(host: host, port: port)
@spserver.on "register", (s) -> log r, s if match s
@spserver.on "free", (s) -> log f, s if match s
try @spserver.listen port, host catch error
message = "Seaport server failed\r\n%s"
logger.error message.red, error.stack
return process.exit -1
# Setup and launch either HTTP or HTTPS servers to listen at
# the configured addresses and ports. This method reads up the
# scoping configuration in order to obtain the data necessary
# for instantiating, configuring and launching up the servers.
# This version goes to the Seaport hub to obtain the options!
startupHttpsServer: ->
assert type = "https".toUpperCase().bold
assert _.isObject config = try nconf.get()
assert _.isObject(@seaport), "got no seaport"
msg = "Got #{type} port from the Seaport: %s"
assert identica = @constructor.identica()
cfg = config: config, identica: identica
_.extend cfg, host: try config.server.host
_.extend cfg, uuid: uuid.v4(), kind: "https"
_.extend cfg, token: @token or undefined
record = @seaport.register identica, cfg
assert _.isNumber(record), "got mistaken"
logger.info msg.green, "#{record}".bold
try config.server.https = record or null
try nconf.defaults config; return super
# Setup and launch either HTTP or HTTPS servers to listen at
# the configured addresses and ports. This method reads up the
# scoping configuration in order to obtain the data necessary
# for instantiating, configuring and launching up the servers.
# This version goes to the Seaport hub to obtain the options!
startupHttpServer: ->
assert type = "http".toUpperCase().bold
assert _.isObject config = try nconf.get()
assert _.isObject(@seaport), "got no seaport"
msg = "Got #{type} port from the Seaport: %s"
assert identica = @constructor.identica()
cfg = config: config, identica: identica
_.extend cfg, host: try config.server.host
_.extend cfg, uuid: uuid.v4(), kind: "http"
_.extend cfg, token: @token or undefined
record = @seaport.register identica, cfg
assert _.isNumber(record), "got mistaken"
logger.info msg.green, "#{record}".bold
try config.server.http = record or null
try nconf.defaults config; return super
# A configuration routine that ensures the scope config has the
# Seaport hub related configuration data. If so, it proceeds to
# retrieving that info and using it to locate and connect to a
# Seaport hub, which is then installed as the kernel instance
# variable, so that it can be accessed by the other routines.
@configure "access the service Seaport hub", (next) ->
nh = "no Seaport host found in the configuration"
np = "no Seaport port found in the configuration"
nt = "no Seaport opts found in the configuration"
brokenLib = "the Seaport library seems to be broken"
assert _.isString(host = nconf.get "hub:host"), nh
assert _.isNumber(port = nconf.get "hub:port"), np
assert _.isObject(opts = nconf.get "hub:opts"), nt
assert _.isFunction(seaport?.connect), brokenLib
this.seaport = seaport.connect host, port, opts
assert _.isObject(@seaport), "seaport failed"
assert @seaport.register?, "a broken seaport"
shl = "#{host}:#{port}".toString().underline
msg = "Locate a Seaport hub at #{shl}".blue
logger.info msg; return next undefined
# The kernel preemption routine is called once the kernel has
# passed the initial launching and configuration phase, but is
# yet to start up the router, connect services and instantiate
# an actual application. This method gets passes continuation
# that does that. The method can either invoke it or omit it.
kernelPreemption: (continuation) ->
assert identify = try @constructor.identify()
assert _.isObject(@options), "got no options"
either = @options.master or @options.instance
assert either, "no master and no instance mode"
nmast = "incorrect master configuration object"
message = "Kernel preemption at %s being invoked"
logger.debug message.red, (try identify.bold)
return continuation() unless @options.master
msg = "Enabling %s operation mode for kernel"
log = (mode) -> logger.warn msg.green, mode.bold
log "instance".toUpperCase() if @options.instance
log "master".toUpperCase() if @options.master
assert _.isObject(nconf.get "master"), nmast
assert not _.isEmpty @createSeaportServer()
assert not _.isEmpty @startupHttpsMaster()
assert not _.isEmpty @startupHttpMaster()
continuation.call @ if @options.instance
# Shutdown the kernel instance. This includes shutting down both
# HTTP and HTTPS server that may be running, stopping the router
# and unregistering all the services as a precauting. After that
# the scope is being dispersed and some events are being emited.
# This implementaton cleans up some of the scalability resources.
shutdownKernel: (reason, eol=yes) ->
terminator = (proxy) -> try proxy.close()
util.puts require("os").EOL if (eol or false)
this.emit "killed-scaled-kernel", arguments...
message = "Graceful shutdown of Scaled kernel"
log = (message) -> logger.debug message.yellow
log "Closing the Seaport servers" if @spserver
log "Closing the server (HTTP) proxy instance"
log "Closing the secure (HTTPS) proxy instance"
log "Terminating remote proxies in the queues"
try @spserver.close() if (@spserver) # Seaport
try @serverProxy.close() if this.serverProxy?
try @secureProxy.close() if this.secureProxy?
_.each @queueOfHttps or Array(), terminator
_.each @queueOfHttp or Array(), terminator
logger.warn message.red; super reason, no
| 203707 | ###
Copyright (c) 2013, <NAME> <<EMAIL>>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
asciify = require "asciify"
connect = require "connect"
seaport = require "seaport"
Keygrip = require "keygrip"
Cookies = require "cookies"
logger = require "winston"
uuid = require "node-uuid"
moment = require "moment"
colors = require "colors"
assert = require "assert"
async = require "async"
nconf = require "nconf"
https = require "https"
paths = require "path"
http = require "http"
util = require "util"
fs = require "fs"
{format} = require "util"
{ServerResponse} = require "http"
{GraniteKernel} = require "./kernel"
{HttpProxy} = require "http-proxy"
# This is the descendant of the generic kernel that implements the
# scaling of the framework across an arbitrary clustered processes
# or even machines. It is built on top of a set of the Node.js based
# technologies, such as service discovery library alongside with a
# library that allows for effective proxying of the HTTP requests.
# Normally this kernel should always be preferred over Generic one!
module.exports.ScaledKernel = class ScaledKernel extends GraniteKernel
# Prepare and setup an HTTPS master server. This server is the
# proxy server that is going to consume all the HTTPS requests
# and load balance the request to some of the instances. Please
# refer to the `node-http-proxy` library for info on the proxy.
# Also see `makeForward` method for details on load balancing!
startupHttpsMaster: ->
assert _.isArray q = @queueOfHttps ?= Array()
assert _.isObject options = @resolveSslDetails()
assert _.isString host = nconf.get "master:host"
assert _.isNumber port = nconf.get "master:https"
assert registr = @makeRegistrar q, "https", undefined
assert selectr = @makeSelectors q, "https", undefined
assert forward = @makeForwarder q, "https", selectr
assert upgrade = @makeUpgraders q, "https", selectr
remove = (s) -> _.remove q, (x) -> s.uuid is x.uuid
@secureProxy = https.createServer options, forward
assert _.isObject @domain; @domain.add @secureProxy
assert @secureProxy; @secureProxy.listen port, host
@secureProxy.on "upgrade", -> upgrade arguments...
assert running = "Master HTTPS server at %s".bold
location = "#{host}:#{port}".toString().underline
logger.info running.underline.magenta, location
@spserver.on "free", (service) -> remove service
@spserver.on "register", registr; return this
# Prepare and setup an HTTP master server. This server is the
# proxy server that is going to consume all the HTTP requests
# and load balance the request to some of the instances. Please
# refer to the `node-http-proxy` library for info on the proxy.
# Also see `makeForward` method for details on load balancing!
startupHttpMaster: ->
assert _.isArray q = @queueOfHttp ?= Array()
assert _.isString host = nconf.get "master:host"
assert _.isNumber port = nconf.get "master:http"
assert registr = @makeRegistrar q, "http", undefined
assert selectr = @makeSelectors q, "http", undefined
assert forward = @makeForwarder q, "http", selectr
assert upgrade = @makeUpgraders q, "http", selectr
remove = (s) -> _.remove q, (x) -> s.uuid is x.uuid
assert @serverProxy = http.createServer forward
assert _.isObject @domain; @domain.add @serverProxy
assert @serverProxy; @serverProxy.listen port, host
@serverProxy.on "upgrade", -> upgrade arguments...
assert running = "Master HTTP server at %s".bold
location = "#{host}:#{port}".toString().underline
logger.info running.underline.magenta, location
@spserver.on "free", (service) -> remove service
@spserver.on "register", registr; return this
# This is a factory method that produces handlers invoked on
# discovering a new service on the Seaport hub. This handler
# examines the service to decide if it suits the parameters
# passed to the factory, and if so - add it to the registry
# of available services that are rotated using round-robin.
makeRegistrar: (queue, kind) -> (service) =>
config = Object https: kind is "https"
assert ids = try @constructor.identica()
compile = (s) -> "#{s.role}@#{s.version}"
return undefined unless service.kind is kind
return undefined unless compile(service) is ids
options = @resolveSslDetails() if config.https
_.extend config, https: options if config.https
where = host: service.host, port: service.port
assert merged = _.extend config, target: where
merged.target.https = service.kind is "https"
merged.target.rejectUnauthorized = false
queue.push proxy = new HttpProxy merged
assert _.isString proxy.uuid = service.uuid
proxy.on "proxyError", (err, req, res) =>
msg = "got an error talking to backend: %s"
res.writeHead 500, "a proxy backend error"
res.end format msg, err.toString(); this
# This is a factory method that produces methods that dispatch
# requests to the corresponding backend proxied server. It is
# the direct implementor of the round-robin rotation algorithm.
# Beware howeber that is also implements the sticky session algo
# based on setting and getting the correctly signed req cookies.
makeSelectors: (queue, kind) -> (request, response) =>
encrypted = request.connection.encrypted or no
assert _.isNumber ttl = nconf.get "balancer:ttl"
response.set = yes # a hack for `cookies` module
response.getHeader = (key) -> [key.toLowerCase()]
ltp = (u) -> _.find queue, (srv) -> srv.uuid is u
rrb = -> assert p = queue.shift(); queue.push p; p
sticky = "Sticky %s request %s of %s".toString()
assert url = "#{request.url}".underline.yellow
assert x = (encrypted and "HTTPS" or "HTTP").bold
assert secret = nconf.get "session:secret" or null
keygrip = new Keygrip [secret], "sha256", "hex"
cookies = new Cookies request, response, keygrip
xbackend = cookies.get "xbackend", signed: yes
return rrb() unless nconf.get "balancer:sticky"
assert _.isObject proxy = ltp(xbackend) or rrb()
configure = signed: yes, overwrite: yes, httpOnly: no
configure.expires = moment().add("s", ttl).toDate()
s = cookies.set "xbackend", proxy.uuid, configure
a = "#{proxy.target.host}:#{proxy.target.port}"
assert a = "#{a.toLowerCase().underline.yellow}"
logger.debug sticky, x.bold, url, a if xbackend
assert s.response is response; return proxy
# This is a factory method that produces request forwarders.
# These are directly responsible for proxying an HTTP request
# from the master server (frontend) to actual server (backend)
# that does the job of handling the request. The forwarder is
# also responsible for rotating (round-robin) servers queue!
makeForwarder: (queue, kind, select) -> (xrequest, xresponse) =>
assert request = _.find arguments, "connection"
assert response = _.find arguments, "writeHead"
encrypted = request.connection.encrypted or false
assert u = try "#{request.url}".underline.yellow
assert x = (encrypted and "HTTPS" or "HTTP").bold
reason = "no instances found behind a frontend"
msg = "the frontend has no instances to talk to"
assert _.isArray(queue), "got invalid proxy queue"
response.writeHead 504, reason if _.isEmpty queue
return response.end(msg) and no if _.isEmpty queue
assert proxy = try select.apply this, arguments
a = "#{proxy.target.host}:#{proxy.target.port}"
assert a = "#{a.toLowerCase().underline.yellow}"
logger.debug "Proxy %s request %s to %s", x, u, a
return proxy.proxyRequest arguments...
# This is a factory method that that produces the specialized
# request handler that is fired when an `upgrade` is requested
# on one of the master servers. This is the functionality that
# is required for WebSockets and other similar transports to
# perform its operation correctly in a distributed environment.
makeUpgraders: (queue, kind, select) -> (xrequest, xsocket) =>
assert request = _.find arguments, "connection"
response = (try _.find arguments, "localAddress")
response?.writeHead = (ServerResponse::writeHead)
encrypted = request.connection.encrypted or false
assert u = try "#{request.url}".underline.yellow
assert x = (encrypted and "HTTPS" or "HTTP").bold
msg = "the frontend has no instances to talk to"
assert _.isArray(queue), "got invalid proxy queue"
reason = r = "no instances found behind a frontend"
try response?.writeHead 504, r if _.isEmpty queue
return response?.end(msg) and no if _.isEmpty queue
assert proxy = try select.apply this, arguments
a = "#{proxy.target.host}:#{proxy.target.port}"
assert a = "#{a.toLowerCase().underline.yellow}"
logger.debug "Proxy %s upgrade %s to %s", x, u, a
return proxy.proxyWebSocketRequest arguments...
# Create and launch a Seaport server in the current kernel. It
# draws the configuration from the same key as Seaport client
# uses. This routine should only be invoked when the kernel is
# launched in the master mode, generally. The method wires in
# some handlers into the Seaport to track hosts come and go.
createSeaportServer: ->
assert r = "New %s service %s at %s".green
assert f = "No %s service %s at %s".yellow
create = "Created the Seaport server at %s"
assert identica = try @constructor.identica()
assert _.isString host = nconf.get "hub:host"
assert _.isNumber port = nconf.get "hub:port"
assert _.isObject opts = nconf.get "hub:opts"
k = (srv) -> "#{srv.kind}".toUpperCase().bold
c = (srv) -> "#{srv.role}@#{srv.version}".bold
l = (srv) -> "#{srv.host}:#{srv.port}".underline
log = (m, s) -> logger.info m, k(s), c(s), l(s)
match = (s) -> "#{s.role}@#{s.version}" is identica
assert @spserver = seaport.createServer opts or {}
assert _.isObject @domain; try @domain.add @spserver
logger.info create.magenta, l(host: host, port: port)
@spserver.on "register", (s) -> log r, s if match s
@spserver.on "free", (s) -> log f, s if match s
try @spserver.listen port, host catch error
message = "Seaport server failed\r\n%s"
logger.error message.red, error.stack
return process.exit -1
# Setup and launch either HTTP or HTTPS servers to listen at
# the configured addresses and ports. This method reads up the
# scoping configuration in order to obtain the data necessary
# for instantiating, configuring and launching up the servers.
# This version goes to the Seaport hub to obtain the options!
startupHttpsServer: ->
assert type = "https".toUpperCase().bold
assert _.isObject config = try nconf.get()
assert _.isObject(@seaport), "got no seaport"
msg = "Got #{type} port from the Seaport: %s"
assert identica = @constructor.identica()
cfg = config: config, identica: identica
_.extend cfg, host: try config.server.host
_.extend cfg, uuid: uuid.v4(), kind: "https"
_.extend cfg, token: @token or undefined
record = @seaport.register identica, cfg
assert _.isNumber(record), "got mistaken"
logger.info msg.green, "#{record}".bold
try config.server.https = record or null
try nconf.defaults config; return super
# Setup and launch either HTTP or HTTPS servers to listen at
# the configured addresses and ports. This method reads up the
# scoping configuration in order to obtain the data necessary
# for instantiating, configuring and launching up the servers.
# This version goes to the Seaport hub to obtain the options!
startupHttpServer: ->
assert type = "http".toUpperCase().bold
assert _.isObject config = try nconf.get()
assert _.isObject(@seaport), "got no seaport"
msg = "Got #{type} port from the Seaport: %s"
assert identica = @constructor.identica()
cfg = config: config, identica: identica
_.extend cfg, host: try config.server.host
_.extend cfg, uuid: uuid.v4(), kind: "http"
_.extend cfg, token: @token or undefined
record = @seaport.register identica, cfg
assert _.isNumber(record), "got mistaken"
logger.info msg.green, "#{record}".bold
try config.server.http = record or null
try nconf.defaults config; return super
# A configuration routine that ensures the scope config has the
# Seaport hub related configuration data. If so, it proceeds to
# retrieving that info and using it to locate and connect to a
# Seaport hub, which is then installed as the kernel instance
# variable, so that it can be accessed by the other routines.
@configure "access the service Seaport hub", (next) ->
nh = "no Seaport host found in the configuration"
np = "no Seaport port found in the configuration"
nt = "no Seaport opts found in the configuration"
brokenLib = "the Seaport library seems to be broken"
assert _.isString(host = nconf.get "hub:host"), nh
assert _.isNumber(port = nconf.get "hub:port"), np
assert _.isObject(opts = nconf.get "hub:opts"), nt
assert _.isFunction(seaport?.connect), brokenLib
this.seaport = seaport.connect host, port, opts
assert _.isObject(@seaport), "seaport failed"
assert @seaport.register?, "a broken seaport"
shl = "#{host}:#{port}".toString().underline
msg = "Locate a Seaport hub at #{shl}".blue
logger.info msg; return next undefined
# The kernel preemption routine is called once the kernel has
# passed the initial launching and configuration phase, but is
# yet to start up the router, connect services and instantiate
# an actual application. This method gets passes continuation
# that does that. The method can either invoke it or omit it.
kernelPreemption: (continuation) ->
assert identify = try @constructor.identify()
assert _.isObject(@options), "got no options"
either = @options.master or @options.instance
assert either, "no master and no instance mode"
nmast = "incorrect master configuration object"
message = "Kernel preemption at %s being invoked"
logger.debug message.red, (try identify.bold)
return continuation() unless @options.master
msg = "Enabling %s operation mode for kernel"
log = (mode) -> logger.warn msg.green, mode.bold
log "instance".toUpperCase() if @options.instance
log "master".toUpperCase() if @options.master
assert _.isObject(nconf.get "master"), nmast
assert not _.isEmpty @createSeaportServer()
assert not _.isEmpty @startupHttpsMaster()
assert not _.isEmpty @startupHttpMaster()
continuation.call @ if @options.instance
# Shutdown the kernel instance. This includes shutting down both
# HTTP and HTTPS server that may be running, stopping the router
# and unregistering all the services as a precauting. After that
# the scope is being dispersed and some events are being emited.
# This implementaton cleans up some of the scalability resources.
shutdownKernel: (reason, eol=yes) ->
terminator = (proxy) -> try proxy.close()
util.puts require("os").EOL if (eol or false)
this.emit "killed-scaled-kernel", arguments...
message = "Graceful shutdown of Scaled kernel"
log = (message) -> logger.debug message.yellow
log "Closing the Seaport servers" if @spserver
log "Closing the server (HTTP) proxy instance"
log "Closing the secure (HTTPS) proxy instance"
log "Terminating remote proxies in the queues"
try @spserver.close() if (@spserver) # Seaport
try @serverProxy.close() if this.serverProxy?
try @secureProxy.close() if this.secureProxy?
_.each @queueOfHttps or Array(), terminator
_.each @queueOfHttp or Array(), terminator
logger.warn message.red; super reason, no
| true | ###
Copyright (c) 2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
asciify = require "asciify"
connect = require "connect"
seaport = require "seaport"
Keygrip = require "keygrip"
Cookies = require "cookies"
logger = require "winston"
uuid = require "node-uuid"
moment = require "moment"
colors = require "colors"
assert = require "assert"
async = require "async"
nconf = require "nconf"
https = require "https"
paths = require "path"
http = require "http"
util = require "util"
fs = require "fs"
{format} = require "util"
{ServerResponse} = require "http"
{GraniteKernel} = require "./kernel"
{HttpProxy} = require "http-proxy"
# This is the descendant of the generic kernel that implements the
# scaling of the framework across an arbitrary clustered processes
# or even machines. It is built on top of a set of the Node.js based
# technologies, such as service discovery library alongside with a
# library that allows for effective proxying of the HTTP requests.
# Normally this kernel should always be preferred over Generic one!
module.exports.ScaledKernel = class ScaledKernel extends GraniteKernel
# Prepare and setup an HTTPS master server. This server is the
# proxy server that is going to consume all the HTTPS requests
# and load balance the request to some of the instances. Please
# refer to the `node-http-proxy` library for info on the proxy.
# Also see `makeForward` method for details on load balancing!
startupHttpsMaster: ->
assert _.isArray q = @queueOfHttps ?= Array()
assert _.isObject options = @resolveSslDetails()
assert _.isString host = nconf.get "master:host"
assert _.isNumber port = nconf.get "master:https"
assert registr = @makeRegistrar q, "https", undefined
assert selectr = @makeSelectors q, "https", undefined
assert forward = @makeForwarder q, "https", selectr
assert upgrade = @makeUpgraders q, "https", selectr
remove = (s) -> _.remove q, (x) -> s.uuid is x.uuid
@secureProxy = https.createServer options, forward
assert _.isObject @domain; @domain.add @secureProxy
assert @secureProxy; @secureProxy.listen port, host
@secureProxy.on "upgrade", -> upgrade arguments...
assert running = "Master HTTPS server at %s".bold
location = "#{host}:#{port}".toString().underline
logger.info running.underline.magenta, location
@spserver.on "free", (service) -> remove service
@spserver.on "register", registr; return this
# Prepare and setup an HTTP master server. This server is the
# proxy server that is going to consume all the HTTP requests
# and load balance the request to some of the instances. Please
# refer to the `node-http-proxy` library for info on the proxy.
# Also see `makeForward` method for details on load balancing!
startupHttpMaster: ->
assert _.isArray q = @queueOfHttp ?= Array()
assert _.isString host = nconf.get "master:host"
assert _.isNumber port = nconf.get "master:http"
assert registr = @makeRegistrar q, "http", undefined
assert selectr = @makeSelectors q, "http", undefined
assert forward = @makeForwarder q, "http", selectr
assert upgrade = @makeUpgraders q, "http", selectr
remove = (s) -> _.remove q, (x) -> s.uuid is x.uuid
assert @serverProxy = http.createServer forward
assert _.isObject @domain; @domain.add @serverProxy
assert @serverProxy; @serverProxy.listen port, host
@serverProxy.on "upgrade", -> upgrade arguments...
assert running = "Master HTTP server at %s".bold
location = "#{host}:#{port}".toString().underline
logger.info running.underline.magenta, location
@spserver.on "free", (service) -> remove service
@spserver.on "register", registr; return this
# This is a factory method that produces handlers invoked on
# discovering a new service on the Seaport hub. This handler
# examines the service to decide if it suits the parameters
# passed to the factory, and if so - add it to the registry
# of available services that are rotated using round-robin.
makeRegistrar: (queue, kind) -> (service) =>
config = Object https: kind is "https"
assert ids = try @constructor.identica()
compile = (s) -> "#{s.role}@#{s.version}"
return undefined unless service.kind is kind
return undefined unless compile(service) is ids
options = @resolveSslDetails() if config.https
_.extend config, https: options if config.https
where = host: service.host, port: service.port
assert merged = _.extend config, target: where
merged.target.https = service.kind is "https"
merged.target.rejectUnauthorized = false
queue.push proxy = new HttpProxy merged
assert _.isString proxy.uuid = service.uuid
proxy.on "proxyError", (err, req, res) =>
msg = "got an error talking to backend: %s"
res.writeHead 500, "a proxy backend error"
res.end format msg, err.toString(); this
# This is a factory method that produces methods that dispatch
# requests to the corresponding backend proxied server. It is
# the direct implementor of the round-robin rotation algorithm.
# Beware howeber that is also implements the sticky session algo
# based on setting and getting the correctly signed req cookies.
makeSelectors: (queue, kind) -> (request, response) =>
encrypted = request.connection.encrypted or no
assert _.isNumber ttl = nconf.get "balancer:ttl"
response.set = yes # a hack for `cookies` module
response.getHeader = (key) -> [key.toLowerCase()]
ltp = (u) -> _.find queue, (srv) -> srv.uuid is u
rrb = -> assert p = queue.shift(); queue.push p; p
sticky = "Sticky %s request %s of %s".toString()
assert url = "#{request.url}".underline.yellow
assert x = (encrypted and "HTTPS" or "HTTP").bold
assert secret = nconf.get "session:secret" or null
keygrip = new Keygrip [secret], "sha256", "hex"
cookies = new Cookies request, response, keygrip
xbackend = cookies.get "xbackend", signed: yes
return rrb() unless nconf.get "balancer:sticky"
assert _.isObject proxy = ltp(xbackend) or rrb()
configure = signed: yes, overwrite: yes, httpOnly: no
configure.expires = moment().add("s", ttl).toDate()
s = cookies.set "xbackend", proxy.uuid, configure
a = "#{proxy.target.host}:#{proxy.target.port}"
assert a = "#{a.toLowerCase().underline.yellow}"
logger.debug sticky, x.bold, url, a if xbackend
assert s.response is response; return proxy
# This is a factory method that produces request forwarders.
# These are directly responsible for proxying an HTTP request
# from the master server (frontend) to actual server (backend)
# that does the job of handling the request. The forwarder is
# also responsible for rotating (round-robin) servers queue!
makeForwarder: (queue, kind, select) -> (xrequest, xresponse) =>
assert request = _.find arguments, "connection"
assert response = _.find arguments, "writeHead"
encrypted = request.connection.encrypted or false
assert u = try "#{request.url}".underline.yellow
assert x = (encrypted and "HTTPS" or "HTTP").bold
reason = "no instances found behind a frontend"
msg = "the frontend has no instances to talk to"
assert _.isArray(queue), "got invalid proxy queue"
response.writeHead 504, reason if _.isEmpty queue
return response.end(msg) and no if _.isEmpty queue
assert proxy = try select.apply this, arguments
a = "#{proxy.target.host}:#{proxy.target.port}"
assert a = "#{a.toLowerCase().underline.yellow}"
logger.debug "Proxy %s request %s to %s", x, u, a
return proxy.proxyRequest arguments...
# This is a factory method that that produces the specialized
# request handler that is fired when an `upgrade` is requested
# on one of the master servers. This is the functionality that
# is required for WebSockets and other similar transports to
# perform its operation correctly in a distributed environment.
makeUpgraders: (queue, kind, select) -> (xrequest, xsocket) =>
assert request = _.find arguments, "connection"
response = (try _.find arguments, "localAddress")
response?.writeHead = (ServerResponse::writeHead)
encrypted = request.connection.encrypted or false
assert u = try "#{request.url}".underline.yellow
assert x = (encrypted and "HTTPS" or "HTTP").bold
msg = "the frontend has no instances to talk to"
assert _.isArray(queue), "got invalid proxy queue"
reason = r = "no instances found behind a frontend"
try response?.writeHead 504, r if _.isEmpty queue
return response?.end(msg) and no if _.isEmpty queue
assert proxy = try select.apply this, arguments
a = "#{proxy.target.host}:#{proxy.target.port}"
assert a = "#{a.toLowerCase().underline.yellow}"
logger.debug "Proxy %s upgrade %s to %s", x, u, a
return proxy.proxyWebSocketRequest arguments...
# Create and launch a Seaport server in the current kernel. It
# draws the configuration from the same key as Seaport client
# uses. This routine should only be invoked when the kernel is
# launched in the master mode, generally. The method wires in
# some handlers into the Seaport to track hosts come and go.
createSeaportServer: ->
assert r = "New %s service %s at %s".green
assert f = "No %s service %s at %s".yellow
create = "Created the Seaport server at %s"
assert identica = try @constructor.identica()
assert _.isString host = nconf.get "hub:host"
assert _.isNumber port = nconf.get "hub:port"
assert _.isObject opts = nconf.get "hub:opts"
k = (srv) -> "#{srv.kind}".toUpperCase().bold
c = (srv) -> "#{srv.role}@#{srv.version}".bold
l = (srv) -> "#{srv.host}:#{srv.port}".underline
log = (m, s) -> logger.info m, k(s), c(s), l(s)
match = (s) -> "#{s.role}@#{s.version}" is identica
assert @spserver = seaport.createServer opts or {}
assert _.isObject @domain; try @domain.add @spserver
logger.info create.magenta, l(host: host, port: port)
@spserver.on "register", (s) -> log r, s if match s
@spserver.on "free", (s) -> log f, s if match s
try @spserver.listen port, host catch error
message = "Seaport server failed\r\n%s"
logger.error message.red, error.stack
return process.exit -1
# Setup and launch either HTTP or HTTPS servers to listen at
# the configured addresses and ports. This method reads up the
# scoping configuration in order to obtain the data necessary
# for instantiating, configuring and launching up the servers.
# This version goes to the Seaport hub to obtain the options!
startupHttpsServer: ->
assert type = "https".toUpperCase().bold
assert _.isObject config = try nconf.get()
assert _.isObject(@seaport), "got no seaport"
msg = "Got #{type} port from the Seaport: %s"
assert identica = @constructor.identica()
cfg = config: config, identica: identica
_.extend cfg, host: try config.server.host
_.extend cfg, uuid: uuid.v4(), kind: "https"
_.extend cfg, token: @token or undefined
record = @seaport.register identica, cfg
assert _.isNumber(record), "got mistaken"
logger.info msg.green, "#{record}".bold
try config.server.https = record or null
try nconf.defaults config; return super
# Setup and launch either HTTP or HTTPS servers to listen at
# the configured addresses and ports. This method reads up the
# scoping configuration in order to obtain the data necessary
# for instantiating, configuring and launching up the servers.
# This version goes to the Seaport hub to obtain the options!
startupHttpServer: ->
assert type = "http".toUpperCase().bold
assert _.isObject config = try nconf.get()
assert _.isObject(@seaport), "got no seaport"
msg = "Got #{type} port from the Seaport: %s"
assert identica = @constructor.identica()
cfg = config: config, identica: identica
_.extend cfg, host: try config.server.host
_.extend cfg, uuid: uuid.v4(), kind: "http"
_.extend cfg, token: @token or undefined
record = @seaport.register identica, cfg
assert _.isNumber(record), "got mistaken"
logger.info msg.green, "#{record}".bold
try config.server.http = record or null
try nconf.defaults config; return super
# A configuration routine that ensures the scope config has the
# Seaport hub related configuration data. If so, it proceeds to
# retrieving that info and using it to locate and connect to a
# Seaport hub, which is then installed as the kernel instance
# variable, so that it can be accessed by the other routines.
@configure "access the service Seaport hub", (next) ->
nh = "no Seaport host found in the configuration"
np = "no Seaport port found in the configuration"
nt = "no Seaport opts found in the configuration"
brokenLib = "the Seaport library seems to be broken"
assert _.isString(host = nconf.get "hub:host"), nh
assert _.isNumber(port = nconf.get "hub:port"), np
assert _.isObject(opts = nconf.get "hub:opts"), nt
assert _.isFunction(seaport?.connect), brokenLib
this.seaport = seaport.connect host, port, opts
assert _.isObject(@seaport), "seaport failed"
assert @seaport.register?, "a broken seaport"
shl = "#{host}:#{port}".toString().underline
msg = "Locate a Seaport hub at #{shl}".blue
logger.info msg; return next undefined
# The kernel preemption routine is called once the kernel has
# passed the initial launching and configuration phase, but is
# yet to start up the router, connect services and instantiate
# an actual application. This method gets passes continuation
# that does that. The method can either invoke it or omit it.
kernelPreemption: (continuation) ->
assert identify = try @constructor.identify()
assert _.isObject(@options), "got no options"
either = @options.master or @options.instance
assert either, "no master and no instance mode"
nmast = "incorrect master configuration object"
message = "Kernel preemption at %s being invoked"
logger.debug message.red, (try identify.bold)
return continuation() unless @options.master
msg = "Enabling %s operation mode for kernel"
log = (mode) -> logger.warn msg.green, mode.bold
log "instance".toUpperCase() if @options.instance
log "master".toUpperCase() if @options.master
assert _.isObject(nconf.get "master"), nmast
assert not _.isEmpty @createSeaportServer()
assert not _.isEmpty @startupHttpsMaster()
assert not _.isEmpty @startupHttpMaster()
continuation.call @ if @options.instance
# Shutdown the kernel instance. This includes shutting down both
# HTTP and HTTPS server that may be running, stopping the router
# and unregistering all the services as a precauting. After that
# the scope is being dispersed and some events are being emited.
# This implementaton cleans up some of the scalability resources.
shutdownKernel: (reason, eol=yes) ->
terminator = (proxy) -> try proxy.close()
util.puts require("os").EOL if (eol or false)
this.emit "killed-scaled-kernel", arguments...
message = "Graceful shutdown of Scaled kernel"
log = (message) -> logger.debug message.yellow
log "Closing the Seaport servers" if @spserver
log "Closing the server (HTTP) proxy instance"
log "Closing the secure (HTTPS) proxy instance"
log "Terminating remote proxies in the queues"
try @spserver.close() if (@spserver) # Seaport
try @serverProxy.close() if this.serverProxy?
try @secureProxy.close() if this.secureProxy?
_.each @queueOfHttps or Array(), terminator
_.each @queueOfHttp or Array(), terminator
logger.warn message.red; super reason, no
|
[
{
"context": " require './config'\n\n\napp = express()\n\n\n# Added by Geoffrey\nhttp = require('http').Server(app)\nhttp.listen co",
"end": 378,
"score": 0.9932708740234375,
"start": 370,
"tag": "NAME",
"value": "Geoffrey"
}
] | app.coffee | ggeoffrey/Choregraphie | 1 | express = require 'express'
path = require 'path'
favicon = require 'static-favicon'
logger = require 'morgan'
cookieParser = require 'cookie-parser'
bodyParser = require 'body-parser'
compression = require 'compression'
routes = require './routes/index'
angularTemplates = require './routes/angularTemplates'
config = require './config'
app = express()
# Added by Geoffrey
http = require('http').Server(app)
http.listen config.port
io = require 'socket.io'
restApi = require('./modules/restApi')
SocketManagerClass = require('./modules/socketManager')
socketManager = new SocketManagerClass(io, http)
# -----------------------------
# view engine setup
app.set 'views', path.join(__dirname, 'views')
app.set 'view engine', 'jade'
app.use favicon()
app.use logger('dev')
app.use compression()
app.use bodyParser.json()
app.use bodyParser.urlencoded()
app.use cookieParser()
app.use require('stylus').middleware(path.join(__dirname, 'public'))
app.use express.static(path.join(__dirname, 'public'))
# ROUTES
app.use '/', routes
app.use '/template', angularTemplates
app.use '/api', restApi
# catch 404 and forward to error handler
app.use (req, res, next)->
err = new Error 'Not Found'
err.status = 404
next err
# error handlers
# development error handler
# will print stack trace
if app.get('env') is 'development'
app.locals.pretty = on
app.use (err, req, res, next)->
res.status err.status or 500
res.render 'error', {
message: err.message
error: err
}
# production error handler
# no stack traces leaked to user
app.use (err, req, res, next)->
res.status err.status or 500
res.render 'error', {
message: err.message
error: {}
}
module.exports = app | 215281 | express = require 'express'
path = require 'path'
favicon = require 'static-favicon'
logger = require 'morgan'
cookieParser = require 'cookie-parser'
bodyParser = require 'body-parser'
compression = require 'compression'
routes = require './routes/index'
angularTemplates = require './routes/angularTemplates'
config = require './config'
app = express()
# Added by <NAME>
http = require('http').Server(app)
http.listen config.port
io = require 'socket.io'
restApi = require('./modules/restApi')
SocketManagerClass = require('./modules/socketManager')
socketManager = new SocketManagerClass(io, http)
# -----------------------------
# view engine setup
app.set 'views', path.join(__dirname, 'views')
app.set 'view engine', 'jade'
app.use favicon()
app.use logger('dev')
app.use compression()
app.use bodyParser.json()
app.use bodyParser.urlencoded()
app.use cookieParser()
app.use require('stylus').middleware(path.join(__dirname, 'public'))
app.use express.static(path.join(__dirname, 'public'))
# ROUTES
app.use '/', routes
app.use '/template', angularTemplates
app.use '/api', restApi
# catch 404 and forward to error handler
app.use (req, res, next)->
err = new Error 'Not Found'
err.status = 404
next err
# error handlers
# development error handler
# will print stack trace
if app.get('env') is 'development'
app.locals.pretty = on
app.use (err, req, res, next)->
res.status err.status or 500
res.render 'error', {
message: err.message
error: err
}
# production error handler
# no stack traces leaked to user
app.use (err, req, res, next)->
res.status err.status or 500
res.render 'error', {
message: err.message
error: {}
}
module.exports = app | true | express = require 'express'
path = require 'path'
favicon = require 'static-favicon'
logger = require 'morgan'
cookieParser = require 'cookie-parser'
bodyParser = require 'body-parser'
compression = require 'compression'
routes = require './routes/index'
angularTemplates = require './routes/angularTemplates'
config = require './config'
app = express()
# Added by PI:NAME:<NAME>END_PI
http = require('http').Server(app)
http.listen config.port
io = require 'socket.io'
restApi = require('./modules/restApi')
SocketManagerClass = require('./modules/socketManager')
socketManager = new SocketManagerClass(io, http)
# -----------------------------
# view engine setup
app.set 'views', path.join(__dirname, 'views')
app.set 'view engine', 'jade'
app.use favicon()
app.use logger('dev')
app.use compression()
app.use bodyParser.json()
app.use bodyParser.urlencoded()
app.use cookieParser()
app.use require('stylus').middleware(path.join(__dirname, 'public'))
app.use express.static(path.join(__dirname, 'public'))
# ROUTES
app.use '/', routes
app.use '/template', angularTemplates
app.use '/api', restApi
# catch 404 and forward to error handler
app.use (req, res, next)->
err = new Error 'Not Found'
err.status = 404
next err
# error handlers
# development error handler
# will print stack trace
if app.get('env') is 'development'
app.locals.pretty = on
app.use (err, req, res, next)->
res.status err.status or 500
res.render 'error', {
message: err.message
error: err
}
# production error handler
# no stack traces leaked to user
app.use (err, req, res, next)->
res.status err.status or 500
res.render 'error', {
message: err.message
error: {}
}
module.exports = app |
[
{
"context": "module.exports =\n info: 'I am nephews.bibby'\n lazyLoads: module._globalLazyLoads",
"end": 32,
"score": 0.6686870455741882,
"start": 31,
"tag": "USERNAME",
"value": "n"
},
{
"context": "module.exports =\n info: 'I am nephews.bibby'\n lazyLoads: module._globalLazyLo... | cdap-web-app/tools/node_modules/groc/node_modules/autorequire/test/examples/spaghetti/lib/nephews/bibby.coffee | cybervisiontech/cdap | 0 | module.exports =
info: 'I am nephews.bibby'
lazyLoads: module._globalLazyLoads
| 17793 | module.exports =
info: 'I am n<NAME>hews<NAME>.bib<NAME>'
lazyLoads: module._globalLazyLoads
| true | module.exports =
info: 'I am nPI:NAME:<NAME>END_PIhewsPI:NAME:<NAME>END_PI.bibPI:NAME:<NAME>END_PI'
lazyLoads: module._globalLazyLoads
|
[
{
"context": "h ->\r\n @clientID = 12345\r\n @clientSecret = 'deadbeefbaadf00d'\r\n @callbackURL = 'https://dead.beef/bad/f00d'",
"end": 932,
"score": 0.9946087002754211,
"start": 916,
"tag": "KEY",
"value": "deadbeefbaadf00d"
},
{
"context": "ts', ->\r\n beforeEach ->\r\... | test/strategy.coffee | javierprovecho/passport-eveonline | 14 | sinon = require('sinon')
chai = require('chai')
sinonChai = require('sinon-chai')
should = require('chai').should()
constants = require('../src/constants')
VerificationError = require('../src/errors/VerificationError')
chai.use(sinonChai)
class DummyOAuth2
constructor: ->
@get = sinon.spy()
@useAuthorizationHeaderforGET = sinon.spy()
class DummyStrategy
constructor: (_arguments...) ->
@isInherited = true
@parentConstructor = sinon.spy()
@parentConstructor.apply(this, _arguments)
@parentAuthenticate = sinon.spy()
@_oauth2 = new DummyOAuth2()
authenticate: (_arguments...) ->
@parentAuthenticate.apply(this, _arguments)
EveOnlineStrategy = require('../src/strategy')(DummyStrategy)
describe 'EVE Online OAuth Strategy', ->
beforeEach ->
@clientID = 12345
@clientSecret = 'deadbeefbaadf00d'
@callbackURL = 'https://dead.beef/bad/f00d'
@verify = sinon.spy()
@strategy = new EveOnlineStrategy(
clientID: @clientID
clientSecret: @clientSecret
callbackURL: @callbackURL
@verify)
@constructorOptions = @strategy.parentConstructor.args[0][0]
@oAuth2Verify = @strategy.parentConstructor.args[0][1]
it "should be named 'eveonline'", ->
@strategy.name.should.equal 'eveonline'
it 'must inherit from passport-oauth2 strategy', ->
@strategy.isInherited.should.be.true
it "must not have an attribute named '_verify'", ->
should.not.exist @strategy._verify
it 'should use the authorization header for get requests', ->
@strategy._oauth2.useAuthorizationHeaderforGET.should.be.calledWith true
describe 'when created with defaults', ->
it 'should invoke the base strategy constructor', ->
@strategy.parentConstructor.should.be.called
it 'should pass authorizationURL to the base strategy constructor', ->
@constructorOptions.should.have.property('authorizationURL').equal \
constants.defaultAuthorizationURL
it 'should pass tokenURL to the base strategy constructor', ->
@constructorOptions.should.have.property('tokenURL').equal \
constants.defaultTokenURL
it 'should pass clientID to the base strategy constructor', ->
@constructorOptions.should.have.property('clientID').equal @clientID
it 'should pass clientSecret to the base strategy constructor', ->
@constructorOptions.should.have.property(
'clientSecret').equal @clientSecret
it 'should pass callbackURL to the base strategy constructor', ->
@constructorOptions.should.have.property('callbackURL').equal @callbackURL
it 'should pass a verify function to the base strategy constructor', ->
@oAuth2Verify.should.be.a.Function
describe 'when constructing with custom URLs', ->
beforeEach ->
@customAuthorizationURL = 'custom authorization URL'
@customTokenURL = 'custom token URL'
@strategy = new EveOnlineStrategy(
clientID: @clientID
clientSecret: @clientSecret
callbackURL: @callbackURL
authorizationURL: @customAuthorizationURL
tokenURL: @customTokenURL
@verify)
@constructorOptions = @strategy.parentConstructor.args[0][0]
it 'should use the authorizationURL property provided', ->
@constructorOptions.should.have.property('authorizationURL').equal \
@customAuthorizationURL
it 'should use the tokenURL property provided', ->
@constructorOptions.should.have.property('tokenURL').equal @customTokenURL
describe 'when constructing without a callbackURL', ->
it 'should throw an exception', ->
(->
new EveOnlineStrategy(
clientID: @clientID
clientSecret: @clientSecret,
@verify)
).should.throw()
describe 'when authenticating', ->
beforeEach ->
@request = 'request'
@authenticateOptions = {some: 'options'}
@strategy.authenticate(@request, @authenticateOptions)
it 'should invoke the base authenticate function', ->
@strategy.parentAuthenticate.should.be.calledWith(
@request, @authenticateOptions)
describe 'when verifying', ->
beforeEach ->
@oAuth2VerifyDone = 'done callback'
@profile = 'profile'
@oAuth2Verify.call(
@strategy,
'access token',
'refresh token',
@profile,
@oAuth2VerifyDone)
it 'translates passport-oauth2 verifications', ->
@verify.should.be.calledWith(@profile, @oAuth2VerifyDone)
describe 'when building character information with defaults', ->
beforeEach ->
@accessToken = 'deadbeef'
@userProfileCallback = sinon.spy()
@strategy.userProfile(@accessToken, @userProfileCallback)
@oAuth2Get = @strategy._oauth2.get.args[0]
@oAuth2GetCallback = @oAuth2Get[2]
it 'should fetch character information using the protected _oauth2
object', ->
@oAuth2Get[0].should.equal constants.defaultVerifyURL
@oAuth2Get[1].should.equal @accessToken
@oAuth2GetCallback.should.be.a.Function
describe 'when called back with character information', ->
beforeEach ->
@expectedProfile =
CharacterID: 54321
CharacterName: 'Kooky Kira'
ExpiresOn: 'Some Expiration Date'
Scopes: 'some scopes'
TokenType: 'Character'
CharacterOwnerHash: 'beefdeadbad'
@oAuth2GetCallback(null, JSON.stringify(@expectedProfile), null)
@characterInformation = @userProfileCallback.args[0][1]
it 'should not return an error', ->
should.not.exist @userProfileCallback.args[0][0]
it 'should provide exactly what was given by the EVE API', ->
@userProfileCallback.should.be.calledWith(null, @expectedProfile)
describe 'when called back with an error in the JSON response', ->
beforeEach ->
@expectedError =
error: 'invalid_token'
error_description: 'The authorization header is not set'
@oAuth2GetCallback(null, JSON.stringify(@expectedError))
@error = @userProfileCallback.args[0][0]
it 'should callback with a VerificationError', ->
@error.code.should.equal @expectedError.error
@error.description.should.equal @expectedError.error_description
describe 'when called back with a mal-formed JSON body', ->
beforeEach ->
@oAuth2GetCallback(null, 'a bad body', null)
@error = @userProfileCallback.args[0][0]
it 'should catch exceptions and callback with an error', ->
@error.should.be.ok
describe 'when called back with an error', ->
beforeEach ->
@innerError = new Error('some error')
@oAuth2GetCallback(@innerError)
@error = @userProfileCallback.args[0][0]
it 'should callback with an InternalOAuthError', ->
@error.name.should.equal 'InternalOAuthError'
@error.message.should.equal constants.fetchCharacterInformationError
@error.oauthError.should.equal @innerError
| 119123 | sinon = require('sinon')
chai = require('chai')
sinonChai = require('sinon-chai')
should = require('chai').should()
constants = require('../src/constants')
VerificationError = require('../src/errors/VerificationError')
chai.use(sinonChai)
class DummyOAuth2
constructor: ->
@get = sinon.spy()
@useAuthorizationHeaderforGET = sinon.spy()
class DummyStrategy
constructor: (_arguments...) ->
@isInherited = true
@parentConstructor = sinon.spy()
@parentConstructor.apply(this, _arguments)
@parentAuthenticate = sinon.spy()
@_oauth2 = new DummyOAuth2()
authenticate: (_arguments...) ->
@parentAuthenticate.apply(this, _arguments)
EveOnlineStrategy = require('../src/strategy')(DummyStrategy)
describe 'EVE Online OAuth Strategy', ->
beforeEach ->
@clientID = 12345
@clientSecret = '<KEY>'
@callbackURL = 'https://dead.beef/bad/f00d'
@verify = sinon.spy()
@strategy = new EveOnlineStrategy(
clientID: @clientID
clientSecret: @clientSecret
callbackURL: @callbackURL
@verify)
@constructorOptions = @strategy.parentConstructor.args[0][0]
@oAuth2Verify = @strategy.parentConstructor.args[0][1]
it "should be named 'eveonline'", ->
@strategy.name.should.equal 'eveonline'
it 'must inherit from passport-oauth2 strategy', ->
@strategy.isInherited.should.be.true
it "must not have an attribute named '_verify'", ->
should.not.exist @strategy._verify
it 'should use the authorization header for get requests', ->
@strategy._oauth2.useAuthorizationHeaderforGET.should.be.calledWith true
describe 'when created with defaults', ->
it 'should invoke the base strategy constructor', ->
@strategy.parentConstructor.should.be.called
it 'should pass authorizationURL to the base strategy constructor', ->
@constructorOptions.should.have.property('authorizationURL').equal \
constants.defaultAuthorizationURL
it 'should pass tokenURL to the base strategy constructor', ->
@constructorOptions.should.have.property('tokenURL').equal \
constants.defaultTokenURL
it 'should pass clientID to the base strategy constructor', ->
@constructorOptions.should.have.property('clientID').equal @clientID
it 'should pass clientSecret to the base strategy constructor', ->
@constructorOptions.should.have.property(
'clientSecret').equal @clientSecret
it 'should pass callbackURL to the base strategy constructor', ->
@constructorOptions.should.have.property('callbackURL').equal @callbackURL
it 'should pass a verify function to the base strategy constructor', ->
@oAuth2Verify.should.be.a.Function
describe 'when constructing with custom URLs', ->
beforeEach ->
@customAuthorizationURL = 'custom authorization URL'
@customTokenURL = 'custom token URL'
@strategy = new EveOnlineStrategy(
clientID: @clientID
clientSecret: @clientSecret
callbackURL: @callbackURL
authorizationURL: @customAuthorizationURL
tokenURL: @customTokenURL
@verify)
@constructorOptions = @strategy.parentConstructor.args[0][0]
it 'should use the authorizationURL property provided', ->
@constructorOptions.should.have.property('authorizationURL').equal \
@customAuthorizationURL
it 'should use the tokenURL property provided', ->
@constructorOptions.should.have.property('tokenURL').equal @customTokenURL
describe 'when constructing without a callbackURL', ->
it 'should throw an exception', ->
(->
new EveOnlineStrategy(
clientID: @clientID
clientSecret: @clientSecret,
@verify)
).should.throw()
describe 'when authenticating', ->
beforeEach ->
@request = 'request'
@authenticateOptions = {some: 'options'}
@strategy.authenticate(@request, @authenticateOptions)
it 'should invoke the base authenticate function', ->
@strategy.parentAuthenticate.should.be.calledWith(
@request, @authenticateOptions)
describe 'when verifying', ->
beforeEach ->
@oAuth2VerifyDone = 'done callback'
@profile = 'profile'
@oAuth2Verify.call(
@strategy,
'access token',
'refresh token',
@profile,
@oAuth2VerifyDone)
it 'translates passport-oauth2 verifications', ->
@verify.should.be.calledWith(@profile, @oAuth2VerifyDone)
describe 'when building character information with defaults', ->
beforeEach ->
@accessToken = '<KEY>'
@userProfileCallback = sinon.spy()
@strategy.userProfile(@accessToken, @userProfileCallback)
@oAuth2Get = @strategy._oauth2.get.args[0]
@oAuth2GetCallback = @oAuth2Get[2]
it 'should fetch character information using the protected _oauth2
object', ->
@oAuth2Get[0].should.equal constants.defaultVerifyURL
@oAuth2Get[1].should.equal @accessToken
@oAuth2GetCallback.should.be.a.Function
describe 'when called back with character information', ->
beforeEach ->
@expectedProfile =
CharacterID: 54321
CharacterName: '<NAME>'
ExpiresOn: 'Some Expiration Date'
Scopes: 'some scopes'
TokenType: 'Character'
CharacterOwnerHash: 'beefdeadbad'
@oAuth2GetCallback(null, JSON.stringify(@expectedProfile), null)
@characterInformation = @userProfileCallback.args[0][1]
it 'should not return an error', ->
should.not.exist @userProfileCallback.args[0][0]
it 'should provide exactly what was given by the EVE API', ->
@userProfileCallback.should.be.calledWith(null, @expectedProfile)
describe 'when called back with an error in the JSON response', ->
beforeEach ->
@expectedError =
error: 'invalid_token'
error_description: 'The authorization header is not set'
@oAuth2GetCallback(null, JSON.stringify(@expectedError))
@error = @userProfileCallback.args[0][0]
it 'should callback with a VerificationError', ->
@error.code.should.equal @expectedError.error
@error.description.should.equal @expectedError.error_description
describe 'when called back with a mal-formed JSON body', ->
beforeEach ->
@oAuth2GetCallback(null, 'a bad body', null)
@error = @userProfileCallback.args[0][0]
it 'should catch exceptions and callback with an error', ->
@error.should.be.ok
describe 'when called back with an error', ->
beforeEach ->
@innerError = new Error('some error')
@oAuth2GetCallback(@innerError)
@error = @userProfileCallback.args[0][0]
it 'should callback with an InternalOAuthError', ->
@error.name.should.equal 'InternalOAuthError'
@error.message.should.equal constants.fetchCharacterInformationError
@error.oauthError.should.equal @innerError
| true | sinon = require('sinon')
chai = require('chai')
sinonChai = require('sinon-chai')
should = require('chai').should()
constants = require('../src/constants')
VerificationError = require('../src/errors/VerificationError')
chai.use(sinonChai)
class DummyOAuth2
constructor: ->
@get = sinon.spy()
@useAuthorizationHeaderforGET = sinon.spy()
class DummyStrategy
constructor: (_arguments...) ->
@isInherited = true
@parentConstructor = sinon.spy()
@parentConstructor.apply(this, _arguments)
@parentAuthenticate = sinon.spy()
@_oauth2 = new DummyOAuth2()
authenticate: (_arguments...) ->
@parentAuthenticate.apply(this, _arguments)
EveOnlineStrategy = require('../src/strategy')(DummyStrategy)
describe 'EVE Online OAuth Strategy', ->
beforeEach ->
@clientID = 12345
@clientSecret = 'PI:KEY:<KEY>END_PI'
@callbackURL = 'https://dead.beef/bad/f00d'
@verify = sinon.spy()
@strategy = new EveOnlineStrategy(
clientID: @clientID
clientSecret: @clientSecret
callbackURL: @callbackURL
@verify)
@constructorOptions = @strategy.parentConstructor.args[0][0]
@oAuth2Verify = @strategy.parentConstructor.args[0][1]
it "should be named 'eveonline'", ->
@strategy.name.should.equal 'eveonline'
it 'must inherit from passport-oauth2 strategy', ->
@strategy.isInherited.should.be.true
it "must not have an attribute named '_verify'", ->
should.not.exist @strategy._verify
it 'should use the authorization header for get requests', ->
@strategy._oauth2.useAuthorizationHeaderforGET.should.be.calledWith true
describe 'when created with defaults', ->
it 'should invoke the base strategy constructor', ->
@strategy.parentConstructor.should.be.called
it 'should pass authorizationURL to the base strategy constructor', ->
@constructorOptions.should.have.property('authorizationURL').equal \
constants.defaultAuthorizationURL
it 'should pass tokenURL to the base strategy constructor', ->
@constructorOptions.should.have.property('tokenURL').equal \
constants.defaultTokenURL
it 'should pass clientID to the base strategy constructor', ->
@constructorOptions.should.have.property('clientID').equal @clientID
it 'should pass clientSecret to the base strategy constructor', ->
@constructorOptions.should.have.property(
'clientSecret').equal @clientSecret
it 'should pass callbackURL to the base strategy constructor', ->
@constructorOptions.should.have.property('callbackURL').equal @callbackURL
it 'should pass a verify function to the base strategy constructor', ->
@oAuth2Verify.should.be.a.Function
describe 'when constructing with custom URLs', ->
beforeEach ->
@customAuthorizationURL = 'custom authorization URL'
@customTokenURL = 'custom token URL'
@strategy = new EveOnlineStrategy(
clientID: @clientID
clientSecret: @clientSecret
callbackURL: @callbackURL
authorizationURL: @customAuthorizationURL
tokenURL: @customTokenURL
@verify)
@constructorOptions = @strategy.parentConstructor.args[0][0]
it 'should use the authorizationURL property provided', ->
@constructorOptions.should.have.property('authorizationURL').equal \
@customAuthorizationURL
it 'should use the tokenURL property provided', ->
@constructorOptions.should.have.property('tokenURL').equal @customTokenURL
describe 'when constructing without a callbackURL', ->
it 'should throw an exception', ->
(->
new EveOnlineStrategy(
clientID: @clientID
clientSecret: @clientSecret,
@verify)
).should.throw()
describe 'when authenticating', ->
beforeEach ->
@request = 'request'
@authenticateOptions = {some: 'options'}
@strategy.authenticate(@request, @authenticateOptions)
it 'should invoke the base authenticate function', ->
@strategy.parentAuthenticate.should.be.calledWith(
@request, @authenticateOptions)
describe 'when verifying', ->
beforeEach ->
@oAuth2VerifyDone = 'done callback'
@profile = 'profile'
@oAuth2Verify.call(
@strategy,
'access token',
'refresh token',
@profile,
@oAuth2VerifyDone)
it 'translates passport-oauth2 verifications', ->
@verify.should.be.calledWith(@profile, @oAuth2VerifyDone)
describe 'when building character information with defaults', ->
beforeEach ->
@accessToken = 'PI:KEY:<KEY>END_PI'
@userProfileCallback = sinon.spy()
@strategy.userProfile(@accessToken, @userProfileCallback)
@oAuth2Get = @strategy._oauth2.get.args[0]
@oAuth2GetCallback = @oAuth2Get[2]
it 'should fetch character information using the protected _oauth2
object', ->
@oAuth2Get[0].should.equal constants.defaultVerifyURL
@oAuth2Get[1].should.equal @accessToken
@oAuth2GetCallback.should.be.a.Function
describe 'when called back with character information', ->
beforeEach ->
@expectedProfile =
CharacterID: 54321
CharacterName: 'PI:NAME:<NAME>END_PI'
ExpiresOn: 'Some Expiration Date'
Scopes: 'some scopes'
TokenType: 'Character'
CharacterOwnerHash: 'beefdeadbad'
@oAuth2GetCallback(null, JSON.stringify(@expectedProfile), null)
@characterInformation = @userProfileCallback.args[0][1]
it 'should not return an error', ->
should.not.exist @userProfileCallback.args[0][0]
it 'should provide exactly what was given by the EVE API', ->
@userProfileCallback.should.be.calledWith(null, @expectedProfile)
describe 'when called back with an error in the JSON response', ->
beforeEach ->
@expectedError =
error: 'invalid_token'
error_description: 'The authorization header is not set'
@oAuth2GetCallback(null, JSON.stringify(@expectedError))
@error = @userProfileCallback.args[0][0]
it 'should callback with a VerificationError', ->
@error.code.should.equal @expectedError.error
@error.description.should.equal @expectedError.error_description
describe 'when called back with a mal-formed JSON body', ->
beforeEach ->
@oAuth2GetCallback(null, 'a bad body', null)
@error = @userProfileCallback.args[0][0]
it 'should catch exceptions and callback with an error', ->
@error.should.be.ok
describe 'when called back with an error', ->
beforeEach ->
@innerError = new Error('some error')
@oAuth2GetCallback(@innerError)
@error = @userProfileCallback.args[0][0]
it 'should callback with an InternalOAuthError', ->
@error.name.should.equal 'InternalOAuthError'
@error.message.should.equal constants.fetchCharacterInformationError
@error.oauthError.should.equal @innerError
|
[
{
"context": "ta.execute mkcmd\n principal: 'ryba'\n password: 'ryba123'\n cmd: 'hdfs dfs -ls'\n```\n\n###\n\n# Options:\n# - c",
"end": 238,
"score": 0.9993929862976074,
"start": 231,
"tag": "PASSWORD",
"value": "ryba123"
}
] | packages/metal/lib/mkcmd.coffee | ryba-io/ryba | 24 |
###
Options:
* `password`
* `principal`
* `cmd`
* `name`
Unix exemple
```
nikita.execute mkcmd
name: 'ryba'
cmd: 'hdfs dfs -ls'
```
Kerberos exemple
```
nikita.execute mkcmd
principal: 'ryba'
password: 'ryba123'
cmd: 'hdfs dfs -ls'
```
###
# Options:
# - cmd
# - password, if security is "kerberos"
# - principal, if security is "kerberos"
# - name, if security isnt "kerberos"
module.exports = (args...) ->
options = {}
for opts in args
if typeof opts is 'string'
throw Error "Invalid mkcmd options: cmd already defined" if options.cmd
options.cmd ?= opts
options[k] = v for k, v of opts
throw Error "Required Option: password is required if principal is provided" if options.principal and not options.password
if options.principal
then "echo '#{options.password}' | kinit #{options.principal} >/dev/null && {\n#{options.cmd}\n}"
else "su -l #{options.name} -c \"#{options.cmd}\""
# if options.principal
# then "echo '#{options.password}' | kinit #{options.principal} >/dev/null && {\n#{options.cmd}\n}"
# else "su -l #{options.name} -c \"#{options.cmd}\""
module.exports.hbase = (krb5_user, cmd) ->
security = 'kerberos'
if security is 'kerberos'
then "echo '#{krb5_user.password}' | kinit #{krb5_user.principal} >/dev/null && {\n#{cmd}\n}"
else "su -l #{user.name} -c \"#{cmd}\""
module.exports.hdfs = (krb5_user, cmd) ->
security = 'kerberos'
if security is 'kerberos'
then "echo '#{krb5_user.password}' | kinit #{krb5_user.principal} >/dev/null && {\n#{cmd}\n}"
else "su -l #{user.name} -c \"#{cmd}\""
module.exports.test = (krb5_user, cmd) ->
# {security, user, test_user} = ctx.config.ryba
security = 'kerberos'
if security is 'kerberos'
then "echo #{krb5_user.password} | kinit #{krb5_user.principal} >/dev/null && {\n#{cmd}\n}"
else "su -l #{user.name} -c \"#{cmd}\""
module.exports.kafka = (krb5_user, cmd) ->
security = 'kerberos'
if security is 'kerberos'
then "echo '#{krb5_user.password}' | kinit #{krb5_user.principal} >/dev/null && {\n#{cmd}\n}"
else "su -l #{hbase.user.name} -c \"#{cmd}\""
module.exports.solr = (opts, cmd) ->
{authentication} = opts
if authentication is 'kerberos'
then "echo '#{opts.admin_password}' | kinit #{opts.admin_principal} >/dev/null && {\n#{cmd}\n}"
else "su -l #{opts.user.name} -c \"#{cmd}\""
| 183777 |
###
Options:
* `password`
* `principal`
* `cmd`
* `name`
Unix exemple
```
nikita.execute mkcmd
name: 'ryba'
cmd: 'hdfs dfs -ls'
```
Kerberos exemple
```
nikita.execute mkcmd
principal: 'ryba'
password: '<PASSWORD>'
cmd: 'hdfs dfs -ls'
```
###
# Options:
# - cmd
# - password, if security is "kerberos"
# - principal, if security is "kerberos"
# - name, if security isnt "kerberos"
module.exports = (args...) ->
options = {}
for opts in args
if typeof opts is 'string'
throw Error "Invalid mkcmd options: cmd already defined" if options.cmd
options.cmd ?= opts
options[k] = v for k, v of opts
throw Error "Required Option: password is required if principal is provided" if options.principal and not options.password
if options.principal
then "echo '#{options.password}' | kinit #{options.principal} >/dev/null && {\n#{options.cmd}\n}"
else "su -l #{options.name} -c \"#{options.cmd}\""
# if options.principal
# then "echo '#{options.password}' | kinit #{options.principal} >/dev/null && {\n#{options.cmd}\n}"
# else "su -l #{options.name} -c \"#{options.cmd}\""
module.exports.hbase = (krb5_user, cmd) ->
security = 'kerberos'
if security is 'kerberos'
then "echo '#{krb5_user.password}' | kinit #{krb5_user.principal} >/dev/null && {\n#{cmd}\n}"
else "su -l #{user.name} -c \"#{cmd}\""
module.exports.hdfs = (krb5_user, cmd) ->
security = 'kerberos'
if security is 'kerberos'
then "echo '#{krb5_user.password}' | kinit #{krb5_user.principal} >/dev/null && {\n#{cmd}\n}"
else "su -l #{user.name} -c \"#{cmd}\""
module.exports.test = (krb5_user, cmd) ->
# {security, user, test_user} = ctx.config.ryba
security = 'kerberos'
if security is 'kerberos'
then "echo #{krb5_user.password} | kinit #{krb5_user.principal} >/dev/null && {\n#{cmd}\n}"
else "su -l #{user.name} -c \"#{cmd}\""
module.exports.kafka = (krb5_user, cmd) ->
security = 'kerberos'
if security is 'kerberos'
then "echo '#{krb5_user.password}' | kinit #{krb5_user.principal} >/dev/null && {\n#{cmd}\n}"
else "su -l #{hbase.user.name} -c \"#{cmd}\""
module.exports.solr = (opts, cmd) ->
{authentication} = opts
if authentication is 'kerberos'
then "echo '#{opts.admin_password}' | kinit #{opts.admin_principal} >/dev/null && {\n#{cmd}\n}"
else "su -l #{opts.user.name} -c \"#{cmd}\""
| true |
###
Options:
* `password`
* `principal`
* `cmd`
* `name`
Unix exemple
```
nikita.execute mkcmd
name: 'ryba'
cmd: 'hdfs dfs -ls'
```
Kerberos exemple
```
nikita.execute mkcmd
principal: 'ryba'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
cmd: 'hdfs dfs -ls'
```
###
# Options:
# - cmd
# - password, if security is "kerberos"
# - principal, if security is "kerberos"
# - name, if security isnt "kerberos"
module.exports = (args...) ->
options = {}
for opts in args
if typeof opts is 'string'
throw Error "Invalid mkcmd options: cmd already defined" if options.cmd
options.cmd ?= opts
options[k] = v for k, v of opts
throw Error "Required Option: password is required if principal is provided" if options.principal and not options.password
if options.principal
then "echo '#{options.password}' | kinit #{options.principal} >/dev/null && {\n#{options.cmd}\n}"
else "su -l #{options.name} -c \"#{options.cmd}\""
# if options.principal
# then "echo '#{options.password}' | kinit #{options.principal} >/dev/null && {\n#{options.cmd}\n}"
# else "su -l #{options.name} -c \"#{options.cmd}\""
module.exports.hbase = (krb5_user, cmd) ->
security = 'kerberos'
if security is 'kerberos'
then "echo '#{krb5_user.password}' | kinit #{krb5_user.principal} >/dev/null && {\n#{cmd}\n}"
else "su -l #{user.name} -c \"#{cmd}\""
module.exports.hdfs = (krb5_user, cmd) ->
security = 'kerberos'
if security is 'kerberos'
then "echo '#{krb5_user.password}' | kinit #{krb5_user.principal} >/dev/null && {\n#{cmd}\n}"
else "su -l #{user.name} -c \"#{cmd}\""
module.exports.test = (krb5_user, cmd) ->
# {security, user, test_user} = ctx.config.ryba
security = 'kerberos'
if security is 'kerberos'
then "echo #{krb5_user.password} | kinit #{krb5_user.principal} >/dev/null && {\n#{cmd}\n}"
else "su -l #{user.name} -c \"#{cmd}\""
module.exports.kafka = (krb5_user, cmd) ->
security = 'kerberos'
if security is 'kerberos'
then "echo '#{krb5_user.password}' | kinit #{krb5_user.principal} >/dev/null && {\n#{cmd}\n}"
else "su -l #{hbase.user.name} -c \"#{cmd}\""
module.exports.solr = (opts, cmd) ->
{authentication} = opts
if authentication is 'kerberos'
then "echo '#{opts.admin_password}' | kinit #{opts.admin_principal} >/dev/null && {\n#{cmd}\n}"
else "su -l #{opts.user.name} -c \"#{cmd}\""
|
[
{
"context": "x compatibility\n else\n user.password = null\n delete user.password\n user.totpSec",
"end": 2804,
"score": 0.995793342590332,
"start": 2800,
"tag": "PASSWORD",
"value": "null"
},
{
"context": "mpatibility\n else\n user.password... | server/controllers/user.coffee | sterob7/gi-security | 0 | _ = require 'underscore'
gi = require 'gi-util'
qrcode = require "qrcode"
otplib = require "otplib"
base32 = require "base32"
logger = gi.common
module.exports = (model, crudControllerFactory) ->
crud = crudControllerFactory(model)
isUsernameAvailable = (req, res) ->
systemId = req.systemId
email = req.query.username
if email?
model.findOne { "email" : { $regex : new RegExp(email, "i") }, "systemId": systemId }, (err, user) ->
if err?
if err is "Cannot find User"
res.status(200).json({available: true}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(500).json({message: 'error searching by email: ' + err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else if (not user)
res.status(200).json({available: true}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(200).json({available: false}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(200).json({available: false}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
verify = (req, res) ->
email = req.body.email
password = req.body.password
systemId = req.systemId
output = {}
if email? and password? and systemId?
model.findOne { "email" : { $regex : new RegExp(email, "i") }, "systemId": systemId }, (err, user) ->
if err or (not user)
res.status(200).json({valid: false}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
model.comparePassword user, password, (err, isValid) ->
if err or (not isValid)
res.status(200).json({valid: false}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
output = user.toJSON()
delete output._id
delete output.systemId
delete output.userIds
delete output.password
delete output.totpSecret
output.valid = true
res.status(200).json(output) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(400).end("Required data not supplied")
showMe = (req, res) ->
model.findById req.user._id, req.systemId, (err, user) ->
if err
res.status(404).json({message: err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
user.password = null
delete user.password
user.totpSecret = null
delete user.totpSecret
res.status(200).json(user) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
updateMe = (req, res) ->
#first check that the user we want to update is the user
#making the request
if req.user._id is not req.body._id
res.status(401).json() #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
req.body.systemId = req.systemId
model.update req.user._id, req.body, (err, user) ->
if err
res.status(404).json() #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
user.password = null
delete user.password
user.totpSecret = null
delete user.totpSecret
res.status(200).json(user) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
destroyMe = (req, res) ->
model.destroy req.user._id, req.systemId, (err) ->
if err
res.status(404).json() #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(200).json() #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
generateAPISecretForMe = (req, res) ->
if req.user._id is not req.body._id
res.status(401).json() #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
model.resetAPISecret req.user._id, req.systemId, (err) ->
if err
res.status(404).json() #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(200).json() #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
stripPasswords = (res) ->
if _.isArray res.giResult
_.each res.giResult, (r) ->
r.obj.password = null
delete r.obj.password
r.obj.confirm = null
delete r.obj.confirm
r.obj.totpSecret = null
delete r.obj.totpSecret
res.status(res.giResultCode).json(res.giResult)
else
res.giResult.password = null
delete res.giResult.password
res.giResult.confirm = null
delete res.giResult.confirm
res.giResult.totpSecret = null
delete res.giResult.totpSecret
res.status(200).json(res.giResult) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
index = (req, res) ->
crud.index req, res, () ->
_.each res.giResult, (u) ->
u.password = null
delete u.password
u.totpSecret = null
delete u.totpSecret
res.status(200).json(res.giResult) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
findById = (req, res) ->
crud.show req, res, () ->
stripPasswords res
create = (req, res) ->
req.body.createdById = req.user._id
crud.create req, res, () ->
stripPasswords res
update = (req, res) ->
crud.update req, res, () ->
stripPasswords res
checkResetToken = (req, res) ->
if req.body.token?
model.findOneBy 'token', req.body.token, req.systemId, (err, user) ->
if err
res.status(500).json({message: err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else if not user
res.status(404).json({message: "invalid token"}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(200).json({message: "token ok"}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(200).json({isValid: false}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
resetPassword = (req, res) ->
if req.body.token?
model.findOneBy 'token', req.body.token, req.systemId, (err, u) ->
if err
res.status(500).json({message: err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else if not u
res.status(404).json({message: "invalid token"})
else
user = u.toObject()
updateObj =
password: req.body.password
systemId: req.systemId
$unset:
token: ""
model.update user._id, updateObj, (err, obj) ->
if err
res.status(500).json({message: "error saving token to user " + err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
msg =
message: "password reset sucesfully"
email: user.email
res.status(200).json(msg) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
#look for a user with the specified e-mail
#generate a random token
model.findOne { "email" : { $regex : new RegExp(req.body.email, "i") }, "systemId": req.systemId }, (err, user) ->
if err
res.status(500).json({message: err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else if not user?
res.status(404).json({message: "Could not find account for that e-mail"})
else
model.generateToken (err, token) ->
if err
res.status(500).json({message: err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else if not token
res.status(500).json({message: "could not generate reset token"}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
updateObj =
token: token
systemId: req.systemId
model.update user._id, updateObj, (err, obj) ->
if err
res.status(500).json({message: "error saving token to user " + err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
resetObj =
host: req.protocol + "://" + req.hostname #Changed 'req.host' to 'req.hostname' for express 4.x compatibility
email: user.email
token: token
model.sendResetInstructions resetObj, (err) ->
if err
res.status(500).json({message: err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
msg = "password reset instructions sent"
res.status(200).json({message: msg}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
getResetToken = (req, res) ->
if req.body.email?
model.findOneBy 'email', req.body.email, req.systemId, (err, user) ->
if err
res.status(500).json({message: err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else if not user?
res.status(404).json({message: "Could not find account for that e-mail"}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
model.generateToken (err, token) ->
if err
res.status(500).json({message: err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else if not token
res.status(500).json({message: "could not generate reset token"}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
updateObj =
token: token
systemId: req.systemId
model.update user._id, updateObj, (err, obj) ->
if err
res.status(500).json({message: "error saving token to user " + err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
resetObj =
host: req.protocol + "://" + req.hostname #Changed 'req.host' to 'req.hostname' for express 4.x compatibility
email: user.email
token: token
_id: user._id
res.status(200).json(resetObj) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(500).json({ message:"No email passed." }) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
getQRCode = (req, res) ->
_getSecret = (systemId, userId, cb) ->
model.findOneBy '_id', userId, systemId, (err, user) ->
if err
cb err, null, null
else
if user.toObject().totpSecret
cb null, user.email, user.toObject().totpSecret
else
secret = otplib.authenticator.generateSecret()
model.update user._id, { systemId: req.systemId, $set: { totpSecret: secret }}, (err, newUser) ->
cb err, user.email, secret || null
if not req.user
res.status(401).end()
else
_getSecret req.systemId, (req.params.id or req.user._id), (err, email, secret) ->
if err
res.status(500).send("Unable to generate secret")
else
appName = "F2F2"
if process.env["F2F2_ENV"] isnt "prod" then appName += "-" + process.env["F2F2_ENV"]
otpauth = otplib.authenticator.keyuri(encodeURIComponent(email), encodeURIComponent(appName), secret)
qrcode.toDataURL otpauth, (err, imageUrl) ->
if err
res.status(500).send("Unable to generate QR Code");
else
res.set "Content-Type", "image/png"
res.set "Content-Length", imageUrl.length
imageUrl = imageUrl.split(",")[1]
buff = Buffer.from imageUrl, "base64"
res.status(200).send(buff);
exports = gi.common.extend {}, crud
exports.index = index
exports.show = findById
exports.create = create
exports.update = update
exports.showMe = showMe
exports.updateMe = updateMe
exports.destroyMe = destroyMe
exports.generateAPISecretForMe = generateAPISecretForMe
exports.resetPassword = resetPassword
exports.getResetToken = getResetToken
exports.checkResetToken = checkResetToken
exports.verify = verify
exports.isUsernameAvailable = isUsernameAvailable
exports.getQRCode = getQRCode
exports
| 198269 | _ = require 'underscore'
gi = require 'gi-util'
qrcode = require "qrcode"
otplib = require "otplib"
base32 = require "base32"
logger = gi.common
module.exports = (model, crudControllerFactory) ->
crud = crudControllerFactory(model)
isUsernameAvailable = (req, res) ->
systemId = req.systemId
email = req.query.username
if email?
model.findOne { "email" : { $regex : new RegExp(email, "i") }, "systemId": systemId }, (err, user) ->
if err?
if err is "Cannot find User"
res.status(200).json({available: true}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(500).json({message: 'error searching by email: ' + err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else if (not user)
res.status(200).json({available: true}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(200).json({available: false}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(200).json({available: false}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
verify = (req, res) ->
email = req.body.email
password = req.body.password
systemId = req.systemId
output = {}
if email? and password? and systemId?
model.findOne { "email" : { $regex : new RegExp(email, "i") }, "systemId": systemId }, (err, user) ->
if err or (not user)
res.status(200).json({valid: false}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
model.comparePassword user, password, (err, isValid) ->
if err or (not isValid)
res.status(200).json({valid: false}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
output = user.toJSON()
delete output._id
delete output.systemId
delete output.userIds
delete output.password
delete output.totpSecret
output.valid = true
res.status(200).json(output) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(400).end("Required data not supplied")
showMe = (req, res) ->
model.findById req.user._id, req.systemId, (err, user) ->
if err
res.status(404).json({message: err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
user.password = <PASSWORD>
delete user.password
user.totpSecret = null
delete user.totpSecret
res.status(200).json(user) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
updateMe = (req, res) ->
#first check that the user we want to update is the user
#making the request
if req.user._id is not req.body._id
res.status(401).json() #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
req.body.systemId = req.systemId
model.update req.user._id, req.body, (err, user) ->
if err
res.status(404).json() #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
user.password = <PASSWORD>
delete user.password
user.totpSecret = null
delete user.totpSecret
res.status(200).json(user) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
destroyMe = (req, res) ->
model.destroy req.user._id, req.systemId, (err) ->
if err
res.status(404).json() #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(200).json() #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
generateAPISecretForMe = (req, res) ->
if req.user._id is not req.body._id
res.status(401).json() #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
model.resetAPISecret req.user._id, req.systemId, (err) ->
if err
res.status(404).json() #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(200).json() #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
stripPasswords = (res) ->
if _.isArray res.giResult
_.each res.giResult, (r) ->
r.obj.password = null
delete r.obj.password
r.obj.confirm = null
delete r.obj.confirm
r.obj.totpSecret = null
delete r.obj.totpSecret
res.status(res.giResultCode).json(res.giResult)
else
res.giResult.password = <PASSWORD>
delete res.giResult.password
res.giResult.confirm = null
delete res.giResult.confirm
res.giResult.totpSecret = null
delete res.giResult.totpSecret
res.status(200).json(res.giResult) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
index = (req, res) ->
crud.index req, res, () ->
_.each res.giResult, (u) ->
u.password = <PASSWORD>
delete u.password
u.totpSecret = null
delete u.totpSecret
res.status(200).json(res.giResult) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
findById = (req, res) ->
crud.show req, res, () ->
stripPasswords res
create = (req, res) ->
req.body.createdById = req.user._id
crud.create req, res, () ->
stripPasswords res
update = (req, res) ->
crud.update req, res, () ->
stripPasswords res
checkResetToken = (req, res) ->
if req.body.token?
model.findOneBy 'token', req.body.token, req.systemId, (err, user) ->
if err
res.status(500).json({message: err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else if not user
res.status(404).json({message: "invalid token"}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(200).json({message: "token ok"}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(200).json({isValid: false}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
resetPassword = (req, res) ->
if req.body.token?
model.findOneBy 'token', req.body.token, req.systemId, (err, u) ->
if err
res.status(500).json({message: err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else if not u
res.status(404).json({message: "invalid token"})
else
user = u.toObject()
updateObj =
password: <PASSWORD>
systemId: req.systemId
$unset:
token: ""
model.update user._id, updateObj, (err, obj) ->
if err
res.status(500).json({message: "error saving token to user " + err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
msg =
message: "password reset sucesfully"
email: user.email
res.status(200).json(msg) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
#look for a user with the specified e-mail
#generate a random token
model.findOne { "email" : { $regex : new RegExp(req.body.email, "i") }, "systemId": req.systemId }, (err, user) ->
if err
res.status(500).json({message: err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else if not user?
res.status(404).json({message: "Could not find account for that e-mail"})
else
model.generateToken (err, token) ->
if err
res.status(500).json({message: err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else if not token
res.status(500).json({message: "could not generate reset token"}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
updateObj =
token: token
systemId: req.systemId
model.update user._id, updateObj, (err, obj) ->
if err
res.status(500).json({message: "error saving token to user " + err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
resetObj =
host: req.protocol + "://" + req.hostname #Changed 'req.host' to 'req.hostname' for express 4.x compatibility
email: user.email
token: token
model.sendResetInstructions resetObj, (err) ->
if err
res.status(500).json({message: err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
msg = "password reset instructions sent"
res.status(200).json({message: msg}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
getResetToken = (req, res) ->
if req.body.email?
model.findOneBy 'email', req.body.email, req.systemId, (err, user) ->
if err
res.status(500).json({message: err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else if not user?
res.status(404).json({message: "Could not find account for that e-mail"}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
model.generateToken (err, token) ->
if err
res.status(500).json({message: err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else if not token
res.status(500).json({message: "could not generate reset token"}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
updateObj =
token: <PASSWORD>
systemId: req.systemId
model.update user._id, updateObj, (err, obj) ->
if err
res.status(500).json({message: "error saving token to user " + err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
resetObj =
host: req.protocol + "://" + req.hostname #Changed 'req.host' to 'req.hostname' for express 4.x compatibility
email: user.email
token: token
_id: user._id
res.status(200).json(resetObj) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(500).json({ message:"No email passed." }) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
getQRCode = (req, res) ->
_getSecret = (systemId, userId, cb) ->
model.findOneBy '_id', userId, systemId, (err, user) ->
if err
cb err, null, null
else
if user.toObject().totpSecret
cb null, user.email, user.toObject().totpSecret
else
secret = otplib.authenticator.generateSecret()
model.update user._id, { systemId: req.systemId, $set: { totpSecret: secret }}, (err, newUser) ->
cb err, user.email, secret || null
if not req.user
res.status(401).end()
else
_getSecret req.systemId, (req.params.id or req.user._id), (err, email, secret) ->
if err
res.status(500).send("Unable to generate secret")
else
appName = "F2F2"
if process.env["F2F2_ENV"] isnt "prod" then appName += "-" + process.env["F2F2_ENV"]
otpauth = otplib.authenticator.keyuri(encodeURIComponent(email), encodeURIComponent(appName), secret)
qrcode.toDataURL otpauth, (err, imageUrl) ->
if err
res.status(500).send("Unable to generate QR Code");
else
res.set "Content-Type", "image/png"
res.set "Content-Length", imageUrl.length
imageUrl = imageUrl.split(",")[1]
buff = Buffer.from imageUrl, "base64"
res.status(200).send(buff);
exports = gi.common.extend {}, crud
exports.index = index
exports.show = findById
exports.create = create
exports.update = update
exports.showMe = showMe
exports.updateMe = updateMe
exports.destroyMe = destroyMe
exports.generateAPISecretForMe = generateAPISecretForMe
exports.resetPassword = <PASSWORD>
exports.getResetToken = getResetToken
exports.checkResetToken = checkResetToken
exports.verify = verify
exports.isUsernameAvailable = isUsernameAvailable
exports.getQRCode = getQRCode
exports
| true | _ = require 'underscore'
gi = require 'gi-util'
qrcode = require "qrcode"
otplib = require "otplib"
base32 = require "base32"
logger = gi.common
module.exports = (model, crudControllerFactory) ->
crud = crudControllerFactory(model)
isUsernameAvailable = (req, res) ->
systemId = req.systemId
email = req.query.username
if email?
model.findOne { "email" : { $regex : new RegExp(email, "i") }, "systemId": systemId }, (err, user) ->
if err?
if err is "Cannot find User"
res.status(200).json({available: true}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(500).json({message: 'error searching by email: ' + err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else if (not user)
res.status(200).json({available: true}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(200).json({available: false}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(200).json({available: false}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
verify = (req, res) ->
email = req.body.email
password = req.body.password
systemId = req.systemId
output = {}
if email? and password? and systemId?
model.findOne { "email" : { $regex : new RegExp(email, "i") }, "systemId": systemId }, (err, user) ->
if err or (not user)
res.status(200).json({valid: false}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
model.comparePassword user, password, (err, isValid) ->
if err or (not isValid)
res.status(200).json({valid: false}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
output = user.toJSON()
delete output._id
delete output.systemId
delete output.userIds
delete output.password
delete output.totpSecret
output.valid = true
res.status(200).json(output) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(400).end("Required data not supplied")
showMe = (req, res) ->
model.findById req.user._id, req.systemId, (err, user) ->
if err
res.status(404).json({message: err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
user.password = PI:PASSWORD:<PASSWORD>END_PI
delete user.password
user.totpSecret = null
delete user.totpSecret
res.status(200).json(user) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
updateMe = (req, res) ->
#first check that the user we want to update is the user
#making the request
if req.user._id is not req.body._id
res.status(401).json() #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
req.body.systemId = req.systemId
model.update req.user._id, req.body, (err, user) ->
if err
res.status(404).json() #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
user.password = PI:PASSWORD:<PASSWORD>END_PI
delete user.password
user.totpSecret = null
delete user.totpSecret
res.status(200).json(user) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
destroyMe = (req, res) ->
model.destroy req.user._id, req.systemId, (err) ->
if err
res.status(404).json() #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(200).json() #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
generateAPISecretForMe = (req, res) ->
if req.user._id is not req.body._id
res.status(401).json() #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
model.resetAPISecret req.user._id, req.systemId, (err) ->
if err
res.status(404).json() #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(200).json() #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
stripPasswords = (res) ->
if _.isArray res.giResult
_.each res.giResult, (r) ->
r.obj.password = null
delete r.obj.password
r.obj.confirm = null
delete r.obj.confirm
r.obj.totpSecret = null
delete r.obj.totpSecret
res.status(res.giResultCode).json(res.giResult)
else
res.giResult.password = PI:PASSWORD:<PASSWORD>END_PI
delete res.giResult.password
res.giResult.confirm = null
delete res.giResult.confirm
res.giResult.totpSecret = null
delete res.giResult.totpSecret
res.status(200).json(res.giResult) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
index = (req, res) ->
crud.index req, res, () ->
_.each res.giResult, (u) ->
u.password = PI:PASSWORD:<PASSWORD>END_PI
delete u.password
u.totpSecret = null
delete u.totpSecret
res.status(200).json(res.giResult) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
findById = (req, res) ->
crud.show req, res, () ->
stripPasswords res
create = (req, res) ->
req.body.createdById = req.user._id
crud.create req, res, () ->
stripPasswords res
update = (req, res) ->
crud.update req, res, () ->
stripPasswords res
checkResetToken = (req, res) ->
if req.body.token?
model.findOneBy 'token', req.body.token, req.systemId, (err, user) ->
if err
res.status(500).json({message: err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else if not user
res.status(404).json({message: "invalid token"}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(200).json({message: "token ok"}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(200).json({isValid: false}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
resetPassword = (req, res) ->
if req.body.token?
model.findOneBy 'token', req.body.token, req.systemId, (err, u) ->
if err
res.status(500).json({message: err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else if not u
res.status(404).json({message: "invalid token"})
else
user = u.toObject()
updateObj =
password: PI:PASSWORD:<PASSWORD>END_PI
systemId: req.systemId
$unset:
token: ""
model.update user._id, updateObj, (err, obj) ->
if err
res.status(500).json({message: "error saving token to user " + err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
msg =
message: "password reset sucesfully"
email: user.email
res.status(200).json(msg) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
#look for a user with the specified e-mail
#generate a random token
model.findOne { "email" : { $regex : new RegExp(req.body.email, "i") }, "systemId": req.systemId }, (err, user) ->
if err
res.status(500).json({message: err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else if not user?
res.status(404).json({message: "Could not find account for that e-mail"})
else
model.generateToken (err, token) ->
if err
res.status(500).json({message: err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else if not token
res.status(500).json({message: "could not generate reset token"}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
updateObj =
token: token
systemId: req.systemId
model.update user._id, updateObj, (err, obj) ->
if err
res.status(500).json({message: "error saving token to user " + err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
resetObj =
host: req.protocol + "://" + req.hostname #Changed 'req.host' to 'req.hostname' for express 4.x compatibility
email: user.email
token: token
model.sendResetInstructions resetObj, (err) ->
if err
res.status(500).json({message: err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
msg = "password reset instructions sent"
res.status(200).json({message: msg}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
getResetToken = (req, res) ->
if req.body.email?
model.findOneBy 'email', req.body.email, req.systemId, (err, user) ->
if err
res.status(500).json({message: err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else if not user?
res.status(404).json({message: "Could not find account for that e-mail"}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
model.generateToken (err, token) ->
if err
res.status(500).json({message: err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else if not token
res.status(500).json({message: "could not generate reset token"}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
updateObj =
token: PI:PASSWORD:<PASSWORD>END_PI
systemId: req.systemId
model.update user._id, updateObj, (err, obj) ->
if err
res.status(500).json({message: "error saving token to user " + err}) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
resetObj =
host: req.protocol + "://" + req.hostname #Changed 'req.host' to 'req.hostname' for express 4.x compatibility
email: user.email
token: token
_id: user._id
res.status(200).json(resetObj) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
else
res.status(500).json({ message:"No email passed." }) #Changed 'res.json(status,obj)' to 'res.status(status).json(obj)' for express 4.x compatibility
getQRCode = (req, res) ->
_getSecret = (systemId, userId, cb) ->
model.findOneBy '_id', userId, systemId, (err, user) ->
if err
cb err, null, null
else
if user.toObject().totpSecret
cb null, user.email, user.toObject().totpSecret
else
secret = otplib.authenticator.generateSecret()
model.update user._id, { systemId: req.systemId, $set: { totpSecret: secret }}, (err, newUser) ->
cb err, user.email, secret || null
if not req.user
res.status(401).end()
else
_getSecret req.systemId, (req.params.id or req.user._id), (err, email, secret) ->
if err
res.status(500).send("Unable to generate secret")
else
appName = "F2F2"
if process.env["F2F2_ENV"] isnt "prod" then appName += "-" + process.env["F2F2_ENV"]
otpauth = otplib.authenticator.keyuri(encodeURIComponent(email), encodeURIComponent(appName), secret)
qrcode.toDataURL otpauth, (err, imageUrl) ->
if err
res.status(500).send("Unable to generate QR Code");
else
res.set "Content-Type", "image/png"
res.set "Content-Length", imageUrl.length
imageUrl = imageUrl.split(",")[1]
buff = Buffer.from imageUrl, "base64"
res.status(200).send(buff);
exports = gi.common.extend {}, crud
exports.index = index
exports.show = findById
exports.create = create
exports.update = update
exports.showMe = showMe
exports.updateMe = updateMe
exports.destroyMe = destroyMe
exports.generateAPISecretForMe = generateAPISecretForMe
exports.resetPassword = PI:PASSWORD:<PASSWORD>END_PI
exports.getResetToken = getResetToken
exports.checkResetToken = checkResetToken
exports.verify = verify
exports.isUsernameAvailable = isUsernameAvailable
exports.getQRCode = getQRCode
exports
|
[
{
"context": "# Copyright 2015, Christopher Joakim <christopher.joakim@gmail.com>\n\ndescribe 'Elapsed",
"end": 36,
"score": 0.9998896718025208,
"start": 18,
"tag": "NAME",
"value": "Christopher Joakim"
},
{
"context": "# Copyright 2015, Christopher Joakim <christopher.joakim@gmail.c... | m26-js/test-src/m26_elapsed_time_spec.coffee | cjoakim/oss | 0 | # Copyright 2015, Christopher Joakim <christopher.joakim@gmail.com>
describe 'ElapsedTime', ->
it 'constructs with a number of seconds', ->
t = new ElapsedTime(3665)
expect(t.as_hhmmss()).toBe('01:01:05')
expect(t.seconds()).isWithin(0.000001, 3665.0)
expect(t.hours()).isWithin(0.000001, 1.0180555555555555)
it 'constructs with a hh:mm:ss string', ->
t = new ElapsedTime('1:1:5')
expect(t.as_hhmmss()).toBe('01:01:05')
t = new ElapsedTime('01:01:05')
expect(t.as_hhmmss()).toBe('01:01:05')
t = new ElapsedTime(' 01 : 01 : 05 ')
expect(t.as_hhmmss()).toBe('01:01:05')
it 'constructs with a mm:ss string', ->
t = new ElapsedTime('1:5')
expect(t.as_hhmmss()).toBe('00:01:05')
t = new ElapsedTime('01:57')
expect(t.as_hhmmss()).toBe('00:01:57')
expect(t.seconds()).isWithin(0.000001, 117.0)
expect(t.hours()).isWithin(0.000001, 0.0325)
it 'constructs with a ss string', ->
t = new ElapsedTime('5')
expect(t.as_hhmmss()).toBe('00:00:05')
t = new ElapsedTime(' 5 ')
expect(t.as_hhmmss()).toBe('00:00:05')
expect(t.seconds()).isWithin(0.000001, 5.0)
expect(t.hours()).isWithin(0.000001, 0.001388888888888889)
| 643 | # Copyright 2015, <NAME> <<EMAIL>>
describe 'ElapsedTime', ->
it 'constructs with a number of seconds', ->
t = new ElapsedTime(3665)
expect(t.as_hhmmss()).toBe('01:01:05')
expect(t.seconds()).isWithin(0.000001, 3665.0)
expect(t.hours()).isWithin(0.000001, 1.0180555555555555)
it 'constructs with a hh:mm:ss string', ->
t = new ElapsedTime('1:1:5')
expect(t.as_hhmmss()).toBe('01:01:05')
t = new ElapsedTime('01:01:05')
expect(t.as_hhmmss()).toBe('01:01:05')
t = new ElapsedTime(' 01 : 01 : 05 ')
expect(t.as_hhmmss()).toBe('01:01:05')
it 'constructs with a mm:ss string', ->
t = new ElapsedTime('1:5')
expect(t.as_hhmmss()).toBe('00:01:05')
t = new ElapsedTime('01:57')
expect(t.as_hhmmss()).toBe('00:01:57')
expect(t.seconds()).isWithin(0.000001, 117.0)
expect(t.hours()).isWithin(0.000001, 0.0325)
it 'constructs with a ss string', ->
t = new ElapsedTime('5')
expect(t.as_hhmmss()).toBe('00:00:05')
t = new ElapsedTime(' 5 ')
expect(t.as_hhmmss()).toBe('00:00:05')
expect(t.seconds()).isWithin(0.000001, 5.0)
expect(t.hours()).isWithin(0.000001, 0.001388888888888889)
| true | # Copyright 2015, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
describe 'ElapsedTime', ->
it 'constructs with a number of seconds', ->
t = new ElapsedTime(3665)
expect(t.as_hhmmss()).toBe('01:01:05')
expect(t.seconds()).isWithin(0.000001, 3665.0)
expect(t.hours()).isWithin(0.000001, 1.0180555555555555)
it 'constructs with a hh:mm:ss string', ->
t = new ElapsedTime('1:1:5')
expect(t.as_hhmmss()).toBe('01:01:05')
t = new ElapsedTime('01:01:05')
expect(t.as_hhmmss()).toBe('01:01:05')
t = new ElapsedTime(' 01 : 01 : 05 ')
expect(t.as_hhmmss()).toBe('01:01:05')
it 'constructs with a mm:ss string', ->
t = new ElapsedTime('1:5')
expect(t.as_hhmmss()).toBe('00:01:05')
t = new ElapsedTime('01:57')
expect(t.as_hhmmss()).toBe('00:01:57')
expect(t.seconds()).isWithin(0.000001, 117.0)
expect(t.hours()).isWithin(0.000001, 0.0325)
it 'constructs with a ss string', ->
t = new ElapsedTime('5')
expect(t.as_hhmmss()).toBe('00:00:05')
t = new ElapsedTime(' 5 ')
expect(t.as_hhmmss()).toBe('00:00:05')
expect(t.seconds()).isWithin(0.000001, 5.0)
expect(t.hours()).isWithin(0.000001, 0.001388888888888889)
|
[
{
"context": " config.appKey,\n config.appSecret,\n '1.0A',\n null,\n 'HMAC-SHA1',\n \n @real",
"end": 617,
"score": 0.6520906090736389,
"start": 613,
"tag": "KEY",
"value": "1.0A"
}
] | lib/plurkHelper.coffee | mmis1000/plurkbot-replace | 0 | {EventEmitter} = require 'events'
OAuth = require 'OAuth'
utils = require './utils'
request = require 'request'
querystring = require 'querystring'
Url = require 'url'
###
event : response # new_response
event : plurk # new_plurk
event : notification # update_notification
###
class Plurk extends EventEmitter
constructor: (@config)->
@lang = @config.lang || "tr_ch"
@qualifier = @config.qualifier || ":"
@oauth = new OAuth.OAuth 'http://www.plurk.com/OAuth/request_token',
'http://www.plurk.com/OAuth/access_token',
config.appKey,
config.appSecret,
'1.0A',
null,
'HMAC-SHA1',
@realtimeChannel = null
@init_()
init_: ()->
@prepareRealTimeChannel_()
prepareRealTimeChannel_: ()->
@get_ 'Realtime/getUserChannel', {}, {}, (e, data, res)=>
try
if e
throw e
obj = JSON.parse(data)
#console.log obj
@startRealtimeChannel_ obj.comet_server
catch e
console.error e
console.log 'fail to load realtime channel, retry after 5 seconds'
setTimeout (@prepareRealTimeChannel_.bind @), 5000
startRealtimeChannel_: (url)->
console.log "pulling data from #{url}"
request url, (error, response, body)=>
try
if error
throw error
if response.statusCode != 200
throw new Error "unexpect http code #{response.statusCode}'"
body = body.replace /CometChannel\.scriptCallback\((.+)\);/, '$1'
obj = JSON.parse body
#console.log obj # Print the google web page.
if obj.data
@handleRealTime obj
if obj.new_offset < -1
throw new Error 'channel desync'
if obj.new_offset != -1
parsedObject = Url.parse url, true
parsedObject.query.offset = obj.new_offset
parsedObject.search = querystring.stringify parsedObject.query
url = Url.format parsedObject
@startRealtimeChannel_ url
catch e
console.error e
console.log 'fail to load realtime channel, retry after 5 seconds'
setTimeout (@prepareRealTimeChannel_.bind @), 5000
get_: (api, options, defaultOptions, callback)->
@oauth.post "http://www.plurk.com/APP/#{api}",
@config.clientToken,
@config.clientSecret,
(utils.mergeDefault options, defaultOptions),
callback
handleRealTime: (data)->
console.log JSON.stringify data, null, 2
plurk: (content, options)->
response : (id, content, options)->
getResponse : (id)->
markAllAsReaded : ()->
module.exports = Plurk | 95705 | {EventEmitter} = require 'events'
OAuth = require 'OAuth'
utils = require './utils'
request = require 'request'
querystring = require 'querystring'
Url = require 'url'
###
event : response # new_response
event : plurk # new_plurk
event : notification # update_notification
###
class Plurk extends EventEmitter
constructor: (@config)->
@lang = @config.lang || "tr_ch"
@qualifier = @config.qualifier || ":"
@oauth = new OAuth.OAuth 'http://www.plurk.com/OAuth/request_token',
'http://www.plurk.com/OAuth/access_token',
config.appKey,
config.appSecret,
'<KEY>',
null,
'HMAC-SHA1',
@realtimeChannel = null
@init_()
init_: ()->
@prepareRealTimeChannel_()
prepareRealTimeChannel_: ()->
@get_ 'Realtime/getUserChannel', {}, {}, (e, data, res)=>
try
if e
throw e
obj = JSON.parse(data)
#console.log obj
@startRealtimeChannel_ obj.comet_server
catch e
console.error e
console.log 'fail to load realtime channel, retry after 5 seconds'
setTimeout (@prepareRealTimeChannel_.bind @), 5000
startRealtimeChannel_: (url)->
console.log "pulling data from #{url}"
request url, (error, response, body)=>
try
if error
throw error
if response.statusCode != 200
throw new Error "unexpect http code #{response.statusCode}'"
body = body.replace /CometChannel\.scriptCallback\((.+)\);/, '$1'
obj = JSON.parse body
#console.log obj # Print the google web page.
if obj.data
@handleRealTime obj
if obj.new_offset < -1
throw new Error 'channel desync'
if obj.new_offset != -1
parsedObject = Url.parse url, true
parsedObject.query.offset = obj.new_offset
parsedObject.search = querystring.stringify parsedObject.query
url = Url.format parsedObject
@startRealtimeChannel_ url
catch e
console.error e
console.log 'fail to load realtime channel, retry after 5 seconds'
setTimeout (@prepareRealTimeChannel_.bind @), 5000
get_: (api, options, defaultOptions, callback)->
@oauth.post "http://www.plurk.com/APP/#{api}",
@config.clientToken,
@config.clientSecret,
(utils.mergeDefault options, defaultOptions),
callback
handleRealTime: (data)->
console.log JSON.stringify data, null, 2
plurk: (content, options)->
response : (id, content, options)->
getResponse : (id)->
markAllAsReaded : ()->
module.exports = Plurk | true | {EventEmitter} = require 'events'
OAuth = require 'OAuth'
utils = require './utils'
request = require 'request'
querystring = require 'querystring'
Url = require 'url'
###
event : response # new_response
event : plurk # new_plurk
event : notification # update_notification
###
class Plurk extends EventEmitter
constructor: (@config)->
@lang = @config.lang || "tr_ch"
@qualifier = @config.qualifier || ":"
@oauth = new OAuth.OAuth 'http://www.plurk.com/OAuth/request_token',
'http://www.plurk.com/OAuth/access_token',
config.appKey,
config.appSecret,
'PI:KEY:<KEY>END_PI',
null,
'HMAC-SHA1',
@realtimeChannel = null
@init_()
init_: ()->
@prepareRealTimeChannel_()
prepareRealTimeChannel_: ()->
@get_ 'Realtime/getUserChannel', {}, {}, (e, data, res)=>
try
if e
throw e
obj = JSON.parse(data)
#console.log obj
@startRealtimeChannel_ obj.comet_server
catch e
console.error e
console.log 'fail to load realtime channel, retry after 5 seconds'
setTimeout (@prepareRealTimeChannel_.bind @), 5000
startRealtimeChannel_: (url)->
console.log "pulling data from #{url}"
request url, (error, response, body)=>
try
if error
throw error
if response.statusCode != 200
throw new Error "unexpect http code #{response.statusCode}'"
body = body.replace /CometChannel\.scriptCallback\((.+)\);/, '$1'
obj = JSON.parse body
#console.log obj # Print the google web page.
if obj.data
@handleRealTime obj
if obj.new_offset < -1
throw new Error 'channel desync'
if obj.new_offset != -1
parsedObject = Url.parse url, true
parsedObject.query.offset = obj.new_offset
parsedObject.search = querystring.stringify parsedObject.query
url = Url.format parsedObject
@startRealtimeChannel_ url
catch e
console.error e
console.log 'fail to load realtime channel, retry after 5 seconds'
setTimeout (@prepareRealTimeChannel_.bind @), 5000
get_: (api, options, defaultOptions, callback)->
@oauth.post "http://www.plurk.com/APP/#{api}",
@config.clientToken,
@config.clientSecret,
(utils.mergeDefault options, defaultOptions),
callback
handleRealTime: (data)->
console.log JSON.stringify data, null, 2
plurk: (content, options)->
response : (id, content, options)->
getResponse : (id)->
markAllAsReaded : ()->
module.exports = Plurk |
[
{
"context": "res.send polygons[req.params.id]\n\napp.get '/email/your@email.com', bigLag, (req, res)->\n res.send { email: 'your@",
"end": 1212,
"score": 0.9933250546455383,
"start": 1198,
"tag": "EMAIL",
"value": "your@email.com"
},
{
"context": "l.com', bigLag, (req, res)->\n re... | examples/server.coffee | crowdstart/crowd-control | 27 | path = require 'path'
express = require 'express'
simulateLatency = require('express-simulate-latency')
app = express()
smallLag = simulateLatency min: 100, max: 500
bigLag = simulateLatency min: 1000, max: 5000
app.use smallLag
app.use express.static __dirname + '/'
app.get '/el.js', (req, res)->
res.sendFile path.resolve(__dirname + '/../el.js')
start = Date.now()
secondsList = []
setInterval ()->
secondsList.unshift value: parseInt((Date.now() - start) / 1000, 10)
secondsList.length = 10
, 1000
app.get '/seconds', bigLag, (req, res)->
res.send secondsList
polygonIds = [0,1,2,3,4,5,6]
polygons = [
{
id: 0
value: 'nothing'
}
{
id: 1
value: 'monogon'
}
{
id: 2
value: 'digon'
}
{
id: 3
value: 'triangle'
}
{
id: 4
value: 'quadrilateral'
}
{
id: 5
value: 'pentagon'
}
{
id: 6
value: 'hexagon'
}
]
app.get '/polygon', (req, res)->
ids = polygonIds.slice()
for id, i in ids
n = Math.floor(Math.random() * (i + 1))
swap = ids[i]
ids[i] = ids[n]
ids[n] = swap
res.send ids
app.get '/polygon/:id', bigLag, (req, res)->
res.send polygons[req.params.id]
app.get '/email/your@email.com', bigLag, (req, res)->
res.send { email: 'your@email.com' }
app.listen 12345, ()->
console.log 'STARTING EXAMPLE SERVER @ localhost:12345'
| 12904 | path = require 'path'
express = require 'express'
simulateLatency = require('express-simulate-latency')
app = express()
smallLag = simulateLatency min: 100, max: 500
bigLag = simulateLatency min: 1000, max: 5000
app.use smallLag
app.use express.static __dirname + '/'
app.get '/el.js', (req, res)->
res.sendFile path.resolve(__dirname + '/../el.js')
start = Date.now()
secondsList = []
setInterval ()->
secondsList.unshift value: parseInt((Date.now() - start) / 1000, 10)
secondsList.length = 10
, 1000
app.get '/seconds', bigLag, (req, res)->
res.send secondsList
polygonIds = [0,1,2,3,4,5,6]
polygons = [
{
id: 0
value: 'nothing'
}
{
id: 1
value: 'monogon'
}
{
id: 2
value: 'digon'
}
{
id: 3
value: 'triangle'
}
{
id: 4
value: 'quadrilateral'
}
{
id: 5
value: 'pentagon'
}
{
id: 6
value: 'hexagon'
}
]
app.get '/polygon', (req, res)->
ids = polygonIds.slice()
for id, i in ids
n = Math.floor(Math.random() * (i + 1))
swap = ids[i]
ids[i] = ids[n]
ids[n] = swap
res.send ids
app.get '/polygon/:id', bigLag, (req, res)->
res.send polygons[req.params.id]
app.get '/email/<EMAIL>', bigLag, (req, res)->
res.send { email: '<EMAIL>' }
app.listen 12345, ()->
console.log 'STARTING EXAMPLE SERVER @ localhost:12345'
| true | path = require 'path'
express = require 'express'
simulateLatency = require('express-simulate-latency')
app = express()
smallLag = simulateLatency min: 100, max: 500
bigLag = simulateLatency min: 1000, max: 5000
app.use smallLag
app.use express.static __dirname + '/'
app.get '/el.js', (req, res)->
res.sendFile path.resolve(__dirname + '/../el.js')
start = Date.now()
secondsList = []
setInterval ()->
secondsList.unshift value: parseInt((Date.now() - start) / 1000, 10)
secondsList.length = 10
, 1000
app.get '/seconds', bigLag, (req, res)->
res.send secondsList
polygonIds = [0,1,2,3,4,5,6]
polygons = [
{
id: 0
value: 'nothing'
}
{
id: 1
value: 'monogon'
}
{
id: 2
value: 'digon'
}
{
id: 3
value: 'triangle'
}
{
id: 4
value: 'quadrilateral'
}
{
id: 5
value: 'pentagon'
}
{
id: 6
value: 'hexagon'
}
]
app.get '/polygon', (req, res)->
ids = polygonIds.slice()
for id, i in ids
n = Math.floor(Math.random() * (i + 1))
swap = ids[i]
ids[i] = ids[n]
ids[n] = swap
res.send ids
app.get '/polygon/:id', bigLag, (req, res)->
res.send polygons[req.params.id]
app.get '/email/PI:EMAIL:<EMAIL>END_PI', bigLag, (req, res)->
res.send { email: 'PI:EMAIL:<EMAIL>END_PI' }
app.listen 12345, ()->
console.log 'STARTING EXAMPLE SERVER @ localhost:12345'
|
[
{
"context": "ttempt fails\":\n topic: -> connect(password: 'absolute_nonsense', @callback)\n\n \"it should not have an error ",
"end": 1294,
"score": 0.9983869791030884,
"start": 1277,
"tag": "PASSWORD",
"value": "absolute_nonsense"
}
] | test/connection_test.coffee | simplereach/node-vertica | 0 | path = require 'path'
fs = require 'fs'
vows = require 'vows'
assert = require 'assert'
if !fs.existsSync('./test/connection.json')
console.error "Create test/connection.json to run functional tests"
else
Vertica = require('../src/vertica')
baseConnectionInfo = JSON.parse(fs.readFileSync('./test/connection.json'))
# help function to connect
connect = (info, callback) ->
for key, value of baseConnectionInfo
info[key] ?= value
connection = Vertica.connect info, (err) -> callback(err, connection)
undefined
vow = vows.describe('Query')
vow.addBatch
"it should fail to connect to an invalid host":
topic: -> connect({host: 'fake.fake'}, @callback)
"it should have an error message": (err, _) ->
assert.ok err?, "Connecting should fail with a fake host."
"it should connect properly with the base info":
topic: -> connect({}, @callback)
"it should not have an error message": (err, _) ->
assert.equal err, null
"it should have a non-busy, working connection": (_, connection) ->
assert.equal connection.busy, false
assert.equal connection.connected, true
"it should return an error if the connection attempt fails":
topic: -> connect(password: 'absolute_nonsense', @callback)
"it should not have an error message": (err, _) ->
assert.ok err?, "Connecting should fail with a wrong password."
"it should use SSL if requested":
topic: -> connect(ssl: 'required', @callback)
"it should connect with an cleartext and encrypted socket pair": (err, conn) ->
if err != 'The server does not support SSL connection'
assert.ok conn.isSSL(), "Connection should be using SSL but isn't."
"it should not use SSL if explicitely requested":
topic: -> connect(ssl: false, @callback)
"it should connect without an SSL socket": (_, conn) ->
assert.ok !conn.isSSL()
"it should be able to interrupt the session":
topic: ->
connect interruptible: true, (err, conn) =>
@callback(err) if err?
conn.query "SELECT sleep(10)", @callback
setTimeout conn.interruptSession.bind(conn), 100
"it should not close the connection": (err, _) ->
assert.equal err, 'The connection was closed.'
vow.export(module)
| 67577 | path = require 'path'
fs = require 'fs'
vows = require 'vows'
assert = require 'assert'
if !fs.existsSync('./test/connection.json')
console.error "Create test/connection.json to run functional tests"
else
Vertica = require('../src/vertica')
baseConnectionInfo = JSON.parse(fs.readFileSync('./test/connection.json'))
# help function to connect
connect = (info, callback) ->
for key, value of baseConnectionInfo
info[key] ?= value
connection = Vertica.connect info, (err) -> callback(err, connection)
undefined
vow = vows.describe('Query')
vow.addBatch
"it should fail to connect to an invalid host":
topic: -> connect({host: 'fake.fake'}, @callback)
"it should have an error message": (err, _) ->
assert.ok err?, "Connecting should fail with a fake host."
"it should connect properly with the base info":
topic: -> connect({}, @callback)
"it should not have an error message": (err, _) ->
assert.equal err, null
"it should have a non-busy, working connection": (_, connection) ->
assert.equal connection.busy, false
assert.equal connection.connected, true
"it should return an error if the connection attempt fails":
topic: -> connect(password: '<PASSWORD>', @callback)
"it should not have an error message": (err, _) ->
assert.ok err?, "Connecting should fail with a wrong password."
"it should use SSL if requested":
topic: -> connect(ssl: 'required', @callback)
"it should connect with an cleartext and encrypted socket pair": (err, conn) ->
if err != 'The server does not support SSL connection'
assert.ok conn.isSSL(), "Connection should be using SSL but isn't."
"it should not use SSL if explicitely requested":
topic: -> connect(ssl: false, @callback)
"it should connect without an SSL socket": (_, conn) ->
assert.ok !conn.isSSL()
"it should be able to interrupt the session":
topic: ->
connect interruptible: true, (err, conn) =>
@callback(err) if err?
conn.query "SELECT sleep(10)", @callback
setTimeout conn.interruptSession.bind(conn), 100
"it should not close the connection": (err, _) ->
assert.equal err, 'The connection was closed.'
vow.export(module)
| true | path = require 'path'
fs = require 'fs'
vows = require 'vows'
assert = require 'assert'
if !fs.existsSync('./test/connection.json')
console.error "Create test/connection.json to run functional tests"
else
Vertica = require('../src/vertica')
baseConnectionInfo = JSON.parse(fs.readFileSync('./test/connection.json'))
# help function to connect
connect = (info, callback) ->
for key, value of baseConnectionInfo
info[key] ?= value
connection = Vertica.connect info, (err) -> callback(err, connection)
undefined
vow = vows.describe('Query')
vow.addBatch
"it should fail to connect to an invalid host":
topic: -> connect({host: 'fake.fake'}, @callback)
"it should have an error message": (err, _) ->
assert.ok err?, "Connecting should fail with a fake host."
"it should connect properly with the base info":
topic: -> connect({}, @callback)
"it should not have an error message": (err, _) ->
assert.equal err, null
"it should have a non-busy, working connection": (_, connection) ->
assert.equal connection.busy, false
assert.equal connection.connected, true
"it should return an error if the connection attempt fails":
topic: -> connect(password: 'PI:PASSWORD:<PASSWORD>END_PI', @callback)
"it should not have an error message": (err, _) ->
assert.ok err?, "Connecting should fail with a wrong password."
"it should use SSL if requested":
topic: -> connect(ssl: 'required', @callback)
"it should connect with an cleartext and encrypted socket pair": (err, conn) ->
if err != 'The server does not support SSL connection'
assert.ok conn.isSSL(), "Connection should be using SSL but isn't."
"it should not use SSL if explicitely requested":
topic: -> connect(ssl: false, @callback)
"it should connect without an SSL socket": (_, conn) ->
assert.ok !conn.isSSL()
"it should be able to interrupt the session":
topic: ->
connect interruptible: true, (err, conn) =>
@callback(err) if err?
conn.query "SELECT sleep(10)", @callback
setTimeout conn.interruptSession.bind(conn), 100
"it should not close the connection": (err, _) ->
assert.equal err, 'The connection was closed.'
vow.export(module)
|
[
{
"context": "$.fn.simpleTab = (arg, args...)->\n storeKey = 'honey.tab'\n# 仅允许调用公开的方法\n if typeof(arg) is 'string' a",
"end": 2187,
"score": 0.9973469972610474,
"start": 2178,
"tag": "KEY",
"value": "honey.tab"
}
] | src/js/plugin/jquery.honey.simple-tab.coffee | Kiteam/kiteam-angular | 0 | ###
简单的tab实现
调用:$(expr).simpleTab(options)
切换到指定的标签tab
$(expr).simpleTab('change', target); //其中target可以是索引或者命名
options:请参考defaultOptions
HTML的格式如下:
<div class="tab" tab>
<ul class="nav" data-field="nav">
<li class="active">menu 1</li>
<li>menu 1</li>
<li>menu 1</li>
</ul>
<div class="content" data-field="content">
<div>panel 1</div>
<div>panel 2</div>
<div>panel 3</div>
</div>
</div>
###
(($)->
class SimpleTab
constructor: ($container, options)->
defaultOptions =
#查找导航容器的表达式
navExpr: '[data-field="nav"]'
#查找panel容器的表达式
panelExpr: '[data-field="content"]'
#触发tab切换的事件类型
eventName: 'click'
#活动的class
activeClass: 'active'
#指定活动的面版(可以是索引或者名字),如果没有指定,则查找activeClass,如果没有指定activeClass,则取第一个panel
activePanel: null
@options = $.extend defaultOptions, options
@initElements $container
@initSelected()
#初始化标签
initElements: ($o)->
self = @
ops = @options
els = @elements =
menus: $o.find ops.navExpr
panels: $o.find ops.panelExpr
els.menus.children().bind ops.eventName, ->
$this = $(this)
target = $this.attr('data-value') || $this.index()
self.change target
initSelected: ()->
#已经指定默认显示的面版
return @change @options.activePanel if @options.activePanel
#没有指定,则查找active
els = @elements
$current = els.menus.find(">.#{@options.activeClass}")
$current = els.menus.eq(0) if $current.length is 0
@change $current.index()
#切换到指定的标签
change: (target)->
klass = @options.activeClass
els = @elements
useIndex = typeof target is 'number'
expr = if useIndex then ">:eq(#{target})" else ">[data-value='#{target}']"
els.menus.find(">.#{klass}").removeClass(klass)
index = els.menus.find(expr).addClass(klass).index()
els.panels.find('>*').hide()
#如果有指定名称,则查找名称,否则使用索引的方式
els.panels.find(expr).show()
SimpleTab.publicMethods = ['change']
$.fn.simpleTab = (arg, args...)->
storeKey = 'honey.tab'
# 仅允许调用公开的方法
if typeof(arg) is 'string' and arg in SimpleTab.publicMethods
instance = this.data storeKey
return console.log('Plugin or Method not defined.') if not instance or not instance[arg]
return instance[arg].apply instance, args
#实例化
instance = new SimpleTab(this, arg)
this.data storeKey, instance
this
)($ || window.jQuery || window.jquery) | 71954 | ###
简单的tab实现
调用:$(expr).simpleTab(options)
切换到指定的标签tab
$(expr).simpleTab('change', target); //其中target可以是索引或者命名
options:请参考defaultOptions
HTML的格式如下:
<div class="tab" tab>
<ul class="nav" data-field="nav">
<li class="active">menu 1</li>
<li>menu 1</li>
<li>menu 1</li>
</ul>
<div class="content" data-field="content">
<div>panel 1</div>
<div>panel 2</div>
<div>panel 3</div>
</div>
</div>
###
(($)->
class SimpleTab
constructor: ($container, options)->
defaultOptions =
#查找导航容器的表达式
navExpr: '[data-field="nav"]'
#查找panel容器的表达式
panelExpr: '[data-field="content"]'
#触发tab切换的事件类型
eventName: 'click'
#活动的class
activeClass: 'active'
#指定活动的面版(可以是索引或者名字),如果没有指定,则查找activeClass,如果没有指定activeClass,则取第一个panel
activePanel: null
@options = $.extend defaultOptions, options
@initElements $container
@initSelected()
#初始化标签
initElements: ($o)->
self = @
ops = @options
els = @elements =
menus: $o.find ops.navExpr
panels: $o.find ops.panelExpr
els.menus.children().bind ops.eventName, ->
$this = $(this)
target = $this.attr('data-value') || $this.index()
self.change target
initSelected: ()->
#已经指定默认显示的面版
return @change @options.activePanel if @options.activePanel
#没有指定,则查找active
els = @elements
$current = els.menus.find(">.#{@options.activeClass}")
$current = els.menus.eq(0) if $current.length is 0
@change $current.index()
#切换到指定的标签
change: (target)->
klass = @options.activeClass
els = @elements
useIndex = typeof target is 'number'
expr = if useIndex then ">:eq(#{target})" else ">[data-value='#{target}']"
els.menus.find(">.#{klass}").removeClass(klass)
index = els.menus.find(expr).addClass(klass).index()
els.panels.find('>*').hide()
#如果有指定名称,则查找名称,否则使用索引的方式
els.panels.find(expr).show()
SimpleTab.publicMethods = ['change']
$.fn.simpleTab = (arg, args...)->
storeKey = '<KEY>'
# 仅允许调用公开的方法
if typeof(arg) is 'string' and arg in SimpleTab.publicMethods
instance = this.data storeKey
return console.log('Plugin or Method not defined.') if not instance or not instance[arg]
return instance[arg].apply instance, args
#实例化
instance = new SimpleTab(this, arg)
this.data storeKey, instance
this
)($ || window.jQuery || window.jquery) | true | ###
简单的tab实现
调用:$(expr).simpleTab(options)
切换到指定的标签tab
$(expr).simpleTab('change', target); //其中target可以是索引或者命名
options:请参考defaultOptions
HTML的格式如下:
<div class="tab" tab>
<ul class="nav" data-field="nav">
<li class="active">menu 1</li>
<li>menu 1</li>
<li>menu 1</li>
</ul>
<div class="content" data-field="content">
<div>panel 1</div>
<div>panel 2</div>
<div>panel 3</div>
</div>
</div>
###
(($)->
class SimpleTab
constructor: ($container, options)->
defaultOptions =
#查找导航容器的表达式
navExpr: '[data-field="nav"]'
#查找panel容器的表达式
panelExpr: '[data-field="content"]'
#触发tab切换的事件类型
eventName: 'click'
#活动的class
activeClass: 'active'
#指定活动的面版(可以是索引或者名字),如果没有指定,则查找activeClass,如果没有指定activeClass,则取第一个panel
activePanel: null
@options = $.extend defaultOptions, options
@initElements $container
@initSelected()
#初始化标签
initElements: ($o)->
self = @
ops = @options
els = @elements =
menus: $o.find ops.navExpr
panels: $o.find ops.panelExpr
els.menus.children().bind ops.eventName, ->
$this = $(this)
target = $this.attr('data-value') || $this.index()
self.change target
initSelected: ()->
#已经指定默认显示的面版
return @change @options.activePanel if @options.activePanel
#没有指定,则查找active
els = @elements
$current = els.menus.find(">.#{@options.activeClass}")
$current = els.menus.eq(0) if $current.length is 0
@change $current.index()
#切换到指定的标签
change: (target)->
klass = @options.activeClass
els = @elements
useIndex = typeof target is 'number'
expr = if useIndex then ">:eq(#{target})" else ">[data-value='#{target}']"
els.menus.find(">.#{klass}").removeClass(klass)
index = els.menus.find(expr).addClass(klass).index()
els.panels.find('>*').hide()
#如果有指定名称,则查找名称,否则使用索引的方式
els.panels.find(expr).show()
SimpleTab.publicMethods = ['change']
$.fn.simpleTab = (arg, args...)->
storeKey = 'PI:KEY:<KEY>END_PI'
# 仅允许调用公开的方法
if typeof(arg) is 'string' and arg in SimpleTab.publicMethods
instance = this.data storeKey
return console.log('Plugin or Method not defined.') if not instance or not instance[arg]
return instance[arg].apply instance, args
#实例化
instance = new SimpleTab(this, arg)
this.data storeKey, instance
this
)($ || window.jQuery || window.jquery) |
[
{
"context": " Backbone.Model({\n patients: [{id: 5, name: \"Elijah Hoppe\"}, {id: 7, name: \"Sofia Grimes\"}]\n })\n\n @my",
"end": 285,
"score": 0.9998729228973389,
"start": 273,
"tag": "NAME",
"value": "Elijah Hoppe"
},
{
"context": "s: [{id: 5, name: \"Elijah Hoppe\"},... | spec/javascripts/core/apps/visit/form-view.spec.coffee | houzelio/houzel | 2 | import FormView from 'javascripts/core/apps/visit/form-view'
import mom from 'moment'
describe("Visit Form View", () ->
MyRegion = Marionette.Region.extend({
el: '#main-region'
})
beforeEach ->
myModel = new Backbone.Model({
patients: [{id: 5, name: "Elijah Hoppe"}, {id: 7, name: "Sofia Grimes"}]
})
@myMedicalHistory = [
{start_date: '2004-04-14 08:30', complaint: "Cough, Chest Pain" , diagnosis: "Asthma"},
{start_date: '2009-10-22 14:20', complaint: "Fever, Fatigue" , diagnosis: "Influenza"}
]
@myRegion = new MyRegion
@myView = new FormView {model: myModel }
describe("after initializing", () ->
it("should exist", () ->
expect(@myView).toBeTruthy()
)
)
describe("after rendering", () ->
beforeEach ->
@myView.render()
it("should set the title correctly", () ->
expect(@myView.$el.find('.content-title').children()).not.toBe('')
)
it("should set the link for the button Back properly", () ->
expect(@myView.$el.find('.content-btn').children().length).toBe(1)
)
)
describe("when attaching", () ->
beforeEach ->
spyOn(@myView, '_showPickers').and.callThrough()
spyOn(@myView, '_showSelects').and.callThrough()
@myRegion.show(@myView)
it("shows the picker components", () ->
expect(@myView._showPickers).toHaveBeenCalled()
)
describe("with a patient", () ->
it("shows the patient's information", () ->
myModel = new Backbone.Model({
id: 1
patient: {name: "Elijah Hoppe", observation: "Sint ratione est autem dolor"}
patient_id: 5
})
myView = new FormView {model: myModel}
@myRegion.show(myView)
expect(myView.$el.find('#patient-sel')).not.toBeInDOM()
expect(myView.$el).toContainText("Elijah Hoppe")
)
)
describe("without a patient", () ->
it("shows the select components", () ->
expect(@myView._showSelects).toHaveBeenCalled()
)
)
describe("with a medical history", () ->
it("shows the patient's medical history", () ->
myModel = new Backbone.Model({
id: 1
patient: {name: "Elijah Hoppe", observation: "Sint ratione est autem dolor"}
patient_id: 5
})
myView = new FormView({
model: myModel
mclHistoryCollection: new Backbone.Collection(@myMedicalHistory)
})
@myRegion.show(myView)
expect(myView.$el.find('#mcl-history-region')).not.toBeEmpty()
)
)
describe("without a medical history", () ->
it("shows an empty history", () ->
expect(@myView.$el.find('#mcl-history-region')).toBeEmpty()
)
)
describe("Events", () ->
beforeEach ->
@myObject = new Marionette.MnObject
@spy = jasmine.createSpyObj('spy', ['save'])
@myView.render()
it("triggers the Save event", () ->
@myObject.listenTo(@myView, 'visit:save', @spy.save)
@myView.$el.find('#save-btn').click()
expect(@spy.save).toHaveBeenCalled()
)
)
describe("::onAnchorPickerClick", () ->
it("should update the date", () ->
@myView.$el.find('#checkin-pickr').val('')
@myView.$el.find('#checkin-pickr').next().click()
@myView.$el.find('#checkout-pickr').next().click()
getDate = (id) =>
mom(@myView.pickers[id].getValue(), 'YYYY-MM-DD HH:mm')
checkInDate = getDate('#checkin-pickr')
checkOutDate = getDate('#checkout-pickr')
expect(mom(checkInDate).isValid()).toBeTruthy()
expect(mom(checkOutDate).isValid()).toBeTruthy()
)
)
)
)
| 179458 | import FormView from 'javascripts/core/apps/visit/form-view'
import mom from 'moment'
describe("Visit Form View", () ->
MyRegion = Marionette.Region.extend({
el: '#main-region'
})
beforeEach ->
myModel = new Backbone.Model({
patients: [{id: 5, name: "<NAME>"}, {id: 7, name: "<NAME>"}]
})
@myMedicalHistory = [
{start_date: '2004-04-14 08:30', complaint: "Cough, Chest Pain" , diagnosis: "Asthma"},
{start_date: '2009-10-22 14:20', complaint: "Fever, Fatigue" , diagnosis: "Influenza"}
]
@myRegion = new MyRegion
@myView = new FormView {model: myModel }
describe("after initializing", () ->
it("should exist", () ->
expect(@myView).toBeTruthy()
)
)
describe("after rendering", () ->
beforeEach ->
@myView.render()
it("should set the title correctly", () ->
expect(@myView.$el.find('.content-title').children()).not.toBe('')
)
it("should set the link for the button Back properly", () ->
expect(@myView.$el.find('.content-btn').children().length).toBe(1)
)
)
describe("when attaching", () ->
beforeEach ->
spyOn(@myView, '_showPickers').and.callThrough()
spyOn(@myView, '_showSelects').and.callThrough()
@myRegion.show(@myView)
it("shows the picker components", () ->
expect(@myView._showPickers).toHaveBeenCalled()
)
describe("with a patient", () ->
it("shows the patient's information", () ->
myModel = new Backbone.Model({
id: 1
patient: {name: "<NAME>", observation: "Sint ratione est autem dolor"}
patient_id: 5
})
myView = new FormView {model: myModel}
@myRegion.show(myView)
expect(myView.$el.find('#patient-sel')).not.toBeInDOM()
expect(myView.$el).toContainText("<NAME>")
)
)
describe("without a patient", () ->
it("shows the select components", () ->
expect(@myView._showSelects).toHaveBeenCalled()
)
)
describe("with a medical history", () ->
it("shows the patient's medical history", () ->
myModel = new Backbone.Model({
id: 1
patient: {name: "<NAME>", observation: "Sint ratione est autem dolor"}
patient_id: 5
})
myView = new FormView({
model: myModel
mclHistoryCollection: new Backbone.Collection(@myMedicalHistory)
})
@myRegion.show(myView)
expect(myView.$el.find('#mcl-history-region')).not.toBeEmpty()
)
)
describe("without a medical history", () ->
it("shows an empty history", () ->
expect(@myView.$el.find('#mcl-history-region')).toBeEmpty()
)
)
describe("Events", () ->
beforeEach ->
@myObject = new Marionette.MnObject
@spy = jasmine.createSpyObj('spy', ['save'])
@myView.render()
it("triggers the Save event", () ->
@myObject.listenTo(@myView, 'visit:save', @spy.save)
@myView.$el.find('#save-btn').click()
expect(@spy.save).toHaveBeenCalled()
)
)
describe("::onAnchorPickerClick", () ->
it("should update the date", () ->
@myView.$el.find('#checkin-pickr').val('')
@myView.$el.find('#checkin-pickr').next().click()
@myView.$el.find('#checkout-pickr').next().click()
getDate = (id) =>
mom(@myView.pickers[id].getValue(), 'YYYY-MM-DD HH:mm')
checkInDate = getDate('#checkin-pickr')
checkOutDate = getDate('#checkout-pickr')
expect(mom(checkInDate).isValid()).toBeTruthy()
expect(mom(checkOutDate).isValid()).toBeTruthy()
)
)
)
)
| true | import FormView from 'javascripts/core/apps/visit/form-view'
import mom from 'moment'
describe("Visit Form View", () ->
MyRegion = Marionette.Region.extend({
el: '#main-region'
})
beforeEach ->
myModel = new Backbone.Model({
patients: [{id: 5, name: "PI:NAME:<NAME>END_PI"}, {id: 7, name: "PI:NAME:<NAME>END_PI"}]
})
@myMedicalHistory = [
{start_date: '2004-04-14 08:30', complaint: "Cough, Chest Pain" , diagnosis: "Asthma"},
{start_date: '2009-10-22 14:20', complaint: "Fever, Fatigue" , diagnosis: "Influenza"}
]
@myRegion = new MyRegion
@myView = new FormView {model: myModel }
describe("after initializing", () ->
it("should exist", () ->
expect(@myView).toBeTruthy()
)
)
describe("after rendering", () ->
beforeEach ->
@myView.render()
it("should set the title correctly", () ->
expect(@myView.$el.find('.content-title').children()).not.toBe('')
)
it("should set the link for the button Back properly", () ->
expect(@myView.$el.find('.content-btn').children().length).toBe(1)
)
)
describe("when attaching", () ->
beforeEach ->
spyOn(@myView, '_showPickers').and.callThrough()
spyOn(@myView, '_showSelects').and.callThrough()
@myRegion.show(@myView)
it("shows the picker components", () ->
expect(@myView._showPickers).toHaveBeenCalled()
)
describe("with a patient", () ->
it("shows the patient's information", () ->
myModel = new Backbone.Model({
id: 1
patient: {name: "PI:NAME:<NAME>END_PI", observation: "Sint ratione est autem dolor"}
patient_id: 5
})
myView = new FormView {model: myModel}
@myRegion.show(myView)
expect(myView.$el.find('#patient-sel')).not.toBeInDOM()
expect(myView.$el).toContainText("PI:NAME:<NAME>END_PI")
)
)
describe("without a patient", () ->
it("shows the select components", () ->
expect(@myView._showSelects).toHaveBeenCalled()
)
)
describe("with a medical history", () ->
it("shows the patient's medical history", () ->
myModel = new Backbone.Model({
id: 1
patient: {name: "PI:NAME:<NAME>END_PI", observation: "Sint ratione est autem dolor"}
patient_id: 5
})
myView = new FormView({
model: myModel
mclHistoryCollection: new Backbone.Collection(@myMedicalHistory)
})
@myRegion.show(myView)
expect(myView.$el.find('#mcl-history-region')).not.toBeEmpty()
)
)
describe("without a medical history", () ->
it("shows an empty history", () ->
expect(@myView.$el.find('#mcl-history-region')).toBeEmpty()
)
)
describe("Events", () ->
beforeEach ->
@myObject = new Marionette.MnObject
@spy = jasmine.createSpyObj('spy', ['save'])
@myView.render()
it("triggers the Save event", () ->
@myObject.listenTo(@myView, 'visit:save', @spy.save)
@myView.$el.find('#save-btn').click()
expect(@spy.save).toHaveBeenCalled()
)
)
describe("::onAnchorPickerClick", () ->
it("should update the date", () ->
@myView.$el.find('#checkin-pickr').val('')
@myView.$el.find('#checkin-pickr').next().click()
@myView.$el.find('#checkout-pickr').next().click()
getDate = (id) =>
mom(@myView.pickers[id].getValue(), 'YYYY-MM-DD HH:mm')
checkInDate = getDate('#checkin-pickr')
checkOutDate = getDate('#checkout-pickr')
expect(mom(checkInDate).isValid()).toBeTruthy()
expect(mom(checkOutDate).isValid()).toBeTruthy()
)
)
)
)
|
[
{
"context": "*******\n# JSSwitch - switch parts class\n# Coded by Hajime Oh-yake 2013.05.20\n#*************************************",
"end": 100,
"score": 0.99989253282547,
"start": 86,
"tag": "NAME",
"value": "Hajime Oh-yake"
}
] | JSKit/04_JSSwitch.coffee | digitarhythm/codeJS | 0 | #*****************************************
# JSSwitch - switch parts class
# Coded by Hajime Oh-yake 2013.05.20
#*****************************************
class JSSwitch extends JSControl
constructor:(frame = JSRectMake(0, 2, 86, 24))->
super(frame)
@_bgColor = JSColor("clearColor")
@_value = false
setValue:(@_value)->
if (@_value == true)
$("input[name='"+@_objectID+"_radio']").val(['on'])
else
$("input[name='"+@_objectID+"_radio']").val(['off'])
$(@_viewSelector).buttonset()
getValue:->
val = $("input[name='"+@_objectID+"_radio']:checked").val()
if (val == "on")
ret = true
else
ret = false
return ret
viewDidAppear:->
super()
tag = "<div id='"+@_objectID+"_switch' style='position:absolute;z-index:1;font-size:8pt; margin:0;float:left;width:"+@_frame.size.width+"px;'>"
tag += "<input type='radio' id='"+@_objectID+"_off' name='"+@_objectID+"_radio' value='off' style='height:20px;'><label for='"+@_objectID+"_off'>OFF</label>"
tag += "<input type='radio' id='"+@_objectID+"_on' name='"+@_objectID+"_radio' value='on' style='height:20px;'><label for='"+@_objectID+"_on'>ON</label>"
tag += "</div>"
if ($(@_viewSelector+"_switch").length)
$(@_viewSelector+"switch").remove()
$(@_viewSelector).append(tag)
@setValue(@_value)
$(@_viewSelector).buttonset()
| 106655 | #*****************************************
# JSSwitch - switch parts class
# Coded by <NAME> 2013.05.20
#*****************************************
class JSSwitch extends JSControl
constructor:(frame = JSRectMake(0, 2, 86, 24))->
super(frame)
@_bgColor = JSColor("clearColor")
@_value = false
setValue:(@_value)->
if (@_value == true)
$("input[name='"+@_objectID+"_radio']").val(['on'])
else
$("input[name='"+@_objectID+"_radio']").val(['off'])
$(@_viewSelector).buttonset()
getValue:->
val = $("input[name='"+@_objectID+"_radio']:checked").val()
if (val == "on")
ret = true
else
ret = false
return ret
viewDidAppear:->
super()
tag = "<div id='"+@_objectID+"_switch' style='position:absolute;z-index:1;font-size:8pt; margin:0;float:left;width:"+@_frame.size.width+"px;'>"
tag += "<input type='radio' id='"+@_objectID+"_off' name='"+@_objectID+"_radio' value='off' style='height:20px;'><label for='"+@_objectID+"_off'>OFF</label>"
tag += "<input type='radio' id='"+@_objectID+"_on' name='"+@_objectID+"_radio' value='on' style='height:20px;'><label for='"+@_objectID+"_on'>ON</label>"
tag += "</div>"
if ($(@_viewSelector+"_switch").length)
$(@_viewSelector+"switch").remove()
$(@_viewSelector).append(tag)
@setValue(@_value)
$(@_viewSelector).buttonset()
| true | #*****************************************
# JSSwitch - switch parts class
# Coded by PI:NAME:<NAME>END_PI 2013.05.20
#*****************************************
class JSSwitch extends JSControl
constructor:(frame = JSRectMake(0, 2, 86, 24))->
super(frame)
@_bgColor = JSColor("clearColor")
@_value = false
setValue:(@_value)->
if (@_value == true)
$("input[name='"+@_objectID+"_radio']").val(['on'])
else
$("input[name='"+@_objectID+"_radio']").val(['off'])
$(@_viewSelector).buttonset()
getValue:->
val = $("input[name='"+@_objectID+"_radio']:checked").val()
if (val == "on")
ret = true
else
ret = false
return ret
viewDidAppear:->
super()
tag = "<div id='"+@_objectID+"_switch' style='position:absolute;z-index:1;font-size:8pt; margin:0;float:left;width:"+@_frame.size.width+"px;'>"
tag += "<input type='radio' id='"+@_objectID+"_off' name='"+@_objectID+"_radio' value='off' style='height:20px;'><label for='"+@_objectID+"_off'>OFF</label>"
tag += "<input type='radio' id='"+@_objectID+"_on' name='"+@_objectID+"_radio' value='on' style='height:20px;'><label for='"+@_objectID+"_on'>ON</label>"
tag += "</div>"
if ($(@_viewSelector+"_switch").length)
$(@_viewSelector+"switch").remove()
$(@_viewSelector).append(tag)
@setValue(@_value)
$(@_viewSelector).buttonset()
|
[
{
"context": "forces spaces inside of object literals.\n# @author Jamund Ferguson\n###\n'use strict'\n\n#------------------------------",
"end": 102,
"score": 0.9998725652694702,
"start": 87,
"tag": "NAME",
"value": "Jamund Ferguson"
},
{
"context": "jects: yes}]\n ,\n ###\n #... | src/tests/rules/object-curly-spacing.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Disallows or enforces spaces inside of object literals.
# @author Jamund Ferguson
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/object-curly-spacing'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'object-curly-spacing', rule,
valid: [
# always - object literals
code: 'obj = { foo: bar, baz: qux }', options: ['always']
,
code: 'obj = { foo: { bar: quxx }, baz: qux }', options: ['always']
,
code: '''
obj = {
foo: bar
baz: qux
}
'''
options: ['always']
,
code: 'x: y', options: ['always']
,
code: 'x: y', options: ['never']
,
# always - destructuring
code: '{ x } = y', options: ['always']
,
code: '{ x, y } = y'
options: ['always']
,
code: '{ x,y } = y'
options: ['always']
,
code: '''
{
x,y } = y
'''
options: ['always']
,
code: '''
{
x,y
} = z
'''
options: ['always']
,
code: '{ x = 10, y } = y'
options: ['always']
,
code: '{ x: { z }, y } = y'
options: ['always']
,
code: '''
{
y,
} = x
'''
options: ['always']
,
code: '{ y, } = x', options: ['always']
,
code: '{ y: x } = x'
options: ['always']
,
# always - import / export
code: "import door from 'room'"
options: ['always']
,
code: "import * as door from 'room'"
options: ['always']
,
code: "import { door } from 'room'"
options: ['always']
,
code: '''
import {
door
} from 'room'
'''
options: ['always']
,
code: "export { door } from 'room'"
options: ['always']
,
code: "import { house, mouse } from 'caravan'"
options: ['always']
,
code: "import house, { mouse } from 'caravan'"
options: ['always']
,
code: "import door, { house, mouse } from 'caravan'"
options: ['always']
,
code: 'export { door }'
options: ['always']
,
code: "import 'room'"
options: ['always']
,
code: "import { bar as x } from 'foo'"
options: ['always']
,
code: "import { x, } from 'foo'"
options: ['always']
,
code: '''
import {
x,
} from 'foo'
'''
options: ['always']
,
code: "export { x, } from 'foo'"
options: ['always']
,
code: '''
export {
x,
} from 'foo'
'''
options: ['always']
,
# always - empty object
code: 'foo = {}', options: ['always']
,
# always - objectsInObjects
code: "obj = { 'foo': { 'bar': 1, 'baz': 2 }}"
options: ['always', {objectsInObjects: no}]
,
code: 'a = { noop: -> }'
options: ['always', {objectsInObjects: no}]
,
code: '{ y: { z }} = x'
options: ['always', {objectsInObjects: no}]
,
# always - arraysInObjects
code: "obj = { 'foo': [ 1, 2 ]}"
options: ['always', {arraysInObjects: no}]
,
code: 'a = { thingInList: list[0] }'
options: ['always', {arraysInObjects: no}]
,
# always - arraysInObjects, objectsInObjects
code: "obj = { 'qux': [ 1, 2 ], 'foo': { 'bar': 1, 'baz': 2 }}"
options: ['always', {arraysInObjects: no, objectsInObjects: no}]
,
# always - arraysInObjects, objectsInObjects (reverse)
code: "obj = { 'foo': { 'bar': 1, 'baz': 2 }, 'qux': [ 1, 2 ]}"
options: ['always', {arraysInObjects: no, objectsInObjects: no}]
,
code: '''
obj = {
foo: bar
baz: qux
}
'''
options: ['never']
,
# never - object literals
code: 'obj = {foo: bar, baz: qux}', options: ['never']
,
code: 'obj = {foo: {bar: quxx}, baz: qux}', options: ['never']
,
code: '''
obj = {foo: {
bar: quxx}, baz: qux
}
'''
options: ['never']
,
code: '''
obj = {foo: {
bar: quxx
}, baz: qux}
'''
options: ['never']
,
code: '''
obj = {
foo: bar,
baz: qux
}
'''
options: ['never']
,
# never - destructuring
code: '{x} = y', options: ['never']
,
code: '{x, y} = y', options: ['never']
,
code: '{x,y} = y', options: ['never']
,
code: '''
{
x,y
} = y
'''
options: ['never']
,
code: '{x = 10} = y'
options: ['never']
,
code: '{x = 10, y} = y'
options: ['never']
,
code: '{x: {z}, y} = y'
options: ['never']
,
code: '''
{
x: {z
}, y} = y
'''
options: ['never']
,
code: '''
{
y,
} = x
'''
options: ['never']
,
code: '{y,} = x', options: ['never']
,
code: '{y:x} = x', options: ['never']
,
# never - import / export
code: "import door from 'room'"
options: ['never']
,
code: "import * as door from 'room'"
options: ['never']
,
code: "import {door} from 'room'"
options: ['never']
,
code: "export {door} from 'room'"
options: ['never']
,
code: '''
import {
door
} from 'room'
'''
options: ['never']
,
code: '''
export {
door
} from 'room'
'''
options: ['never']
,
code: "import {house,mouse} from 'caravan'"
options: ['never']
,
code: "import {house, mouse} from 'caravan'"
options: ['never']
,
code: 'export {door}'
options: ['never']
,
code: "import 'room'"
options: ['never']
,
code: "import x, {bar} from 'foo'"
options: ['never']
,
code: "import x, {bar, baz} from 'foo'"
options: ['never']
,
code: "import {bar as y} from 'foo'"
options: ['never']
,
code: "import {x,} from 'foo'"
options: ['never']
,
code: '''
import {
x,
} from 'foo'
'''
options: ['never']
,
code: "export {x,} from 'foo'"
options: ['never']
,
code: '''
export {
x,
} from 'foo'
'''
options: ['never']
,
# never - empty object
code: 'foo = {}', options: ['never']
,
# never - objectsInObjects
code: "obj = {'foo': {'bar': 1, 'baz': 2} }"
options: ['never', {objectsInObjects: yes}]
,
###
# https://github.com/eslint/eslint/issues/3658
# Empty cases.
###
code: '{} = foo'
,
code: '[] = foo'
,
code: '{a: {}} = foo'
,
code: '{a: []} = foo'
,
code: "import {} from 'foo'"
,
code: "export {} from 'foo'"
,
code: 'export {}'
,
code: '{} = foo', options: ['never']
,
code: '[] = foo', options: ['never']
,
code: '{a: {}} = foo'
options: ['never']
,
code: '{a: []} = foo'
options: ['never']
,
code: "import {} from 'foo'"
options: ['never']
,
code: "export {} from 'foo'"
options: ['never']
,
code: 'export {}'
options: ['never']
]
invalid: [
code: "import {bar} from 'foo.js'"
output: "import { bar } from 'foo.js'"
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ImportDeclaration'
line: 1
column: 8
,
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 12
]
,
code: "import { bar as y} from 'foo.js'"
output: "import { bar as y } from 'foo.js'"
options: ['always']
errors: [
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 18
]
,
code: "import {bar as y} from 'foo.js'"
output: "import { bar as y } from 'foo.js'"
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ImportDeclaration'
line: 1
column: 8
,
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 17
]
,
code: "import { bar} from 'foo.js'"
output: "import { bar } from 'foo.js'"
options: ['always']
errors: [
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 13
]
,
code: "import x, { bar} from 'foo'"
output: "import x, { bar } from 'foo'"
options: ['always']
errors: [
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 16
]
,
code: "import x, { bar, baz} from 'foo'"
output: "import x, { bar, baz } from 'foo'"
options: ['always']
errors: [
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 21
]
,
code: "import x, {bar} from 'foo'"
output: "import x, { bar } from 'foo'"
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ImportDeclaration'
line: 1
column: 11
,
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 15
]
,
code: "import x, {bar, baz} from 'foo'"
output: "import x, { bar, baz } from 'foo'"
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ImportDeclaration'
line: 1
column: 11
,
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 20
]
,
code: "import {bar,} from 'foo'"
output: "import { bar, } from 'foo'"
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ImportDeclaration'
line: 1
column: 8
,
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 13
]
,
code: "import { bar, } from 'foo'"
output: "import {bar,} from 'foo'"
options: ['never']
errors: [
message: "There should be no space after '{'."
type: 'ImportDeclaration'
line: 1
column: 8
,
message: "There should be no space before '}'."
type: 'ImportDeclaration'
line: 1
column: 15
]
,
code: 'export {bar}'
output: 'export { bar }'
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ExportNamedDeclaration'
line: 1
column: 8
,
message: "A space is required before '}'."
type: 'ExportNamedDeclaration'
line: 1
column: 12
]
,
# always - arraysInObjects
code: "obj = { 'foo': [ 1, 2 ] }"
output: "obj = { 'foo': [ 1, 2 ]}"
options: ['always', {arraysInObjects: no}]
errors: [
message: "There should be no space before '}'."
type: 'ObjectExpression'
]
,
code: "obj = { 'foo': [ 1, 2 ] , 'bar': [ 'baz', 'qux' ] }"
output: "obj = { 'foo': [ 1, 2 ] , 'bar': [ 'baz', 'qux' ]}"
options: ['always', {arraysInObjects: no}]
errors: [
message: "There should be no space before '}'."
type: 'ObjectExpression'
]
,
# always-objectsInObjects
code: "obj = { 'foo': { 'bar': 1, 'baz': 2 } }"
output: "obj = { 'foo': { 'bar': 1, 'baz': 2 }}"
options: ['always', {objectsInObjects: no}]
errors: [
message: "There should be no space before '}'."
type: 'ObjectExpression'
line: 1
column: 39
]
,
code: "obj = { 'foo': [ 1, 2 ] , 'bar': { 'baz': 1, 'qux': 2 } }"
output: "obj = { 'foo': [ 1, 2 ] , 'bar': { 'baz': 1, 'qux': 2 }}"
options: ['always', {objectsInObjects: no}]
errors: [
message: "There should be no space before '}'."
type: 'ObjectExpression'
line: 1
column: 57
]
,
# always-destructuring trailing comma
code: '{ a,} = x'
output: '{ a, } = x'
options: ['always']
errors: [
message: "A space is required before '}'."
type: 'ObjectPattern'
line: 1
column: 5
]
,
code: '{a, } = x'
output: '{a,} = x'
options: ['never']
errors: [
message: "There should be no space before '}'."
type: 'ObjectPattern'
line: 1
column: 5
]
,
code: '{a:b } = x'
output: '{a:b} = x'
options: ['never']
errors: [
message: "There should be no space before '}'."
type: 'ObjectPattern'
line: 1
column: 6
]
,
code: '{ a:b } = x'
output: '{a:b} = x'
options: ['never']
errors: [
message: "There should be no space after '{'."
type: 'ObjectPattern'
line: 1
column: 1
,
message: "There should be no space before '}'."
type: 'ObjectPattern'
line: 1
column: 7
]
,
# never-objectsInObjects
code: "obj = {'foo': {'bar': 1, 'baz': 2}}"
output: "obj = {'foo': {'bar': 1, 'baz': 2} }"
options: ['never', {objectsInObjects: yes}]
errors: [
message: "A space is required before '}'."
type: 'ObjectExpression'
line: 1
column: 35
]
,
code: "obj = {'foo': [1, 2] , 'bar': {'baz': 1, 'qux': 2}}"
output: "obj = {'foo': [1, 2] , 'bar': {'baz': 1, 'qux': 2} }"
options: ['never', {objectsInObjects: yes}]
errors: [
message: "A space is required before '}'."
type: 'ObjectExpression'
line: 1
column: 51
]
,
# always & never
code: 'obj = {foo: bar, baz: qux}'
output: 'obj = { foo: bar, baz: qux }'
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ObjectExpression'
line: 1
column: 7
,
message: "A space is required before '}'."
type: 'ObjectExpression'
line: 1
column: 26
]
,
code: 'obj = {foo: bar, baz: qux }'
output: 'obj = { foo: bar, baz: qux }'
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ObjectExpression'
line: 1
column: 7
]
,
code: 'obj = { foo: bar, baz: qux}'
output: 'obj = { foo: bar, baz: qux }'
options: ['always']
errors: [
message: "A space is required before '}'."
type: 'ObjectExpression'
line: 1
column: 27
]
,
code: 'obj = { foo: bar, baz: qux }'
output: 'obj = {foo: bar, baz: qux}'
options: ['never']
errors: [
message: "There should be no space after '{'."
type: 'ObjectExpression'
line: 1
column: 7
,
message: "There should be no space before '}'."
type: 'ObjectExpression'
line: 1
column: 28
]
,
code: 'obj = {foo: bar, baz: qux }'
output: 'obj = {foo: bar, baz: qux}'
options: ['never']
errors: [
message: "There should be no space before '}'."
type: 'ObjectExpression'
line: 1
column: 27
]
,
code: 'obj = { foo: bar, baz: qux}'
output: 'obj = {foo: bar, baz: qux}'
options: ['never']
errors: [
message: "There should be no space after '{'."
type: 'ObjectExpression'
line: 1
column: 7
]
,
code: 'obj = { foo: { bar: quxx}, baz: qux}'
output: 'obj = {foo: {bar: quxx}, baz: qux}'
options: ['never']
errors: [
message: "There should be no space after '{'."
type: 'ObjectExpression'
line: 1
column: 7
,
message: "There should be no space after '{'."
type: 'ObjectExpression'
line: 1
column: 14
]
,
code: 'obj = {foo: {bar: quxx }, baz: qux }'
output: 'obj = {foo: {bar: quxx}, baz: qux}'
options: ['never']
errors: [
message: "There should be no space before '}'."
type: 'ObjectExpression'
line: 1
column: 24
,
message: "There should be no space before '}'."
type: 'ObjectExpression'
line: 1
column: 36
]
,
code: 'export thing = {value: 1 }'
output: 'export thing = { value: 1 }'
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ObjectExpression'
line: 1
column: 16
]
,
# destructuring
code: '{x, y} = y'
output: '{ x, y } = y'
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ObjectPattern'
line: 1
column: 1
,
message: "A space is required before '}'."
type: 'ObjectPattern'
line: 1
column: 6
]
,
code: '{ x, y} = y'
output: '{ x, y } = y'
options: ['always']
errors: [
message: "A space is required before '}'."
type: 'ObjectPattern'
line: 1
column: 7
]
,
code: '{ x, y } = y'
output: '{x, y} = y'
options: ['never']
errors: [
message: "There should be no space after '{'."
type: 'ObjectPattern'
line: 1
column: 1
,
message: "There should be no space before '}'."
type: 'ObjectPattern'
line: 1
column: 8
]
,
code: '{x, y } = y'
output: '{x, y} = y'
options: ['never']
errors: [
message: "There should be no space before '}'."
type: 'ObjectPattern'
line: 1
column: 7
]
,
code: '{ x=10} = y'
output: '{ x=10 } = y'
options: ['always']
errors: [
message: "A space is required before '}'."
type: 'ObjectPattern'
line: 1
column: 7
]
,
code: '{x=10 } = y'
output: '{ x=10 } = y'
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ObjectPattern'
line: 1
column: 1
]
,
# never - arraysInObjects
code: "obj = {'foo': [1, 2]}"
output: "obj = {'foo': [1, 2] }"
options: ['never', {arraysInObjects: yes}]
errors: [
message: "A space is required before '}'."
type: 'ObjectExpression'
]
,
code: "obj = {'foo': [1, 2] , 'bar': ['baz', 'qux']}"
output: "obj = {'foo': [1, 2] , 'bar': ['baz', 'qux'] }"
options: ['never', {arraysInObjects: yes}]
errors: [
message: "A space is required before '}'."
type: 'ObjectExpression'
]
]
| 170870 | ###*
# @fileoverview Disallows or enforces spaces inside of object literals.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/object-curly-spacing'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'object-curly-spacing', rule,
valid: [
# always - object literals
code: 'obj = { foo: bar, baz: qux }', options: ['always']
,
code: 'obj = { foo: { bar: quxx }, baz: qux }', options: ['always']
,
code: '''
obj = {
foo: bar
baz: qux
}
'''
options: ['always']
,
code: 'x: y', options: ['always']
,
code: 'x: y', options: ['never']
,
# always - destructuring
code: '{ x } = y', options: ['always']
,
code: '{ x, y } = y'
options: ['always']
,
code: '{ x,y } = y'
options: ['always']
,
code: '''
{
x,y } = y
'''
options: ['always']
,
code: '''
{
x,y
} = z
'''
options: ['always']
,
code: '{ x = 10, y } = y'
options: ['always']
,
code: '{ x: { z }, y } = y'
options: ['always']
,
code: '''
{
y,
} = x
'''
options: ['always']
,
code: '{ y, } = x', options: ['always']
,
code: '{ y: x } = x'
options: ['always']
,
# always - import / export
code: "import door from 'room'"
options: ['always']
,
code: "import * as door from 'room'"
options: ['always']
,
code: "import { door } from 'room'"
options: ['always']
,
code: '''
import {
door
} from 'room'
'''
options: ['always']
,
code: "export { door } from 'room'"
options: ['always']
,
code: "import { house, mouse } from 'caravan'"
options: ['always']
,
code: "import house, { mouse } from 'caravan'"
options: ['always']
,
code: "import door, { house, mouse } from 'caravan'"
options: ['always']
,
code: 'export { door }'
options: ['always']
,
code: "import 'room'"
options: ['always']
,
code: "import { bar as x } from 'foo'"
options: ['always']
,
code: "import { x, } from 'foo'"
options: ['always']
,
code: '''
import {
x,
} from 'foo'
'''
options: ['always']
,
code: "export { x, } from 'foo'"
options: ['always']
,
code: '''
export {
x,
} from 'foo'
'''
options: ['always']
,
# always - empty object
code: 'foo = {}', options: ['always']
,
# always - objectsInObjects
code: "obj = { 'foo': { 'bar': 1, 'baz': 2 }}"
options: ['always', {objectsInObjects: no}]
,
code: 'a = { noop: -> }'
options: ['always', {objectsInObjects: no}]
,
code: '{ y: { z }} = x'
options: ['always', {objectsInObjects: no}]
,
# always - arraysInObjects
code: "obj = { 'foo': [ 1, 2 ]}"
options: ['always', {arraysInObjects: no}]
,
code: 'a = { thingInList: list[0] }'
options: ['always', {arraysInObjects: no}]
,
# always - arraysInObjects, objectsInObjects
code: "obj = { 'qux': [ 1, 2 ], 'foo': { 'bar': 1, 'baz': 2 }}"
options: ['always', {arraysInObjects: no, objectsInObjects: no}]
,
# always - arraysInObjects, objectsInObjects (reverse)
code: "obj = { 'foo': { 'bar': 1, 'baz': 2 }, 'qux': [ 1, 2 ]}"
options: ['always', {arraysInObjects: no, objectsInObjects: no}]
,
code: '''
obj = {
foo: bar
baz: qux
}
'''
options: ['never']
,
# never - object literals
code: 'obj = {foo: bar, baz: qux}', options: ['never']
,
code: 'obj = {foo: {bar: quxx}, baz: qux}', options: ['never']
,
code: '''
obj = {foo: {
bar: quxx}, baz: qux
}
'''
options: ['never']
,
code: '''
obj = {foo: {
bar: quxx
}, baz: qux}
'''
options: ['never']
,
code: '''
obj = {
foo: bar,
baz: qux
}
'''
options: ['never']
,
# never - destructuring
code: '{x} = y', options: ['never']
,
code: '{x, y} = y', options: ['never']
,
code: '{x,y} = y', options: ['never']
,
code: '''
{
x,y
} = y
'''
options: ['never']
,
code: '{x = 10} = y'
options: ['never']
,
code: '{x = 10, y} = y'
options: ['never']
,
code: '{x: {z}, y} = y'
options: ['never']
,
code: '''
{
x: {z
}, y} = y
'''
options: ['never']
,
code: '''
{
y,
} = x
'''
options: ['never']
,
code: '{y,} = x', options: ['never']
,
code: '{y:x} = x', options: ['never']
,
# never - import / export
code: "import door from 'room'"
options: ['never']
,
code: "import * as door from 'room'"
options: ['never']
,
code: "import {door} from 'room'"
options: ['never']
,
code: "export {door} from 'room'"
options: ['never']
,
code: '''
import {
door
} from 'room'
'''
options: ['never']
,
code: '''
export {
door
} from 'room'
'''
options: ['never']
,
code: "import {house,mouse} from 'caravan'"
options: ['never']
,
code: "import {house, mouse} from 'caravan'"
options: ['never']
,
code: 'export {door}'
options: ['never']
,
code: "import 'room'"
options: ['never']
,
code: "import x, {bar} from 'foo'"
options: ['never']
,
code: "import x, {bar, baz} from 'foo'"
options: ['never']
,
code: "import {bar as y} from 'foo'"
options: ['never']
,
code: "import {x,} from 'foo'"
options: ['never']
,
code: '''
import {
x,
} from 'foo'
'''
options: ['never']
,
code: "export {x,} from 'foo'"
options: ['never']
,
code: '''
export {
x,
} from 'foo'
'''
options: ['never']
,
# never - empty object
code: 'foo = {}', options: ['never']
,
# never - objectsInObjects
code: "obj = {'foo': {'bar': 1, 'baz': 2} }"
options: ['never', {objectsInObjects: yes}]
,
###
# https://github.com/eslint/eslint/issues/3658
# Empty cases.
###
code: '{} = foo'
,
code: '[] = foo'
,
code: '{a: {}} = foo'
,
code: '{a: []} = foo'
,
code: "import {} from 'foo'"
,
code: "export {} from 'foo'"
,
code: 'export {}'
,
code: '{} = foo', options: ['never']
,
code: '[] = foo', options: ['never']
,
code: '{a: {}} = foo'
options: ['never']
,
code: '{a: []} = foo'
options: ['never']
,
code: "import {} from 'foo'"
options: ['never']
,
code: "export {} from 'foo'"
options: ['never']
,
code: 'export {}'
options: ['never']
]
invalid: [
code: "import {bar} from 'foo.js'"
output: "import { bar } from 'foo.js'"
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ImportDeclaration'
line: 1
column: 8
,
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 12
]
,
code: "import { bar as y} from 'foo.js'"
output: "import { bar as y } from 'foo.js'"
options: ['always']
errors: [
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 18
]
,
code: "import {bar as y} from 'foo.js'"
output: "import { bar as y } from 'foo.js'"
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ImportDeclaration'
line: 1
column: 8
,
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 17
]
,
code: "import { bar} from 'foo.js'"
output: "import { bar } from 'foo.js'"
options: ['always']
errors: [
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 13
]
,
code: "import x, { bar} from 'foo'"
output: "import x, { bar } from 'foo'"
options: ['always']
errors: [
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 16
]
,
code: "import x, { bar, baz} from 'foo'"
output: "import x, { bar, baz } from 'foo'"
options: ['always']
errors: [
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 21
]
,
code: "import x, {bar} from 'foo'"
output: "import x, { bar } from 'foo'"
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ImportDeclaration'
line: 1
column: 11
,
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 15
]
,
code: "import x, {bar, baz} from 'foo'"
output: "import x, { bar, baz } from 'foo'"
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ImportDeclaration'
line: 1
column: 11
,
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 20
]
,
code: "import {bar,} from 'foo'"
output: "import { bar, } from 'foo'"
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ImportDeclaration'
line: 1
column: 8
,
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 13
]
,
code: "import { bar, } from 'foo'"
output: "import {bar,} from 'foo'"
options: ['never']
errors: [
message: "There should be no space after '{'."
type: 'ImportDeclaration'
line: 1
column: 8
,
message: "There should be no space before '}'."
type: 'ImportDeclaration'
line: 1
column: 15
]
,
code: 'export {bar}'
output: 'export { bar }'
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ExportNamedDeclaration'
line: 1
column: 8
,
message: "A space is required before '}'."
type: 'ExportNamedDeclaration'
line: 1
column: 12
]
,
# always - arraysInObjects
code: "obj = { 'foo': [ 1, 2 ] }"
output: "obj = { 'foo': [ 1, 2 ]}"
options: ['always', {arraysInObjects: no}]
errors: [
message: "There should be no space before '}'."
type: 'ObjectExpression'
]
,
code: "obj = { 'foo': [ 1, 2 ] , 'bar': [ 'baz', 'qux' ] }"
output: "obj = { 'foo': [ 1, 2 ] , 'bar': [ 'baz', 'qux' ]}"
options: ['always', {arraysInObjects: no}]
errors: [
message: "There should be no space before '}'."
type: 'ObjectExpression'
]
,
# always-objectsInObjects
code: "obj = { 'foo': { 'bar': 1, 'baz': 2 } }"
output: "obj = { 'foo': { 'bar': 1, 'baz': 2 }}"
options: ['always', {objectsInObjects: no}]
errors: [
message: "There should be no space before '}'."
type: 'ObjectExpression'
line: 1
column: 39
]
,
code: "obj = { 'foo': [ 1, 2 ] , 'bar': { 'baz': 1, 'qux': 2 } }"
output: "obj = { 'foo': [ 1, 2 ] , 'bar': { 'baz': 1, 'qux': 2 }}"
options: ['always', {objectsInObjects: no}]
errors: [
message: "There should be no space before '}'."
type: 'ObjectExpression'
line: 1
column: 57
]
,
# always-destructuring trailing comma
code: '{ a,} = x'
output: '{ a, } = x'
options: ['always']
errors: [
message: "A space is required before '}'."
type: 'ObjectPattern'
line: 1
column: 5
]
,
code: '{a, } = x'
output: '{a,} = x'
options: ['never']
errors: [
message: "There should be no space before '}'."
type: 'ObjectPattern'
line: 1
column: 5
]
,
code: '{a:b } = x'
output: '{a:b} = x'
options: ['never']
errors: [
message: "There should be no space before '}'."
type: 'ObjectPattern'
line: 1
column: 6
]
,
code: '{ a:b } = x'
output: '{a:b} = x'
options: ['never']
errors: [
message: "There should be no space after '{'."
type: 'ObjectPattern'
line: 1
column: 1
,
message: "There should be no space before '}'."
type: 'ObjectPattern'
line: 1
column: 7
]
,
# never-objectsInObjects
code: "obj = {'foo': {'bar': 1, 'baz': 2}}"
output: "obj = {'foo': {'bar': 1, 'baz': 2} }"
options: ['never', {objectsInObjects: yes}]
errors: [
message: "A space is required before '}'."
type: 'ObjectExpression'
line: 1
column: 35
]
,
code: "obj = {'foo': [1, 2] , 'bar': {'baz': 1, 'qux': 2}}"
output: "obj = {'foo': [1, 2] , 'bar': {'baz': 1, 'qux': 2} }"
options: ['never', {objectsInObjects: yes}]
errors: [
message: "A space is required before '}'."
type: 'ObjectExpression'
line: 1
column: 51
]
,
# always & never
code: 'obj = {foo: bar, baz: qux}'
output: 'obj = { foo: bar, baz: qux }'
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ObjectExpression'
line: 1
column: 7
,
message: "A space is required before '}'."
type: 'ObjectExpression'
line: 1
column: 26
]
,
code: 'obj = {foo: bar, baz: qux }'
output: 'obj = { foo: bar, baz: qux }'
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ObjectExpression'
line: 1
column: 7
]
,
code: 'obj = { foo: bar, baz: qux}'
output: 'obj = { foo: bar, baz: qux }'
options: ['always']
errors: [
message: "A space is required before '}'."
type: 'ObjectExpression'
line: 1
column: 27
]
,
code: 'obj = { foo: bar, baz: qux }'
output: 'obj = {foo: bar, baz: qux}'
options: ['never']
errors: [
message: "There should be no space after '{'."
type: 'ObjectExpression'
line: 1
column: 7
,
message: "There should be no space before '}'."
type: 'ObjectExpression'
line: 1
column: 28
]
,
code: 'obj = {foo: bar, baz: qux }'
output: 'obj = {foo: bar, baz: qux}'
options: ['never']
errors: [
message: "There should be no space before '}'."
type: 'ObjectExpression'
line: 1
column: 27
]
,
code: 'obj = { foo: bar, baz: qux}'
output: 'obj = {foo: bar, baz: qux}'
options: ['never']
errors: [
message: "There should be no space after '{'."
type: 'ObjectExpression'
line: 1
column: 7
]
,
code: 'obj = { foo: { bar: quxx}, baz: qux}'
output: 'obj = {foo: {bar: quxx}, baz: qux}'
options: ['never']
errors: [
message: "There should be no space after '{'."
type: 'ObjectExpression'
line: 1
column: 7
,
message: "There should be no space after '{'."
type: 'ObjectExpression'
line: 1
column: 14
]
,
code: 'obj = {foo: {bar: quxx }, baz: qux }'
output: 'obj = {foo: {bar: quxx}, baz: qux}'
options: ['never']
errors: [
message: "There should be no space before '}'."
type: 'ObjectExpression'
line: 1
column: 24
,
message: "There should be no space before '}'."
type: 'ObjectExpression'
line: 1
column: 36
]
,
code: 'export thing = {value: 1 }'
output: 'export thing = { value: 1 }'
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ObjectExpression'
line: 1
column: 16
]
,
# destructuring
code: '{x, y} = y'
output: '{ x, y } = y'
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ObjectPattern'
line: 1
column: 1
,
message: "A space is required before '}'."
type: 'ObjectPattern'
line: 1
column: 6
]
,
code: '{ x, y} = y'
output: '{ x, y } = y'
options: ['always']
errors: [
message: "A space is required before '}'."
type: 'ObjectPattern'
line: 1
column: 7
]
,
code: '{ x, y } = y'
output: '{x, y} = y'
options: ['never']
errors: [
message: "There should be no space after '{'."
type: 'ObjectPattern'
line: 1
column: 1
,
message: "There should be no space before '}'."
type: 'ObjectPattern'
line: 1
column: 8
]
,
code: '{x, y } = y'
output: '{x, y} = y'
options: ['never']
errors: [
message: "There should be no space before '}'."
type: 'ObjectPattern'
line: 1
column: 7
]
,
code: '{ x=10} = y'
output: '{ x=10 } = y'
options: ['always']
errors: [
message: "A space is required before '}'."
type: 'ObjectPattern'
line: 1
column: 7
]
,
code: '{x=10 } = y'
output: '{ x=10 } = y'
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ObjectPattern'
line: 1
column: 1
]
,
# never - arraysInObjects
code: "obj = {'foo': [1, 2]}"
output: "obj = {'foo': [1, 2] }"
options: ['never', {arraysInObjects: yes}]
errors: [
message: "A space is required before '}'."
type: 'ObjectExpression'
]
,
code: "obj = {'foo': [1, 2] , 'bar': ['baz', 'qux']}"
output: "obj = {'foo': [1, 2] , 'bar': ['baz', 'qux'] }"
options: ['never', {arraysInObjects: yes}]
errors: [
message: "A space is required before '}'."
type: 'ObjectExpression'
]
]
| true | ###*
# @fileoverview Disallows or enforces spaces inside of object literals.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/object-curly-spacing'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'object-curly-spacing', rule,
valid: [
# always - object literals
code: 'obj = { foo: bar, baz: qux }', options: ['always']
,
code: 'obj = { foo: { bar: quxx }, baz: qux }', options: ['always']
,
code: '''
obj = {
foo: bar
baz: qux
}
'''
options: ['always']
,
code: 'x: y', options: ['always']
,
code: 'x: y', options: ['never']
,
# always - destructuring
code: '{ x } = y', options: ['always']
,
code: '{ x, y } = y'
options: ['always']
,
code: '{ x,y } = y'
options: ['always']
,
code: '''
{
x,y } = y
'''
options: ['always']
,
code: '''
{
x,y
} = z
'''
options: ['always']
,
code: '{ x = 10, y } = y'
options: ['always']
,
code: '{ x: { z }, y } = y'
options: ['always']
,
code: '''
{
y,
} = x
'''
options: ['always']
,
code: '{ y, } = x', options: ['always']
,
code: '{ y: x } = x'
options: ['always']
,
# always - import / export
code: "import door from 'room'"
options: ['always']
,
code: "import * as door from 'room'"
options: ['always']
,
code: "import { door } from 'room'"
options: ['always']
,
code: '''
import {
door
} from 'room'
'''
options: ['always']
,
code: "export { door } from 'room'"
options: ['always']
,
code: "import { house, mouse } from 'caravan'"
options: ['always']
,
code: "import house, { mouse } from 'caravan'"
options: ['always']
,
code: "import door, { house, mouse } from 'caravan'"
options: ['always']
,
code: 'export { door }'
options: ['always']
,
code: "import 'room'"
options: ['always']
,
code: "import { bar as x } from 'foo'"
options: ['always']
,
code: "import { x, } from 'foo'"
options: ['always']
,
code: '''
import {
x,
} from 'foo'
'''
options: ['always']
,
code: "export { x, } from 'foo'"
options: ['always']
,
code: '''
export {
x,
} from 'foo'
'''
options: ['always']
,
# always - empty object
code: 'foo = {}', options: ['always']
,
# always - objectsInObjects
code: "obj = { 'foo': { 'bar': 1, 'baz': 2 }}"
options: ['always', {objectsInObjects: no}]
,
code: 'a = { noop: -> }'
options: ['always', {objectsInObjects: no}]
,
code: '{ y: { z }} = x'
options: ['always', {objectsInObjects: no}]
,
# always - arraysInObjects
code: "obj = { 'foo': [ 1, 2 ]}"
options: ['always', {arraysInObjects: no}]
,
code: 'a = { thingInList: list[0] }'
options: ['always', {arraysInObjects: no}]
,
# always - arraysInObjects, objectsInObjects
code: "obj = { 'qux': [ 1, 2 ], 'foo': { 'bar': 1, 'baz': 2 }}"
options: ['always', {arraysInObjects: no, objectsInObjects: no}]
,
# always - arraysInObjects, objectsInObjects (reverse)
code: "obj = { 'foo': { 'bar': 1, 'baz': 2 }, 'qux': [ 1, 2 ]}"
options: ['always', {arraysInObjects: no, objectsInObjects: no}]
,
code: '''
obj = {
foo: bar
baz: qux
}
'''
options: ['never']
,
# never - object literals
code: 'obj = {foo: bar, baz: qux}', options: ['never']
,
code: 'obj = {foo: {bar: quxx}, baz: qux}', options: ['never']
,
code: '''
obj = {foo: {
bar: quxx}, baz: qux
}
'''
options: ['never']
,
code: '''
obj = {foo: {
bar: quxx
}, baz: qux}
'''
options: ['never']
,
code: '''
obj = {
foo: bar,
baz: qux
}
'''
options: ['never']
,
# never - destructuring
code: '{x} = y', options: ['never']
,
code: '{x, y} = y', options: ['never']
,
code: '{x,y} = y', options: ['never']
,
code: '''
{
x,y
} = y
'''
options: ['never']
,
code: '{x = 10} = y'
options: ['never']
,
code: '{x = 10, y} = y'
options: ['never']
,
code: '{x: {z}, y} = y'
options: ['never']
,
code: '''
{
x: {z
}, y} = y
'''
options: ['never']
,
code: '''
{
y,
} = x
'''
options: ['never']
,
code: '{y,} = x', options: ['never']
,
code: '{y:x} = x', options: ['never']
,
# never - import / export
code: "import door from 'room'"
options: ['never']
,
code: "import * as door from 'room'"
options: ['never']
,
code: "import {door} from 'room'"
options: ['never']
,
code: "export {door} from 'room'"
options: ['never']
,
code: '''
import {
door
} from 'room'
'''
options: ['never']
,
code: '''
export {
door
} from 'room'
'''
options: ['never']
,
code: "import {house,mouse} from 'caravan'"
options: ['never']
,
code: "import {house, mouse} from 'caravan'"
options: ['never']
,
code: 'export {door}'
options: ['never']
,
code: "import 'room'"
options: ['never']
,
code: "import x, {bar} from 'foo'"
options: ['never']
,
code: "import x, {bar, baz} from 'foo'"
options: ['never']
,
code: "import {bar as y} from 'foo'"
options: ['never']
,
code: "import {x,} from 'foo'"
options: ['never']
,
code: '''
import {
x,
} from 'foo'
'''
options: ['never']
,
code: "export {x,} from 'foo'"
options: ['never']
,
code: '''
export {
x,
} from 'foo'
'''
options: ['never']
,
# never - empty object
code: 'foo = {}', options: ['never']
,
# never - objectsInObjects
code: "obj = {'foo': {'bar': 1, 'baz': 2} }"
options: ['never', {objectsInObjects: yes}]
,
###
# https://github.com/eslint/eslint/issues/3658
# Empty cases.
###
code: '{} = foo'
,
code: '[] = foo'
,
code: '{a: {}} = foo'
,
code: '{a: []} = foo'
,
code: "import {} from 'foo'"
,
code: "export {} from 'foo'"
,
code: 'export {}'
,
code: '{} = foo', options: ['never']
,
code: '[] = foo', options: ['never']
,
code: '{a: {}} = foo'
options: ['never']
,
code: '{a: []} = foo'
options: ['never']
,
code: "import {} from 'foo'"
options: ['never']
,
code: "export {} from 'foo'"
options: ['never']
,
code: 'export {}'
options: ['never']
]
invalid: [
code: "import {bar} from 'foo.js'"
output: "import { bar } from 'foo.js'"
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ImportDeclaration'
line: 1
column: 8
,
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 12
]
,
code: "import { bar as y} from 'foo.js'"
output: "import { bar as y } from 'foo.js'"
options: ['always']
errors: [
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 18
]
,
code: "import {bar as y} from 'foo.js'"
output: "import { bar as y } from 'foo.js'"
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ImportDeclaration'
line: 1
column: 8
,
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 17
]
,
code: "import { bar} from 'foo.js'"
output: "import { bar } from 'foo.js'"
options: ['always']
errors: [
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 13
]
,
code: "import x, { bar} from 'foo'"
output: "import x, { bar } from 'foo'"
options: ['always']
errors: [
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 16
]
,
code: "import x, { bar, baz} from 'foo'"
output: "import x, { bar, baz } from 'foo'"
options: ['always']
errors: [
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 21
]
,
code: "import x, {bar} from 'foo'"
output: "import x, { bar } from 'foo'"
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ImportDeclaration'
line: 1
column: 11
,
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 15
]
,
code: "import x, {bar, baz} from 'foo'"
output: "import x, { bar, baz } from 'foo'"
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ImportDeclaration'
line: 1
column: 11
,
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 20
]
,
code: "import {bar,} from 'foo'"
output: "import { bar, } from 'foo'"
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ImportDeclaration'
line: 1
column: 8
,
message: "A space is required before '}'."
type: 'ImportDeclaration'
line: 1
column: 13
]
,
code: "import { bar, } from 'foo'"
output: "import {bar,} from 'foo'"
options: ['never']
errors: [
message: "There should be no space after '{'."
type: 'ImportDeclaration'
line: 1
column: 8
,
message: "There should be no space before '}'."
type: 'ImportDeclaration'
line: 1
column: 15
]
,
code: 'export {bar}'
output: 'export { bar }'
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ExportNamedDeclaration'
line: 1
column: 8
,
message: "A space is required before '}'."
type: 'ExportNamedDeclaration'
line: 1
column: 12
]
,
# always - arraysInObjects
code: "obj = { 'foo': [ 1, 2 ] }"
output: "obj = { 'foo': [ 1, 2 ]}"
options: ['always', {arraysInObjects: no}]
errors: [
message: "There should be no space before '}'."
type: 'ObjectExpression'
]
,
code: "obj = { 'foo': [ 1, 2 ] , 'bar': [ 'baz', 'qux' ] }"
output: "obj = { 'foo': [ 1, 2 ] , 'bar': [ 'baz', 'qux' ]}"
options: ['always', {arraysInObjects: no}]
errors: [
message: "There should be no space before '}'."
type: 'ObjectExpression'
]
,
# always-objectsInObjects
code: "obj = { 'foo': { 'bar': 1, 'baz': 2 } }"
output: "obj = { 'foo': { 'bar': 1, 'baz': 2 }}"
options: ['always', {objectsInObjects: no}]
errors: [
message: "There should be no space before '}'."
type: 'ObjectExpression'
line: 1
column: 39
]
,
code: "obj = { 'foo': [ 1, 2 ] , 'bar': { 'baz': 1, 'qux': 2 } }"
output: "obj = { 'foo': [ 1, 2 ] , 'bar': { 'baz': 1, 'qux': 2 }}"
options: ['always', {objectsInObjects: no}]
errors: [
message: "There should be no space before '}'."
type: 'ObjectExpression'
line: 1
column: 57
]
,
# always-destructuring trailing comma
code: '{ a,} = x'
output: '{ a, } = x'
options: ['always']
errors: [
message: "A space is required before '}'."
type: 'ObjectPattern'
line: 1
column: 5
]
,
code: '{a, } = x'
output: '{a,} = x'
options: ['never']
errors: [
message: "There should be no space before '}'."
type: 'ObjectPattern'
line: 1
column: 5
]
,
code: '{a:b } = x'
output: '{a:b} = x'
options: ['never']
errors: [
message: "There should be no space before '}'."
type: 'ObjectPattern'
line: 1
column: 6
]
,
code: '{ a:b } = x'
output: '{a:b} = x'
options: ['never']
errors: [
message: "There should be no space after '{'."
type: 'ObjectPattern'
line: 1
column: 1
,
message: "There should be no space before '}'."
type: 'ObjectPattern'
line: 1
column: 7
]
,
# never-objectsInObjects
code: "obj = {'foo': {'bar': 1, 'baz': 2}}"
output: "obj = {'foo': {'bar': 1, 'baz': 2} }"
options: ['never', {objectsInObjects: yes}]
errors: [
message: "A space is required before '}'."
type: 'ObjectExpression'
line: 1
column: 35
]
,
code: "obj = {'foo': [1, 2] , 'bar': {'baz': 1, 'qux': 2}}"
output: "obj = {'foo': [1, 2] , 'bar': {'baz': 1, 'qux': 2} }"
options: ['never', {objectsInObjects: yes}]
errors: [
message: "A space is required before '}'."
type: 'ObjectExpression'
line: 1
column: 51
]
,
# always & never
code: 'obj = {foo: bar, baz: qux}'
output: 'obj = { foo: bar, baz: qux }'
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ObjectExpression'
line: 1
column: 7
,
message: "A space is required before '}'."
type: 'ObjectExpression'
line: 1
column: 26
]
,
code: 'obj = {foo: bar, baz: qux }'
output: 'obj = { foo: bar, baz: qux }'
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ObjectExpression'
line: 1
column: 7
]
,
code: 'obj = { foo: bar, baz: qux}'
output: 'obj = { foo: bar, baz: qux }'
options: ['always']
errors: [
message: "A space is required before '}'."
type: 'ObjectExpression'
line: 1
column: 27
]
,
code: 'obj = { foo: bar, baz: qux }'
output: 'obj = {foo: bar, baz: qux}'
options: ['never']
errors: [
message: "There should be no space after '{'."
type: 'ObjectExpression'
line: 1
column: 7
,
message: "There should be no space before '}'."
type: 'ObjectExpression'
line: 1
column: 28
]
,
code: 'obj = {foo: bar, baz: qux }'
output: 'obj = {foo: bar, baz: qux}'
options: ['never']
errors: [
message: "There should be no space before '}'."
type: 'ObjectExpression'
line: 1
column: 27
]
,
code: 'obj = { foo: bar, baz: qux}'
output: 'obj = {foo: bar, baz: qux}'
options: ['never']
errors: [
message: "There should be no space after '{'."
type: 'ObjectExpression'
line: 1
column: 7
]
,
code: 'obj = { foo: { bar: quxx}, baz: qux}'
output: 'obj = {foo: {bar: quxx}, baz: qux}'
options: ['never']
errors: [
message: "There should be no space after '{'."
type: 'ObjectExpression'
line: 1
column: 7
,
message: "There should be no space after '{'."
type: 'ObjectExpression'
line: 1
column: 14
]
,
code: 'obj = {foo: {bar: quxx }, baz: qux }'
output: 'obj = {foo: {bar: quxx}, baz: qux}'
options: ['never']
errors: [
message: "There should be no space before '}'."
type: 'ObjectExpression'
line: 1
column: 24
,
message: "There should be no space before '}'."
type: 'ObjectExpression'
line: 1
column: 36
]
,
code: 'export thing = {value: 1 }'
output: 'export thing = { value: 1 }'
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ObjectExpression'
line: 1
column: 16
]
,
# destructuring
code: '{x, y} = y'
output: '{ x, y } = y'
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ObjectPattern'
line: 1
column: 1
,
message: "A space is required before '}'."
type: 'ObjectPattern'
line: 1
column: 6
]
,
code: '{ x, y} = y'
output: '{ x, y } = y'
options: ['always']
errors: [
message: "A space is required before '}'."
type: 'ObjectPattern'
line: 1
column: 7
]
,
code: '{ x, y } = y'
output: '{x, y} = y'
options: ['never']
errors: [
message: "There should be no space after '{'."
type: 'ObjectPattern'
line: 1
column: 1
,
message: "There should be no space before '}'."
type: 'ObjectPattern'
line: 1
column: 8
]
,
code: '{x, y } = y'
output: '{x, y} = y'
options: ['never']
errors: [
message: "There should be no space before '}'."
type: 'ObjectPattern'
line: 1
column: 7
]
,
code: '{ x=10} = y'
output: '{ x=10 } = y'
options: ['always']
errors: [
message: "A space is required before '}'."
type: 'ObjectPattern'
line: 1
column: 7
]
,
code: '{x=10 } = y'
output: '{ x=10 } = y'
options: ['always']
errors: [
message: "A space is required after '{'."
type: 'ObjectPattern'
line: 1
column: 1
]
,
# never - arraysInObjects
code: "obj = {'foo': [1, 2]}"
output: "obj = {'foo': [1, 2] }"
options: ['never', {arraysInObjects: yes}]
errors: [
message: "A space is required before '}'."
type: 'ObjectExpression'
]
,
code: "obj = {'foo': [1, 2] , 'bar': ['baz', 'qux']}"
output: "obj = {'foo': [1, 2] , 'bar': ['baz', 'qux'] }"
options: ['never', {arraysInObjects: yes}]
errors: [
message: "A space is required before '}'."
type: 'ObjectExpression'
]
]
|
[
{
"context": "ard.factionId = Factions.Faction3\n\t\t\tcard.name = \"Orbrider\"\n\t\t\tcard.setDescription(\"Opening Gambit: Return a",
"end": 6312,
"score": 0.9963875412940979,
"start": 6304,
"tag": "NAME",
"value": "Orbrider"
},
{
"context": ".id = Cards.Spell.IncreasingWinds\n\t\t... | app/sdk/cards/factory/coreshatter/faction3.coffee | willroberts/duelyst | 5 | # do not add this file to a package
# it is specifically parsed by the package generation script
_ = require 'underscore'
moment = require 'moment'
Logger = require 'app/common/logger'
CONFIG = require('app/common/config')
RSX = require('app/data/resources')
Card = require 'app/sdk/cards/card'
Cards = require 'app/sdk/cards/cardsLookupComplete'
CardType = require 'app/sdk/cards/cardType'
Factions = require 'app/sdk/cards/factionsLookup'
FactionFactory = require 'app/sdk/cards/factionFactory'
Races = require 'app/sdk/cards/racesLookup'
Rarity = require 'app/sdk/cards/rarityLookup'
Unit = require 'app/sdk/entities/unit'
CardSet = require 'app/sdk/cards/cardSetLookup'
Artifact = require 'app/sdk/artifacts/artifact'
SpellFilterType = require 'app/sdk/spells/spellFilterType'
SpellIntensifySpawnEntitiesNearGeneral = require 'app/sdk/spells/spellIntensifySpawnEntitiesNearGeneral'
SpellApplyModifiers = require 'app/sdk/spells/spellApplyModifiers'
SpellSummoningStones = require 'app/sdk/spells/spellSummoningStones'
SpellDrawArtifact = require 'app/sdk/spells/spellDrawArtifact'
SpellThoughtExchange = require 'app/sdk/spells/spellThoughtExchange'
SpellMetalworking = require 'app/sdk/spells/spellMetalworking'
Modifier = require 'app/sdk/modifiers/modifier'
ModifierOpeningGambit = require 'app/sdk/modifiers/modifierOpeningGambit'
ModifierStartOpponentsTurnWatchRemoveEntity = require 'app/sdk/modifiers/modifierStartOpponentsTurnWatchRemoveEntity'
ModifierEnemyCannotCastBBS = require 'app/sdk/modifiers/modifierEnemyCannotCastBBS'
ModifierStartTurnWatchRestoreChargeToArtifacts = require 'app/sdk/modifiers/modifierStartTurnWatchRestoreChargeToArtifacts'
ModifierIntensifyBuffSelf = require 'app/sdk/modifiers/modifierIntensifyBuffSelf'
ModifierIntensifyDamageEnemyGeneral = require 'app/sdk/modifiers/modifierIntensifyDamageEnemyGeneral'
ModifierFlying = require 'app/sdk/modifiers/modifierFlying'
ModifierStartsInHand = require 'app/sdk/modifiers/modifierStartsInHand'
ModifierForcefield = require 'app/sdk/modifiers/modifierForcefield'
ModifierFirstBlood = require 'app/sdk/modifiers/modifierFirstBlood'
ModifierBlastAttackStrong = require 'app/sdk/modifiers/modifierBlastAttackStrong'
ModifierMyAttackWatchScarabBlast = require 'app/sdk/modifiers/modifierMyAttackWatchScarabBlast'
ModifierEquipFriendlyArtifactWatchGainAttackEqualToCost = require 'app/sdk/modifiers/modifierEquipFriendlyArtifactWatchGainAttackEqualToCost'
ModifierOnSummonFromHandApplyEmblems = require 'app/sdk/modifiers/modifierOnSummonFromHandApplyEmblems'
ModifierDyingWishGoldenGuide = require 'app/sdk/modifiers/modifierDyingWishGoldenGuide'
ModifierToken = require 'app/sdk/modifiers/modifierToken'
ModifierTokenCreator = require 'app/sdk/modifiers/modifierTokenCreator'
ModifierFateVetruvianMovementQuest = require 'app/sdk/modifiers/modifierFateVetruvianMovementQuest'
ModifierCannotBeReplaced = require 'app/sdk/modifiers/modifierCannotBeReplaced'
ModifierIntensify = require 'app/sdk/modifiers/modifierIntensify'
ModifierCounterIntensify = require 'app/sdk/modifiers/modifierCounterIntensify'
ModifierCannotBeRemovedFromHand = require 'app/sdk/modifiers/modifierCannotBeRemovedFromHand'
PlayerModifierEmblemSituationalVetQuestFrenzy = require 'app/sdk/playerModifiers/playerModifierEmblemSituationalVetQuestFrenzy'
PlayerModifierEmblemSituationalVetQuestFlying = require 'app/sdk/playerModifiers/playerModifierEmblemSituationalVetQuestFlying'
PlayerModifierEmblemSituationalVetQuestCelerity = require 'app/sdk/playerModifiers/playerModifierEmblemSituationalVetQuestCelerity'
i18next = require 'i18next'
if i18next.t() is undefined
i18next.t = (text) ->
return text
class CardFactory_CoreshatterSet_Faction3
###*
* Returns a card that matches the identifier.
* @param {Number|String} identifier
* @param {GameSession} gameSession
* @returns {Card}
###
@cardForIdentifier: (identifier,gameSession) ->
card = null
if (identifier == Cards.Faction3.KeeperOfAges)
card = new Unit(gameSession)
card.factionId = Factions.Faction3
card.setCardSetId(CardSet.Coreshatter)
card.name = "Notion of Starless Eternity"
card.setDescription("Trial: General reaches the other edge of the battlefield with an equipped artifact.\nDestiny: Each equipped artifact gives your General a tier of ascension.")
card.atk = 3
card.maxHP = 3
card.manaCost = 6
card.rarityId = Rarity.Mythron
emblemModifier1 = PlayerModifierEmblemSituationalVetQuestFrenzy.createContextObject(1)
emblemModifier1.appliedName = "Overcome Eternity"
emblemModifier1.appliedDescription = "Each equipped artifact gives your General a tier of ascension: Frenzy, Flying, Celerity."
emblemModifier2 = PlayerModifierEmblemSituationalVetQuestFlying.createContextObject(2)
emblemModifier2.isHiddenToUI = true
emblemModifier3 = PlayerModifierEmblemSituationalVetQuestCelerity.createContextObject(3)
emblemModifier3.isHiddenToUI = true
card.setInherentModifiersContextObjects([
ModifierStartsInHand.createContextObject(),
ModifierCannotBeReplaced.createContextObject(),
ModifierFateVetruvianMovementQuest.createContextObject(),
ModifierOnSummonFromHandApplyEmblems.createContextObject([emblemModifier1, emblemModifier2, emblemModifier3], true, false),
ModifierCannotBeRemovedFromHand.createContextObject()
])
card.setFXResource(["FX.Cards.Neutral.SwornDefender"])
card.setBoundingBoxWidth(70)
card.setBoundingBoxHeight(85)
card.setBaseSoundResource(
apply : RSX.sfx_ui_booster_packexplode.audio
walk : RSX.sfx_singe2.audio
attack : RSX.sfx_neutral_sunseer_attack_swing.audio
receiveDamage : RSX.sfx_neutral_sunseer_hit.audio
attackDamage : RSX.sfx_neutral_sunseer_attack_impact.audio
death : RSX.sfx_neutral_sunseer_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f3KeeperAgesBreathing.name
idle : RSX.f3KeeperAgesIdle.name
walk : RSX.f3KeeperAgesRun.name
attack : RSX.f3KeeperAgesAttack.name
attackReleaseDelay: 0.0
attackDelay: 0.25
damage : RSX.f3KeeperAgesHit.name
death : RSX.f3KeeperAgesDeath.name
)
if (identifier == Cards.Faction3.WindGiver)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction3
card.name = "Orbrider"
card.setDescription("Opening Gambit: Return a nearby friendly minion to your action bar.")
card.addKeywordClassToInclude(ModifierOpeningGambit)
card.atk = 2
card.maxHP = 2
card.manaCost = 2
card.rarityId = Rarity.Common
card.setFollowups([
{
id: Cards.Spell.IceCage
spellFilterType: SpellFilterType.AllyDirect
_private: {
followupSourcePattern: CONFIG.PATTERN_3x3
}
}
])
card.setFXResource(["FX.Cards.Neutral.Spelljammer"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_diretidefrenzy.audio
walk : RSX.sfx_singe2.audio
attack : RSX.sfx_f6_waterelemental_attack_swing.audio
receiveDamage : RSX.sfx_f6_waterelemental_hit.audio
attackDamage : RSX.sfx_neutral_fog_attack_impact.audio
death : RSX.sfx_neutral_fog_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f3WindgiverBreathing.name
idle : RSX.f3WindgiverIdle.name
walk : RSX.f3WindgiverRun.name
attack : RSX.f3WindgiverAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.2
damage : RSX.f3WindgiverHit.name
death : RSX.f3WindgiverDeath.name
)
if (identifier == Cards.Spell.IncreasingWinds)
card = new SpellIntensifySpawnEntitiesNearGeneral(gameSession)
card.factionId = Factions.Faction3
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.IncreasingWinds
card.name = "Accumulonimbus"
card.setDescription("Intensify: Summon 2 Wind Dervishes nearby your General.")
card.manaCost = 5
card.rarityId = Rarity.Common
card.spellFilterType = SpellFilterType.None
card.numberToSummon = 2
card.cardDataOrIndexToSpawn = {id: Cards.Faction3.Dervish}
card.addKeywordClassToInclude(ModifierTokenCreator)
card.addKeywordClassToInclude(ModifierIntensify)
card.setInherentModifiersContextObjects([ModifierCounterIntensify.createContextObject()])
card.setFXResource(["FX.Cards.Spell.Accumulonimbus"])
card.setBaseAnimResource(
idle: RSX.iconIncreasingWindsIdle.name
active: RSX.iconIncreasingWindsActive.name
)
card.setBaseSoundResource(
apply : RSX.sfx_spell_entropicdecay.audio
)
if (identifier == Cards.Spell.GoneWithTheWind)
card = new SpellApplyModifiers(gameSession)
card.factionId = Factions.Faction3
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.GoneWithTheWind
card.name = "Wither"
card.setDescription("An enemy minion disappears at the start of your next turn.")
card.manaCost = 3
card.rarityId = Rarity.Rare
removeEntityContextObject = ModifierStartOpponentsTurnWatchRemoveEntity.createContextObject()
removeEntityContextObject.appliedName = "Withering"
removeEntityContextObject.appliedDescription = "Disappears when you end your turn."
removeEntityContextObject.isRemovable = false
card.setTargetModifiersContextObjects([
removeEntityContextObject
])
card.spellFilterType = SpellFilterType.EnemyDirect
card.canTargetGeneral = false
card.setFXResource(["FX.Cards.Spell.Wither"])
card.setBaseSoundResource(
apply : RSX.sfx_f6_icebeetle_death.audio
)
card.setBaseAnimResource(
idle : RSX.iconGoneWithTheWindIdle.name
active : RSX.iconGoneWithTheWindActive.name
)
if (identifier == Cards.Spell.SummoningStones)
card = new SpellSummoningStones(gameSession)
card.factionId = Factions.Faction3
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.SummoningStones
card.name = "Circle of Fabrication"
card.setDescription("Summon one of each Obelysk from your deck on random spaces.")
card.manaCost = 9
card.rarityId = Rarity.Legendary
card.spellFilterType = SpellFilterType.None
card.setFXResource(["FX.Cards.Spell.CircleOfFabrication"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_manavortex.audio
)
card.setBaseAnimResource(
idle : RSX.iconSummoningStonesIdle.name
active : RSX.iconSummoningStonesActive.name
)
if (identifier == Cards.Faction3.CoughingGus)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction3
card.name = "Fifth Canopic"
card.setDescription("The enemy General cannot cast their Bloodbound Spell.")
card.atk = 4
card.maxHP = 8
card.manaCost = 5
card.rarityId = Rarity.Epic
card.setInherentModifiersContextObjects([ModifierEnemyCannotCastBBS.createContextObject()])
card.setFXResource(["FX.Cards.Neutral.SunElemental"])
card.setBoundingBoxWidth(50)
card.setBoundingBoxHeight(90)
card.setBaseSoundResource(
apply : RSX.sfx_spell_blindscorch.audio
walk : RSX.sfx_neutral_sunelemental_impact.audio
attack : RSX.sfx_neutral_sunelemental_attack_swing.audio
receiveDamage : RSX.sfx_neutral_sunelemental_hit.audio
attackDamage : RSX.sfx_neutral_sunelemental_impact.audio
death : RSX.sfx_neutral_sunelemental_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f3SakkakBreathing.name
idle : RSX.f3SakkakIdle.name
walk : RSX.f3SakkakRun.name
attack : RSX.f3SakkakAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.0
damage : RSX.f3SakkakHit.name
death : RSX.f3SakkakDeath.name
)
if (identifier == Cards.Artifact.RepairSword)
card = new Artifact(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction3
card.id = Cards.Artifact.RepairSword
card.name = "Obdurator"
card.setDescription("Your General gains +1 Attack.\nAt the start of your turn, repair all of your artifacts by 1 durability.")
card.manaCost = 2
card.rarityId = Rarity.Epic
card.durability = 3
card.setTargetModifiersContextObjects([
Modifier.createContextObjectWithAttributeBuffs(1,undefined),
ModifierStartTurnWatchRestoreChargeToArtifacts.createContextObject()
])
card.setFXResource(["FX.Cards.Artifact.Winterblade"])
card.setBaseAnimResource(
idle: RSX.iconRepairStaffIdle.name
active: RSX.iconRepairStaffActive.name
)
card.setBaseSoundResource(
apply : RSX.sfx_victory_crest.audio
)
if (identifier == Cards.Faction3.CursedDervish)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction3
card.name = "Dustdrinker"
card.raceId = Races.Dervish
card.setDescription("Intensify: Deal 1 damage to the enemy General and this minion gains +1 Health.")
card.atk = 2
card.maxHP = 1
card.manaCost = 2
card.rarityId = Rarity.Common
card.setInherentModifiersContextObjects([
ModifierIntensifyDamageEnemyGeneral.createContextObject(1),
ModifierIntensifyBuffSelf.createContextObject(0, 1, "Borrowed Time"),
ModifierCounterIntensify.createContextObject()
])
card.setBoundingBoxWidth(100)
card.setBoundingBoxHeight(80)
card.setFXResource(["FX.Cards.Neutral.WhiteWidow"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_icepillar_melt.audio
walk : RSX.sfx_neutral_primordialgazer_death.audio
attack : RSX.sfx_f6_seismicelemental_attack_impact.audio
receiveDamage : RSX.sfx_neutral_golembloodshard_hit.audio
attackDamage : RSX.sfx_f2lanternfox_death.audio
death : RSX.sfx_f2lanternfox_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f3CursedDervishBreathing.name
idle : RSX.f3CursedDervishIdle.name
walk : RSX.f3CursedDervishRun.name
attack : RSX.f3CursedDervishAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.2
damage : RSX.f3CursedDervishHit.name
death : RSX.f3CursedDervishDeath.name
)
if (identifier == Cards.Spell.GrabAThing)
card = new SpellDrawArtifact(gameSession)
card.factionId = Factions.Faction3
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.GrabAThing
card.name = "Planar Foundry"
card.setDescription("Draw an artifact from your deck.")
card.manaCost = 1
card.rarityId = Rarity.Common
card.spellFilterType = SpellFilterType.None
card.setFXResource(["FX.Cards.Spell.PlanarFoundry"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_forcebarrier.audio
)
card.setBaseAnimResource(
idle : RSX.iconGabArtifactIdle.name
active : RSX.iconGabArtifactActive.name
)
if (identifier == Cards.Spell.ThoughtExchange)
card = new SpellThoughtExchange(gameSession)
card.factionId = Factions.Faction3
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.ThoughtExchange
card.name = "Synaptic Arbitrage"
card.setDescription("Give your opponent a minion to take control of nearby enemy minions with less Attack.")
card.manaCost = 4
card.rarityId = Rarity.Epic
card.spellFilterType = SpellFilterType.AllyDirect
card.canTargetGeneral = false
card.setFXResource(["FX.Cards.Spell.SynapticArbitrage"])
card.setBaseAnimResource(
idle: RSX.iconThoughtExchangeIdle.name
active: RSX.iconThoughtExchangeActive.name
)
card.setBaseSoundResource(
apply : RSX.sfx_spell_icepillar.audio
)
if (identifier == Cards.Spell.Metalworking)
card = new SpellMetalworking(gameSession)
card.factionId = Factions.Faction3
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.Metalworking
card.name = "Metalmeld"
card.setDescription("Equip a friendly artifact that was destroyed this game.")
card.manaCost = 2
card.rarityId = Rarity.Rare
card.spellFilterType = SpellFilterType.None
card.setFXResource(["FX.Cards.Spell.Metalmeld"])
card.setBaseAnimResource(
idle: RSX.iconMetalmeldIdle.name
active: RSX.iconMetalmeldActive.name
)
card.setBaseSoundResource(
apply : RSX.sfx_spell_darktransformation.audio
)
if (identifier == Cards.Faction3.GoldenGuide)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction3
card.name = "Khanuum-ka"
card.raceId = Races.Dervish
card.setDescription("Flying, Rush\nDying Wish: A random friendly Dervish disappears, summoning a Khanuum-ka in its place.")
card.atk = 3
card.maxHP = 3
card.manaCost = 5
card.rarityId = Rarity.Legendary
card.setInherentModifiersContextObjects([
ModifierFirstBlood.createContextObject(),
ModifierFlying.createContextObject(),
ModifierDyingWishGoldenGuide.createContextObject()
])
card.setFXResource(["FX.Cards.Neutral.Fireblazer"])
card.setBaseSoundResource(
apply : RSX.sfx_unit_deploy_3.audio
walk : RSX.sfx_singe2.audio
attack : RSX.sfx_neutral_hailstonehowler_attack_swing.audio
receiveDamage : RSX.sfx_neutral_hailstonehowler_hit.audio
attackDamage : RSX.sfx_neutral_hailstonehowler_attack_impact.audio
death : RSX.sfx_neutral_hailstonehowler_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f3GoldenGuideBreathing.name
idle : RSX.f3GoldenGuideIdle.name
walk : RSX.f3GoldenGuideRun.name
attack : RSX.f3GoldenGuideAttack.name
attackReleaseDelay: 0.0
attackDelay: 0.6
damage : RSX.f3GoldenGuideHit.name
death : RSX.f3GoldenGuideDeath.name
)
if (identifier == Cards.Faction3.ScarabPulverizer)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction3
card.name = "Swarmking Scarab"
card.setDescription("Blast\nWhenever this minion blasts, summon 1/1 Scarabyte with Flying and Rush in those spaces.")
card.atk = 5
card.maxHP = 7
card.manaCost = 6
card.rarityId = Rarity.Legendary
card.setInherentModifiersContextObjects([
ModifierBlastAttackStrong.createContextObject(),
ModifierMyAttackWatchScarabBlast.createContextObject()
])
card.addKeywordClassToInclude(ModifierFirstBlood)
card.addKeywordClassToInclude(ModifierFlying)
card.addKeywordClassToInclude(ModifierTokenCreator)
card.setFXResource(["FX.Cards.Neutral.Serpenti"])
card.setBoundingBoxWidth(105)
card.setBoundingBoxHeight(80)
card.setBaseSoundResource(
apply : RSX.sfx_unit_deploy.audio
walk : RSX.sfx_singe2.audio
attack : RSX.sfx_neutral_serpenti_attack_swing.audio
receiveDamage : RSX.sfx_neutral_serpenti_hit.audio
attackDamage : RSX.sfx_neutral_serpenti_attack_impact.audio
death : RSX.sfx_neutral_serpenti_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f3ScarabPulverizerBreathing.name
idle : RSX.f3ScarabPulverizerIdle.name
walk : RSX.f3ScarabPulverizerRun.name
attack : RSX.f3ScarabPulverizerAttack.name
attackReleaseDelay: 0.0
attackDelay: 0.3
damage : RSX.f3ScarabPulverizerHit.name
death : RSX.f3ScarabPulverizerDeath.name
)
if (identifier == Cards.Faction3.Scarab)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction3
card.name = "Scarabyte"
card.setDescription("Flying\nRush")
card.atk = 1
card.maxHP = 1
card.manaCost = 1
card.rarityId = Rarity.TokenUnit
card.setIsHiddenInCollection(true)
card.setInherentModifiersContextObjects([
ModifierFlying.createContextObject(),
ModifierFirstBlood.createContextObject()
])
card.addKeywordClassToInclude(ModifierToken)
card.setFXResource(["FX.Cards.Neutral.BlackLocust"])
card.setBaseSoundResource(
apply : RSX.sfx_summonlegendary.audio
walk : RSX.sfx_neutral_zurael_death.audio
attack : RSX.sfx_neutral_stormatha_attack_swing.audio
receiveDamage : RSX.sfx_neutral_stormatha_hit.audio
attackDamage : RSX.sfx_neutral_stormatha_attack_impact.audio
death : RSX.sfx_neutral_stormatha_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f3MiniScarabBreathing.name
idle : RSX.f3MiniScarabIdle.name
walk : RSX.f3MiniScarabRun.name
attack : RSX.f3MiniScarabAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.2
damage : RSX.f3MiniScarabHit.name
death : RSX.f3MiniScarabDeath.name
)
if (identifier == Cards.Faction3.StaffWielder)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction3
card.name = "Atom Klinger"
card.setDescription("Whenever you equip an artifact, this minion gains +Attack equal to the artifact's cost.")
card.atk = 1
card.maxHP = 5
card.manaCost = 3
card.rarityId = Rarity.Rare
buffName = "Atomized"
card.setInherentModifiersContextObjects([ModifierEquipFriendlyArtifactWatchGainAttackEqualToCost.createContextObject(buffName)])
card.setFXResource(["FX.Cards.Neutral.ArakiHeadhunter"])
card.setBaseSoundResource(
apply : RSX.sfx_neutral_fog_attack_swing.audio
walk : RSX.sfx_neutral_earthwalker_death.audio
attack : RSX.sfx_neutral_arakiheadhunter_attack_swing.audio
receiveDamage : RSX.sfx_neutral_arakiheadhunter_hit.audio
attackDamage : RSX.sfx_neutral_arakiheadhunter_impact.audio
death : RSX.sfx_neutral_arakiheadhunter_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f3StaffWielderBreathing.name
idle : RSX.f3StaffWielderIdle.name
walk : RSX.f3StaffWielderRun.name
attack : RSX.f3StaffWielderAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.2
damage : RSX.f3StaffWielderHit.name
death : RSX.f3StaffWielderDeath.name
)
return card
module.exports = CardFactory_CoreshatterSet_Faction3
| 19453 | # do not add this file to a package
# it is specifically parsed by the package generation script
_ = require 'underscore'
moment = require 'moment'
Logger = require 'app/common/logger'
CONFIG = require('app/common/config')
RSX = require('app/data/resources')
Card = require 'app/sdk/cards/card'
Cards = require 'app/sdk/cards/cardsLookupComplete'
CardType = require 'app/sdk/cards/cardType'
Factions = require 'app/sdk/cards/factionsLookup'
FactionFactory = require 'app/sdk/cards/factionFactory'
Races = require 'app/sdk/cards/racesLookup'
Rarity = require 'app/sdk/cards/rarityLookup'
Unit = require 'app/sdk/entities/unit'
CardSet = require 'app/sdk/cards/cardSetLookup'
Artifact = require 'app/sdk/artifacts/artifact'
SpellFilterType = require 'app/sdk/spells/spellFilterType'
SpellIntensifySpawnEntitiesNearGeneral = require 'app/sdk/spells/spellIntensifySpawnEntitiesNearGeneral'
SpellApplyModifiers = require 'app/sdk/spells/spellApplyModifiers'
SpellSummoningStones = require 'app/sdk/spells/spellSummoningStones'
SpellDrawArtifact = require 'app/sdk/spells/spellDrawArtifact'
SpellThoughtExchange = require 'app/sdk/spells/spellThoughtExchange'
SpellMetalworking = require 'app/sdk/spells/spellMetalworking'
Modifier = require 'app/sdk/modifiers/modifier'
ModifierOpeningGambit = require 'app/sdk/modifiers/modifierOpeningGambit'
ModifierStartOpponentsTurnWatchRemoveEntity = require 'app/sdk/modifiers/modifierStartOpponentsTurnWatchRemoveEntity'
ModifierEnemyCannotCastBBS = require 'app/sdk/modifiers/modifierEnemyCannotCastBBS'
ModifierStartTurnWatchRestoreChargeToArtifacts = require 'app/sdk/modifiers/modifierStartTurnWatchRestoreChargeToArtifacts'
ModifierIntensifyBuffSelf = require 'app/sdk/modifiers/modifierIntensifyBuffSelf'
ModifierIntensifyDamageEnemyGeneral = require 'app/sdk/modifiers/modifierIntensifyDamageEnemyGeneral'
ModifierFlying = require 'app/sdk/modifiers/modifierFlying'
ModifierStartsInHand = require 'app/sdk/modifiers/modifierStartsInHand'
ModifierForcefield = require 'app/sdk/modifiers/modifierForcefield'
ModifierFirstBlood = require 'app/sdk/modifiers/modifierFirstBlood'
ModifierBlastAttackStrong = require 'app/sdk/modifiers/modifierBlastAttackStrong'
ModifierMyAttackWatchScarabBlast = require 'app/sdk/modifiers/modifierMyAttackWatchScarabBlast'
ModifierEquipFriendlyArtifactWatchGainAttackEqualToCost = require 'app/sdk/modifiers/modifierEquipFriendlyArtifactWatchGainAttackEqualToCost'
ModifierOnSummonFromHandApplyEmblems = require 'app/sdk/modifiers/modifierOnSummonFromHandApplyEmblems'
ModifierDyingWishGoldenGuide = require 'app/sdk/modifiers/modifierDyingWishGoldenGuide'
ModifierToken = require 'app/sdk/modifiers/modifierToken'
ModifierTokenCreator = require 'app/sdk/modifiers/modifierTokenCreator'
ModifierFateVetruvianMovementQuest = require 'app/sdk/modifiers/modifierFateVetruvianMovementQuest'
ModifierCannotBeReplaced = require 'app/sdk/modifiers/modifierCannotBeReplaced'
ModifierIntensify = require 'app/sdk/modifiers/modifierIntensify'
ModifierCounterIntensify = require 'app/sdk/modifiers/modifierCounterIntensify'
ModifierCannotBeRemovedFromHand = require 'app/sdk/modifiers/modifierCannotBeRemovedFromHand'
PlayerModifierEmblemSituationalVetQuestFrenzy = require 'app/sdk/playerModifiers/playerModifierEmblemSituationalVetQuestFrenzy'
PlayerModifierEmblemSituationalVetQuestFlying = require 'app/sdk/playerModifiers/playerModifierEmblemSituationalVetQuestFlying'
PlayerModifierEmblemSituationalVetQuestCelerity = require 'app/sdk/playerModifiers/playerModifierEmblemSituationalVetQuestCelerity'
i18next = require 'i18next'
if i18next.t() is undefined
i18next.t = (text) ->
return text
class CardFactory_CoreshatterSet_Faction3
###*
* Returns a card that matches the identifier.
* @param {Number|String} identifier
* @param {GameSession} gameSession
* @returns {Card}
###
@cardForIdentifier: (identifier,gameSession) ->
card = null
if (identifier == Cards.Faction3.KeeperOfAges)
card = new Unit(gameSession)
card.factionId = Factions.Faction3
card.setCardSetId(CardSet.Coreshatter)
card.name = "Notion of Starless Eternity"
card.setDescription("Trial: General reaches the other edge of the battlefield with an equipped artifact.\nDestiny: Each equipped artifact gives your General a tier of ascension.")
card.atk = 3
card.maxHP = 3
card.manaCost = 6
card.rarityId = Rarity.Mythron
emblemModifier1 = PlayerModifierEmblemSituationalVetQuestFrenzy.createContextObject(1)
emblemModifier1.appliedName = "Overcome Eternity"
emblemModifier1.appliedDescription = "Each equipped artifact gives your General a tier of ascension: Frenzy, Flying, Celerity."
emblemModifier2 = PlayerModifierEmblemSituationalVetQuestFlying.createContextObject(2)
emblemModifier2.isHiddenToUI = true
emblemModifier3 = PlayerModifierEmblemSituationalVetQuestCelerity.createContextObject(3)
emblemModifier3.isHiddenToUI = true
card.setInherentModifiersContextObjects([
ModifierStartsInHand.createContextObject(),
ModifierCannotBeReplaced.createContextObject(),
ModifierFateVetruvianMovementQuest.createContextObject(),
ModifierOnSummonFromHandApplyEmblems.createContextObject([emblemModifier1, emblemModifier2, emblemModifier3], true, false),
ModifierCannotBeRemovedFromHand.createContextObject()
])
card.setFXResource(["FX.Cards.Neutral.SwornDefender"])
card.setBoundingBoxWidth(70)
card.setBoundingBoxHeight(85)
card.setBaseSoundResource(
apply : RSX.sfx_ui_booster_packexplode.audio
walk : RSX.sfx_singe2.audio
attack : RSX.sfx_neutral_sunseer_attack_swing.audio
receiveDamage : RSX.sfx_neutral_sunseer_hit.audio
attackDamage : RSX.sfx_neutral_sunseer_attack_impact.audio
death : RSX.sfx_neutral_sunseer_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f3KeeperAgesBreathing.name
idle : RSX.f3KeeperAgesIdle.name
walk : RSX.f3KeeperAgesRun.name
attack : RSX.f3KeeperAgesAttack.name
attackReleaseDelay: 0.0
attackDelay: 0.25
damage : RSX.f3KeeperAgesHit.name
death : RSX.f3KeeperAgesDeath.name
)
if (identifier == Cards.Faction3.WindGiver)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction3
card.name = "<NAME>"
card.setDescription("Opening Gambit: Return a nearby friendly minion to your action bar.")
card.addKeywordClassToInclude(ModifierOpeningGambit)
card.atk = 2
card.maxHP = 2
card.manaCost = 2
card.rarityId = Rarity.Common
card.setFollowups([
{
id: Cards.Spell.IceCage
spellFilterType: SpellFilterType.AllyDirect
_private: {
followupSourcePattern: CONFIG.PATTERN_3x3
}
}
])
card.setFXResource(["FX.Cards.Neutral.Spelljammer"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_diretidefrenzy.audio
walk : RSX.sfx_singe2.audio
attack : RSX.sfx_f6_waterelemental_attack_swing.audio
receiveDamage : RSX.sfx_f6_waterelemental_hit.audio
attackDamage : RSX.sfx_neutral_fog_attack_impact.audio
death : RSX.sfx_neutral_fog_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f3WindgiverBreathing.name
idle : RSX.f3WindgiverIdle.name
walk : RSX.f3WindgiverRun.name
attack : RSX.f3WindgiverAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.2
damage : RSX.f3WindgiverHit.name
death : RSX.f3WindgiverDeath.name
)
if (identifier == Cards.Spell.IncreasingWinds)
card = new SpellIntensifySpawnEntitiesNearGeneral(gameSession)
card.factionId = Factions.Faction3
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.IncreasingWinds
card.name = "<NAME>"
card.setDescription("Intensify: Summon 2 Wind Dervishes nearby your General.")
card.manaCost = 5
card.rarityId = Rarity.Common
card.spellFilterType = SpellFilterType.None
card.numberToSummon = 2
card.cardDataOrIndexToSpawn = {id: Cards.Faction3.Dervish}
card.addKeywordClassToInclude(ModifierTokenCreator)
card.addKeywordClassToInclude(ModifierIntensify)
card.setInherentModifiersContextObjects([ModifierCounterIntensify.createContextObject()])
card.setFXResource(["FX.Cards.Spell.Accumulonimbus"])
card.setBaseAnimResource(
idle: RSX.iconIncreasingWindsIdle.name
active: RSX.iconIncreasingWindsActive.name
)
card.setBaseSoundResource(
apply : RSX.sfx_spell_entropicdecay.audio
)
if (identifier == Cards.Spell.GoneWithTheWind)
card = new SpellApplyModifiers(gameSession)
card.factionId = Factions.Faction3
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.GoneWithTheWind
card.name = "Wither"
card.setDescription("An enemy minion disappears at the start of your next turn.")
card.manaCost = 3
card.rarityId = Rarity.Rare
removeEntityContextObject = ModifierStartOpponentsTurnWatchRemoveEntity.createContextObject()
removeEntityContextObject.appliedName = "Withering"
removeEntityContextObject.appliedDescription = "Disappears when you end your turn."
removeEntityContextObject.isRemovable = false
card.setTargetModifiersContextObjects([
removeEntityContextObject
])
card.spellFilterType = SpellFilterType.EnemyDirect
card.canTargetGeneral = false
card.setFXResource(["FX.Cards.Spell.Wither"])
card.setBaseSoundResource(
apply : RSX.sfx_f6_icebeetle_death.audio
)
card.setBaseAnimResource(
idle : RSX.iconGoneWithTheWindIdle.name
active : RSX.iconGoneWithTheWindActive.name
)
if (identifier == Cards.Spell.SummoningStones)
card = new SpellSummoningStones(gameSession)
card.factionId = Factions.Faction3
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.SummoningStones
card.name = "Circle of Fabrication"
card.setDescription("Summon one of each Obelysk from your deck on random spaces.")
card.manaCost = 9
card.rarityId = Rarity.Legendary
card.spellFilterType = SpellFilterType.None
card.setFXResource(["FX.Cards.Spell.CircleOfFabrication"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_manavortex.audio
)
card.setBaseAnimResource(
idle : RSX.iconSummoningStonesIdle.name
active : RSX.iconSummoningStonesActive.name
)
if (identifier == Cards.Faction3.CoughingGus)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction3
card.name = "<NAME>"
card.setDescription("The enemy General cannot cast their Bloodbound Spell.")
card.atk = 4
card.maxHP = 8
card.manaCost = 5
card.rarityId = Rarity.Epic
card.setInherentModifiersContextObjects([ModifierEnemyCannotCastBBS.createContextObject()])
card.setFXResource(["FX.Cards.Neutral.SunElemental"])
card.setBoundingBoxWidth(50)
card.setBoundingBoxHeight(90)
card.setBaseSoundResource(
apply : RSX.sfx_spell_blindscorch.audio
walk : RSX.sfx_neutral_sunelemental_impact.audio
attack : RSX.sfx_neutral_sunelemental_attack_swing.audio
receiveDamage : RSX.sfx_neutral_sunelemental_hit.audio
attackDamage : RSX.sfx_neutral_sunelemental_impact.audio
death : RSX.sfx_neutral_sunelemental_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f3SakkakBreathing.name
idle : RSX.f3SakkakIdle.name
walk : RSX.f3SakkakRun.name
attack : RSX.f3SakkakAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.0
damage : RSX.f3SakkakHit.name
death : RSX.f3SakkakDeath.name
)
if (identifier == Cards.Artifact.RepairSword)
card = new Artifact(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction3
card.id = Cards.Artifact.RepairSword
card.name = "<NAME>"
card.setDescription("Your General gains +1 Attack.\nAt the start of your turn, repair all of your artifacts by 1 durability.")
card.manaCost = 2
card.rarityId = Rarity.Epic
card.durability = 3
card.setTargetModifiersContextObjects([
Modifier.createContextObjectWithAttributeBuffs(1,undefined),
ModifierStartTurnWatchRestoreChargeToArtifacts.createContextObject()
])
card.setFXResource(["FX.Cards.Artifact.Winterblade"])
card.setBaseAnimResource(
idle: RSX.iconRepairStaffIdle.name
active: RSX.iconRepairStaffActive.name
)
card.setBaseSoundResource(
apply : RSX.sfx_victory_crest.audio
)
if (identifier == Cards.Faction3.CursedDervish)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction3
card.name = "<NAME>"
card.raceId = Races.Dervish
card.setDescription("Intensify: Deal 1 damage to the enemy General and this minion gains +1 Health.")
card.atk = 2
card.maxHP = 1
card.manaCost = 2
card.rarityId = Rarity.Common
card.setInherentModifiersContextObjects([
ModifierIntensifyDamageEnemyGeneral.createContextObject(1),
ModifierIntensifyBuffSelf.createContextObject(0, 1, "Borrowed Time"),
ModifierCounterIntensify.createContextObject()
])
card.setBoundingBoxWidth(100)
card.setBoundingBoxHeight(80)
card.setFXResource(["FX.Cards.Neutral.WhiteWidow"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_icepillar_melt.audio
walk : RSX.sfx_neutral_primordialgazer_death.audio
attack : RSX.sfx_f6_seismicelemental_attack_impact.audio
receiveDamage : RSX.sfx_neutral_golembloodshard_hit.audio
attackDamage : RSX.sfx_f2lanternfox_death.audio
death : RSX.sfx_f2lanternfox_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f3CursedDervishBreathing.name
idle : RSX.f3CursedDervishIdle.name
walk : RSX.f3CursedDervishRun.name
attack : RSX.f3CursedDervishAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.2
damage : RSX.f3CursedDervishHit.name
death : RSX.f3CursedDervishDeath.name
)
if (identifier == Cards.Spell.GrabAThing)
card = new SpellDrawArtifact(gameSession)
card.factionId = Factions.Faction3
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.GrabAThing
card.name = "<NAME>ar Foundry"
card.setDescription("Draw an artifact from your deck.")
card.manaCost = 1
card.rarityId = Rarity.Common
card.spellFilterType = SpellFilterType.None
card.setFXResource(["FX.Cards.Spell.PlanarFoundry"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_forcebarrier.audio
)
card.setBaseAnimResource(
idle : RSX.iconGabArtifactIdle.name
active : RSX.iconGabArtifactActive.name
)
if (identifier == Cards.Spell.ThoughtExchange)
card = new SpellThoughtExchange(gameSession)
card.factionId = Factions.Faction3
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.ThoughtExchange
card.name = "Synaptic Arbitrage"
card.setDescription("Give your opponent a minion to take control of nearby enemy minions with less Attack.")
card.manaCost = 4
card.rarityId = Rarity.Epic
card.spellFilterType = SpellFilterType.AllyDirect
card.canTargetGeneral = false
card.setFXResource(["FX.Cards.Spell.SynapticArbitrage"])
card.setBaseAnimResource(
idle: RSX.iconThoughtExchangeIdle.name
active: RSX.iconThoughtExchangeActive.name
)
card.setBaseSoundResource(
apply : RSX.sfx_spell_icepillar.audio
)
if (identifier == Cards.Spell.Metalworking)
card = new SpellMetalworking(gameSession)
card.factionId = Factions.Faction3
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.Metalworking
card.name = "<NAME>meld"
card.setDescription("Equip a friendly artifact that was destroyed this game.")
card.manaCost = 2
card.rarityId = Rarity.Rare
card.spellFilterType = SpellFilterType.None
card.setFXResource(["FX.Cards.Spell.Metalmeld"])
card.setBaseAnimResource(
idle: RSX.iconMetalmeldIdle.name
active: RSX.iconMetalmeldActive.name
)
card.setBaseSoundResource(
apply : RSX.sfx_spell_darktransformation.audio
)
if (identifier == Cards.Faction3.GoldenGuide)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction3
card.name = "<NAME>"
card.raceId = Races.Dervish
card.setDescription("Flying, Rush\nDying Wish: A random friendly Dervish disappears, summoning a Khanuum-ka in its place.")
card.atk = 3
card.maxHP = 3
card.manaCost = 5
card.rarityId = Rarity.Legendary
card.setInherentModifiersContextObjects([
ModifierFirstBlood.createContextObject(),
ModifierFlying.createContextObject(),
ModifierDyingWishGoldenGuide.createContextObject()
])
card.setFXResource(["FX.Cards.Neutral.Fireblazer"])
card.setBaseSoundResource(
apply : RSX.sfx_unit_deploy_3.audio
walk : RSX.sfx_singe2.audio
attack : RSX.sfx_neutral_hailstonehowler_attack_swing.audio
receiveDamage : RSX.sfx_neutral_hailstonehowler_hit.audio
attackDamage : RSX.sfx_neutral_hailstonehowler_attack_impact.audio
death : RSX.sfx_neutral_hailstonehowler_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f3GoldenGuideBreathing.name
idle : RSX.f3GoldenGuideIdle.name
walk : RSX.f3GoldenGuideRun.name
attack : RSX.f3GoldenGuideAttack.name
attackReleaseDelay: 0.0
attackDelay: 0.6
damage : RSX.f3GoldenGuideHit.name
death : RSX.f3GoldenGuideDeath.name
)
if (identifier == Cards.Faction3.ScarabPulverizer)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction3
card.name = "<NAME>"
card.setDescription("Blast\nWhenever this minion blasts, summon 1/1 Scarabyte with Flying and Rush in those spaces.")
card.atk = 5
card.maxHP = 7
card.manaCost = 6
card.rarityId = Rarity.Legendary
card.setInherentModifiersContextObjects([
ModifierBlastAttackStrong.createContextObject(),
ModifierMyAttackWatchScarabBlast.createContextObject()
])
card.addKeywordClassToInclude(ModifierFirstBlood)
card.addKeywordClassToInclude(ModifierFlying)
card.addKeywordClassToInclude(ModifierTokenCreator)
card.setFXResource(["FX.Cards.Neutral.Serpenti"])
card.setBoundingBoxWidth(105)
card.setBoundingBoxHeight(80)
card.setBaseSoundResource(
apply : RSX.sfx_unit_deploy.audio
walk : RSX.sfx_singe2.audio
attack : RSX.sfx_neutral_serpenti_attack_swing.audio
receiveDamage : RSX.sfx_neutral_serpenti_hit.audio
attackDamage : RSX.sfx_neutral_serpenti_attack_impact.audio
death : RSX.sfx_neutral_serpenti_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f3ScarabPulverizerBreathing.name
idle : RSX.f3ScarabPulverizerIdle.name
walk : RSX.f3ScarabPulverizerRun.name
attack : RSX.f3ScarabPulverizerAttack.name
attackReleaseDelay: 0.0
attackDelay: 0.3
damage : RSX.f3ScarabPulverizerHit.name
death : RSX.f3ScarabPulverizerDeath.name
)
if (identifier == Cards.Faction3.Scarab)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction3
card.name = "<NAME>"
card.setDescription("Flying\nRush")
card.atk = 1
card.maxHP = 1
card.manaCost = 1
card.rarityId = Rarity.TokenUnit
card.setIsHiddenInCollection(true)
card.setInherentModifiersContextObjects([
ModifierFlying.createContextObject(),
ModifierFirstBlood.createContextObject()
])
card.addKeywordClassToInclude(ModifierToken)
card.setFXResource(["FX.Cards.Neutral.BlackLocust"])
card.setBaseSoundResource(
apply : RSX.sfx_summonlegendary.audio
walk : RSX.sfx_neutral_zurael_death.audio
attack : RSX.sfx_neutral_stormatha_attack_swing.audio
receiveDamage : RSX.sfx_neutral_stormatha_hit.audio
attackDamage : RSX.sfx_neutral_stormatha_attack_impact.audio
death : RSX.sfx_neutral_stormatha_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f3MiniScarabBreathing.name
idle : RSX.f3MiniScarabIdle.name
walk : RSX.f3MiniScarabRun.name
attack : RSX.f3MiniScarabAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.2
damage : RSX.f3MiniScarabHit.name
death : RSX.f3MiniScarabDeath.name
)
if (identifier == Cards.Faction3.StaffWielder)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction3
card.name = "<NAME>"
card.setDescription("Whenever you equip an artifact, this minion gains +Attack equal to the artifact's cost.")
card.atk = 1
card.maxHP = 5
card.manaCost = 3
card.rarityId = Rarity.Rare
buffName = "Atomized"
card.setInherentModifiersContextObjects([ModifierEquipFriendlyArtifactWatchGainAttackEqualToCost.createContextObject(buffName)])
card.setFXResource(["FX.Cards.Neutral.ArakiHeadhunter"])
card.setBaseSoundResource(
apply : RSX.sfx_neutral_fog_attack_swing.audio
walk : RSX.sfx_neutral_earthwalker_death.audio
attack : RSX.sfx_neutral_arakiheadhunter_attack_swing.audio
receiveDamage : RSX.sfx_neutral_arakiheadhunter_hit.audio
attackDamage : RSX.sfx_neutral_arakiheadhunter_impact.audio
death : RSX.sfx_neutral_arakiheadhunter_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f3StaffWielderBreathing.name
idle : RSX.f3StaffWielderIdle.name
walk : RSX.f3StaffWielderRun.name
attack : RSX.f3StaffWielderAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.2
damage : RSX.f3StaffWielderHit.name
death : RSX.f3StaffWielderDeath.name
)
return card
module.exports = CardFactory_CoreshatterSet_Faction3
| true | # do not add this file to a package
# it is specifically parsed by the package generation script
_ = require 'underscore'
moment = require 'moment'
Logger = require 'app/common/logger'
CONFIG = require('app/common/config')
RSX = require('app/data/resources')
Card = require 'app/sdk/cards/card'
Cards = require 'app/sdk/cards/cardsLookupComplete'
CardType = require 'app/sdk/cards/cardType'
Factions = require 'app/sdk/cards/factionsLookup'
FactionFactory = require 'app/sdk/cards/factionFactory'
Races = require 'app/sdk/cards/racesLookup'
Rarity = require 'app/sdk/cards/rarityLookup'
Unit = require 'app/sdk/entities/unit'
CardSet = require 'app/sdk/cards/cardSetLookup'
Artifact = require 'app/sdk/artifacts/artifact'
SpellFilterType = require 'app/sdk/spells/spellFilterType'
SpellIntensifySpawnEntitiesNearGeneral = require 'app/sdk/spells/spellIntensifySpawnEntitiesNearGeneral'
SpellApplyModifiers = require 'app/sdk/spells/spellApplyModifiers'
SpellSummoningStones = require 'app/sdk/spells/spellSummoningStones'
SpellDrawArtifact = require 'app/sdk/spells/spellDrawArtifact'
SpellThoughtExchange = require 'app/sdk/spells/spellThoughtExchange'
SpellMetalworking = require 'app/sdk/spells/spellMetalworking'
Modifier = require 'app/sdk/modifiers/modifier'
ModifierOpeningGambit = require 'app/sdk/modifiers/modifierOpeningGambit'
ModifierStartOpponentsTurnWatchRemoveEntity = require 'app/sdk/modifiers/modifierStartOpponentsTurnWatchRemoveEntity'
ModifierEnemyCannotCastBBS = require 'app/sdk/modifiers/modifierEnemyCannotCastBBS'
ModifierStartTurnWatchRestoreChargeToArtifacts = require 'app/sdk/modifiers/modifierStartTurnWatchRestoreChargeToArtifacts'
ModifierIntensifyBuffSelf = require 'app/sdk/modifiers/modifierIntensifyBuffSelf'
ModifierIntensifyDamageEnemyGeneral = require 'app/sdk/modifiers/modifierIntensifyDamageEnemyGeneral'
ModifierFlying = require 'app/sdk/modifiers/modifierFlying'
ModifierStartsInHand = require 'app/sdk/modifiers/modifierStartsInHand'
ModifierForcefield = require 'app/sdk/modifiers/modifierForcefield'
ModifierFirstBlood = require 'app/sdk/modifiers/modifierFirstBlood'
ModifierBlastAttackStrong = require 'app/sdk/modifiers/modifierBlastAttackStrong'
ModifierMyAttackWatchScarabBlast = require 'app/sdk/modifiers/modifierMyAttackWatchScarabBlast'
ModifierEquipFriendlyArtifactWatchGainAttackEqualToCost = require 'app/sdk/modifiers/modifierEquipFriendlyArtifactWatchGainAttackEqualToCost'
ModifierOnSummonFromHandApplyEmblems = require 'app/sdk/modifiers/modifierOnSummonFromHandApplyEmblems'
ModifierDyingWishGoldenGuide = require 'app/sdk/modifiers/modifierDyingWishGoldenGuide'
ModifierToken = require 'app/sdk/modifiers/modifierToken'
ModifierTokenCreator = require 'app/sdk/modifiers/modifierTokenCreator'
ModifierFateVetruvianMovementQuest = require 'app/sdk/modifiers/modifierFateVetruvianMovementQuest'
ModifierCannotBeReplaced = require 'app/sdk/modifiers/modifierCannotBeReplaced'
ModifierIntensify = require 'app/sdk/modifiers/modifierIntensify'
ModifierCounterIntensify = require 'app/sdk/modifiers/modifierCounterIntensify'
ModifierCannotBeRemovedFromHand = require 'app/sdk/modifiers/modifierCannotBeRemovedFromHand'
PlayerModifierEmblemSituationalVetQuestFrenzy = require 'app/sdk/playerModifiers/playerModifierEmblemSituationalVetQuestFrenzy'
PlayerModifierEmblemSituationalVetQuestFlying = require 'app/sdk/playerModifiers/playerModifierEmblemSituationalVetQuestFlying'
PlayerModifierEmblemSituationalVetQuestCelerity = require 'app/sdk/playerModifiers/playerModifierEmblemSituationalVetQuestCelerity'
i18next = require 'i18next'
if i18next.t() is undefined
i18next.t = (text) ->
return text
class CardFactory_CoreshatterSet_Faction3
###*
* Returns a card that matches the identifier.
* @param {Number|String} identifier
* @param {GameSession} gameSession
* @returns {Card}
###
@cardForIdentifier: (identifier,gameSession) ->
card = null
if (identifier == Cards.Faction3.KeeperOfAges)
card = new Unit(gameSession)
card.factionId = Factions.Faction3
card.setCardSetId(CardSet.Coreshatter)
card.name = "Notion of Starless Eternity"
card.setDescription("Trial: General reaches the other edge of the battlefield with an equipped artifact.\nDestiny: Each equipped artifact gives your General a tier of ascension.")
card.atk = 3
card.maxHP = 3
card.manaCost = 6
card.rarityId = Rarity.Mythron
emblemModifier1 = PlayerModifierEmblemSituationalVetQuestFrenzy.createContextObject(1)
emblemModifier1.appliedName = "Overcome Eternity"
emblemModifier1.appliedDescription = "Each equipped artifact gives your General a tier of ascension: Frenzy, Flying, Celerity."
emblemModifier2 = PlayerModifierEmblemSituationalVetQuestFlying.createContextObject(2)
emblemModifier2.isHiddenToUI = true
emblemModifier3 = PlayerModifierEmblemSituationalVetQuestCelerity.createContextObject(3)
emblemModifier3.isHiddenToUI = true
card.setInherentModifiersContextObjects([
ModifierStartsInHand.createContextObject(),
ModifierCannotBeReplaced.createContextObject(),
ModifierFateVetruvianMovementQuest.createContextObject(),
ModifierOnSummonFromHandApplyEmblems.createContextObject([emblemModifier1, emblemModifier2, emblemModifier3], true, false),
ModifierCannotBeRemovedFromHand.createContextObject()
])
card.setFXResource(["FX.Cards.Neutral.SwornDefender"])
card.setBoundingBoxWidth(70)
card.setBoundingBoxHeight(85)
card.setBaseSoundResource(
apply : RSX.sfx_ui_booster_packexplode.audio
walk : RSX.sfx_singe2.audio
attack : RSX.sfx_neutral_sunseer_attack_swing.audio
receiveDamage : RSX.sfx_neutral_sunseer_hit.audio
attackDamage : RSX.sfx_neutral_sunseer_attack_impact.audio
death : RSX.sfx_neutral_sunseer_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f3KeeperAgesBreathing.name
idle : RSX.f3KeeperAgesIdle.name
walk : RSX.f3KeeperAgesRun.name
attack : RSX.f3KeeperAgesAttack.name
attackReleaseDelay: 0.0
attackDelay: 0.25
damage : RSX.f3KeeperAgesHit.name
death : RSX.f3KeeperAgesDeath.name
)
if (identifier == Cards.Faction3.WindGiver)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction3
card.name = "PI:NAME:<NAME>END_PI"
card.setDescription("Opening Gambit: Return a nearby friendly minion to your action bar.")
card.addKeywordClassToInclude(ModifierOpeningGambit)
card.atk = 2
card.maxHP = 2
card.manaCost = 2
card.rarityId = Rarity.Common
card.setFollowups([
{
id: Cards.Spell.IceCage
spellFilterType: SpellFilterType.AllyDirect
_private: {
followupSourcePattern: CONFIG.PATTERN_3x3
}
}
])
card.setFXResource(["FX.Cards.Neutral.Spelljammer"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_diretidefrenzy.audio
walk : RSX.sfx_singe2.audio
attack : RSX.sfx_f6_waterelemental_attack_swing.audio
receiveDamage : RSX.sfx_f6_waterelemental_hit.audio
attackDamage : RSX.sfx_neutral_fog_attack_impact.audio
death : RSX.sfx_neutral_fog_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f3WindgiverBreathing.name
idle : RSX.f3WindgiverIdle.name
walk : RSX.f3WindgiverRun.name
attack : RSX.f3WindgiverAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.2
damage : RSX.f3WindgiverHit.name
death : RSX.f3WindgiverDeath.name
)
if (identifier == Cards.Spell.IncreasingWinds)
card = new SpellIntensifySpawnEntitiesNearGeneral(gameSession)
card.factionId = Factions.Faction3
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.IncreasingWinds
card.name = "PI:NAME:<NAME>END_PI"
card.setDescription("Intensify: Summon 2 Wind Dervishes nearby your General.")
card.manaCost = 5
card.rarityId = Rarity.Common
card.spellFilterType = SpellFilterType.None
card.numberToSummon = 2
card.cardDataOrIndexToSpawn = {id: Cards.Faction3.Dervish}
card.addKeywordClassToInclude(ModifierTokenCreator)
card.addKeywordClassToInclude(ModifierIntensify)
card.setInherentModifiersContextObjects([ModifierCounterIntensify.createContextObject()])
card.setFXResource(["FX.Cards.Spell.Accumulonimbus"])
card.setBaseAnimResource(
idle: RSX.iconIncreasingWindsIdle.name
active: RSX.iconIncreasingWindsActive.name
)
card.setBaseSoundResource(
apply : RSX.sfx_spell_entropicdecay.audio
)
if (identifier == Cards.Spell.GoneWithTheWind)
card = new SpellApplyModifiers(gameSession)
card.factionId = Factions.Faction3
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.GoneWithTheWind
card.name = "Wither"
card.setDescription("An enemy minion disappears at the start of your next turn.")
card.manaCost = 3
card.rarityId = Rarity.Rare
removeEntityContextObject = ModifierStartOpponentsTurnWatchRemoveEntity.createContextObject()
removeEntityContextObject.appliedName = "Withering"
removeEntityContextObject.appliedDescription = "Disappears when you end your turn."
removeEntityContextObject.isRemovable = false
card.setTargetModifiersContextObjects([
removeEntityContextObject
])
card.spellFilterType = SpellFilterType.EnemyDirect
card.canTargetGeneral = false
card.setFXResource(["FX.Cards.Spell.Wither"])
card.setBaseSoundResource(
apply : RSX.sfx_f6_icebeetle_death.audio
)
card.setBaseAnimResource(
idle : RSX.iconGoneWithTheWindIdle.name
active : RSX.iconGoneWithTheWindActive.name
)
if (identifier == Cards.Spell.SummoningStones)
card = new SpellSummoningStones(gameSession)
card.factionId = Factions.Faction3
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.SummoningStones
card.name = "Circle of Fabrication"
card.setDescription("Summon one of each Obelysk from your deck on random spaces.")
card.manaCost = 9
card.rarityId = Rarity.Legendary
card.spellFilterType = SpellFilterType.None
card.setFXResource(["FX.Cards.Spell.CircleOfFabrication"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_manavortex.audio
)
card.setBaseAnimResource(
idle : RSX.iconSummoningStonesIdle.name
active : RSX.iconSummoningStonesActive.name
)
if (identifier == Cards.Faction3.CoughingGus)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction3
card.name = "PI:NAME:<NAME>END_PI"
card.setDescription("The enemy General cannot cast their Bloodbound Spell.")
card.atk = 4
card.maxHP = 8
card.manaCost = 5
card.rarityId = Rarity.Epic
card.setInherentModifiersContextObjects([ModifierEnemyCannotCastBBS.createContextObject()])
card.setFXResource(["FX.Cards.Neutral.SunElemental"])
card.setBoundingBoxWidth(50)
card.setBoundingBoxHeight(90)
card.setBaseSoundResource(
apply : RSX.sfx_spell_blindscorch.audio
walk : RSX.sfx_neutral_sunelemental_impact.audio
attack : RSX.sfx_neutral_sunelemental_attack_swing.audio
receiveDamage : RSX.sfx_neutral_sunelemental_hit.audio
attackDamage : RSX.sfx_neutral_sunelemental_impact.audio
death : RSX.sfx_neutral_sunelemental_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f3SakkakBreathing.name
idle : RSX.f3SakkakIdle.name
walk : RSX.f3SakkakRun.name
attack : RSX.f3SakkakAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.0
damage : RSX.f3SakkakHit.name
death : RSX.f3SakkakDeath.name
)
if (identifier == Cards.Artifact.RepairSword)
card = new Artifact(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction3
card.id = Cards.Artifact.RepairSword
card.name = "PI:NAME:<NAME>END_PI"
card.setDescription("Your General gains +1 Attack.\nAt the start of your turn, repair all of your artifacts by 1 durability.")
card.manaCost = 2
card.rarityId = Rarity.Epic
card.durability = 3
card.setTargetModifiersContextObjects([
Modifier.createContextObjectWithAttributeBuffs(1,undefined),
ModifierStartTurnWatchRestoreChargeToArtifacts.createContextObject()
])
card.setFXResource(["FX.Cards.Artifact.Winterblade"])
card.setBaseAnimResource(
idle: RSX.iconRepairStaffIdle.name
active: RSX.iconRepairStaffActive.name
)
card.setBaseSoundResource(
apply : RSX.sfx_victory_crest.audio
)
if (identifier == Cards.Faction3.CursedDervish)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction3
card.name = "PI:NAME:<NAME>END_PI"
card.raceId = Races.Dervish
card.setDescription("Intensify: Deal 1 damage to the enemy General and this minion gains +1 Health.")
card.atk = 2
card.maxHP = 1
card.manaCost = 2
card.rarityId = Rarity.Common
card.setInherentModifiersContextObjects([
ModifierIntensifyDamageEnemyGeneral.createContextObject(1),
ModifierIntensifyBuffSelf.createContextObject(0, 1, "Borrowed Time"),
ModifierCounterIntensify.createContextObject()
])
card.setBoundingBoxWidth(100)
card.setBoundingBoxHeight(80)
card.setFXResource(["FX.Cards.Neutral.WhiteWidow"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_icepillar_melt.audio
walk : RSX.sfx_neutral_primordialgazer_death.audio
attack : RSX.sfx_f6_seismicelemental_attack_impact.audio
receiveDamage : RSX.sfx_neutral_golembloodshard_hit.audio
attackDamage : RSX.sfx_f2lanternfox_death.audio
death : RSX.sfx_f2lanternfox_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f3CursedDervishBreathing.name
idle : RSX.f3CursedDervishIdle.name
walk : RSX.f3CursedDervishRun.name
attack : RSX.f3CursedDervishAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.2
damage : RSX.f3CursedDervishHit.name
death : RSX.f3CursedDervishDeath.name
)
if (identifier == Cards.Spell.GrabAThing)
card = new SpellDrawArtifact(gameSession)
card.factionId = Factions.Faction3
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.GrabAThing
card.name = "PI:NAME:<NAME>END_PIar Foundry"
card.setDescription("Draw an artifact from your deck.")
card.manaCost = 1
card.rarityId = Rarity.Common
card.spellFilterType = SpellFilterType.None
card.setFXResource(["FX.Cards.Spell.PlanarFoundry"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_forcebarrier.audio
)
card.setBaseAnimResource(
idle : RSX.iconGabArtifactIdle.name
active : RSX.iconGabArtifactActive.name
)
if (identifier == Cards.Spell.ThoughtExchange)
card = new SpellThoughtExchange(gameSession)
card.factionId = Factions.Faction3
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.ThoughtExchange
card.name = "Synaptic Arbitrage"
card.setDescription("Give your opponent a minion to take control of nearby enemy minions with less Attack.")
card.manaCost = 4
card.rarityId = Rarity.Epic
card.spellFilterType = SpellFilterType.AllyDirect
card.canTargetGeneral = false
card.setFXResource(["FX.Cards.Spell.SynapticArbitrage"])
card.setBaseAnimResource(
idle: RSX.iconThoughtExchangeIdle.name
active: RSX.iconThoughtExchangeActive.name
)
card.setBaseSoundResource(
apply : RSX.sfx_spell_icepillar.audio
)
if (identifier == Cards.Spell.Metalworking)
card = new SpellMetalworking(gameSession)
card.factionId = Factions.Faction3
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.Metalworking
card.name = "PI:NAME:<NAME>END_PImeld"
card.setDescription("Equip a friendly artifact that was destroyed this game.")
card.manaCost = 2
card.rarityId = Rarity.Rare
card.spellFilterType = SpellFilterType.None
card.setFXResource(["FX.Cards.Spell.Metalmeld"])
card.setBaseAnimResource(
idle: RSX.iconMetalmeldIdle.name
active: RSX.iconMetalmeldActive.name
)
card.setBaseSoundResource(
apply : RSX.sfx_spell_darktransformation.audio
)
if (identifier == Cards.Faction3.GoldenGuide)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction3
card.name = "PI:NAME:<NAME>END_PI"
card.raceId = Races.Dervish
card.setDescription("Flying, Rush\nDying Wish: A random friendly Dervish disappears, summoning a Khanuum-ka in its place.")
card.atk = 3
card.maxHP = 3
card.manaCost = 5
card.rarityId = Rarity.Legendary
card.setInherentModifiersContextObjects([
ModifierFirstBlood.createContextObject(),
ModifierFlying.createContextObject(),
ModifierDyingWishGoldenGuide.createContextObject()
])
card.setFXResource(["FX.Cards.Neutral.Fireblazer"])
card.setBaseSoundResource(
apply : RSX.sfx_unit_deploy_3.audio
walk : RSX.sfx_singe2.audio
attack : RSX.sfx_neutral_hailstonehowler_attack_swing.audio
receiveDamage : RSX.sfx_neutral_hailstonehowler_hit.audio
attackDamage : RSX.sfx_neutral_hailstonehowler_attack_impact.audio
death : RSX.sfx_neutral_hailstonehowler_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f3GoldenGuideBreathing.name
idle : RSX.f3GoldenGuideIdle.name
walk : RSX.f3GoldenGuideRun.name
attack : RSX.f3GoldenGuideAttack.name
attackReleaseDelay: 0.0
attackDelay: 0.6
damage : RSX.f3GoldenGuideHit.name
death : RSX.f3GoldenGuideDeath.name
)
if (identifier == Cards.Faction3.ScarabPulverizer)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction3
card.name = "PI:NAME:<NAME>END_PI"
card.setDescription("Blast\nWhenever this minion blasts, summon 1/1 Scarabyte with Flying and Rush in those spaces.")
card.atk = 5
card.maxHP = 7
card.manaCost = 6
card.rarityId = Rarity.Legendary
card.setInherentModifiersContextObjects([
ModifierBlastAttackStrong.createContextObject(),
ModifierMyAttackWatchScarabBlast.createContextObject()
])
card.addKeywordClassToInclude(ModifierFirstBlood)
card.addKeywordClassToInclude(ModifierFlying)
card.addKeywordClassToInclude(ModifierTokenCreator)
card.setFXResource(["FX.Cards.Neutral.Serpenti"])
card.setBoundingBoxWidth(105)
card.setBoundingBoxHeight(80)
card.setBaseSoundResource(
apply : RSX.sfx_unit_deploy.audio
walk : RSX.sfx_singe2.audio
attack : RSX.sfx_neutral_serpenti_attack_swing.audio
receiveDamage : RSX.sfx_neutral_serpenti_hit.audio
attackDamage : RSX.sfx_neutral_serpenti_attack_impact.audio
death : RSX.sfx_neutral_serpenti_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f3ScarabPulverizerBreathing.name
idle : RSX.f3ScarabPulverizerIdle.name
walk : RSX.f3ScarabPulverizerRun.name
attack : RSX.f3ScarabPulverizerAttack.name
attackReleaseDelay: 0.0
attackDelay: 0.3
damage : RSX.f3ScarabPulverizerHit.name
death : RSX.f3ScarabPulverizerDeath.name
)
if (identifier == Cards.Faction3.Scarab)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction3
card.name = "PI:NAME:<NAME>END_PI"
card.setDescription("Flying\nRush")
card.atk = 1
card.maxHP = 1
card.manaCost = 1
card.rarityId = Rarity.TokenUnit
card.setIsHiddenInCollection(true)
card.setInherentModifiersContextObjects([
ModifierFlying.createContextObject(),
ModifierFirstBlood.createContextObject()
])
card.addKeywordClassToInclude(ModifierToken)
card.setFXResource(["FX.Cards.Neutral.BlackLocust"])
card.setBaseSoundResource(
apply : RSX.sfx_summonlegendary.audio
walk : RSX.sfx_neutral_zurael_death.audio
attack : RSX.sfx_neutral_stormatha_attack_swing.audio
receiveDamage : RSX.sfx_neutral_stormatha_hit.audio
attackDamage : RSX.sfx_neutral_stormatha_attack_impact.audio
death : RSX.sfx_neutral_stormatha_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f3MiniScarabBreathing.name
idle : RSX.f3MiniScarabIdle.name
walk : RSX.f3MiniScarabRun.name
attack : RSX.f3MiniScarabAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.2
damage : RSX.f3MiniScarabHit.name
death : RSX.f3MiniScarabDeath.name
)
if (identifier == Cards.Faction3.StaffWielder)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction3
card.name = "PI:NAME:<NAME>END_PI"
card.setDescription("Whenever you equip an artifact, this minion gains +Attack equal to the artifact's cost.")
card.atk = 1
card.maxHP = 5
card.manaCost = 3
card.rarityId = Rarity.Rare
buffName = "Atomized"
card.setInherentModifiersContextObjects([ModifierEquipFriendlyArtifactWatchGainAttackEqualToCost.createContextObject(buffName)])
card.setFXResource(["FX.Cards.Neutral.ArakiHeadhunter"])
card.setBaseSoundResource(
apply : RSX.sfx_neutral_fog_attack_swing.audio
walk : RSX.sfx_neutral_earthwalker_death.audio
attack : RSX.sfx_neutral_arakiheadhunter_attack_swing.audio
receiveDamage : RSX.sfx_neutral_arakiheadhunter_hit.audio
attackDamage : RSX.sfx_neutral_arakiheadhunter_impact.audio
death : RSX.sfx_neutral_arakiheadhunter_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f3StaffWielderBreathing.name
idle : RSX.f3StaffWielderIdle.name
walk : RSX.f3StaffWielderRun.name
attack : RSX.f3StaffWielderAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.2
damage : RSX.f3StaffWielderHit.name
death : RSX.f3StaffWielderDeath.name
)
return card
module.exports = CardFactory_CoreshatterSet_Faction3
|
[
{
"context": "ee')\n\nparameters = [\n { ID: 5, Rate: 0.0, Name: \"正一郎\" }\n { ID: 13, Rate: 0.1, Name: \"清次郎\" }\n { ID: 2",
"end": 84,
"score": 0.9994512796401978,
"start": 81,
"tag": "NAME",
"value": "正一郎"
},
{
"context": " 0.0, Name: \"正一郎\" }\n { ID: 13, Rate: 0.1, Name: \"清... | test/coffee/select.coffee | Lxsbw/linqjs | 0 | Linq = require('../../src/coffee')
parameters = [
{ ID: 5, Rate: 0.0, Name: "正一郎" }
{ ID: 13, Rate: 0.1, Name: "清次郎" }
{ ID: 25, Rate: 0.0, Name: "誠三郎" }
{ ID: 42, Rate: 0.3, Name: "征史郎" }
]
results = new Linq(parameters).Select( (value) -> { ID: value.ID, Name: value.Name } ).ToArray()
console.log 'results:', results
| 2009 | Linq = require('../../src/coffee')
parameters = [
{ ID: 5, Rate: 0.0, Name: "<NAME>" }
{ ID: 13, Rate: 0.1, Name: "<NAME>" }
{ ID: 25, Rate: 0.0, Name: "<NAME>" }
{ ID: 42, Rate: 0.3, Name: "<NAME>" }
]
results = new Linq(parameters).Select( (value) -> { ID: value.ID, Name: value.Name } ).ToArray()
console.log 'results:', results
| true | Linq = require('../../src/coffee')
parameters = [
{ ID: 5, Rate: 0.0, Name: "PI:NAME:<NAME>END_PI" }
{ ID: 13, Rate: 0.1, Name: "PI:NAME:<NAME>END_PI" }
{ ID: 25, Rate: 0.0, Name: "PI:NAME:<NAME>END_PI" }
{ ID: 42, Rate: 0.3, Name: "PI:NAME:<NAME>END_PI" }
]
results = new Linq(parameters).Select( (value) -> { ID: value.ID, Name: value.Name } ).ToArray()
console.log 'results:', results
|
[
{
"context": ") ->\n data =\n token: token\n password: password\n\n $http.post(UserF.RESET_API, data)\n .catch",
"end": 1648,
"score": 0.9977231621742249,
"start": 1640,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "(username, password) ->\n data =\n ... | v1/coffee/utils/UserF.coffee | lizechoo/Bromeliad-Database | 0 | app.factory 'UserF', (LocalStorageF, ConstantsF, ngDialog, $window, $http, $q, $state) ->
UserF = {}
UserF.GET_USER_API = ConstantsF.getPath 'users', 'current'
UserF.LOGIN_USER_API = ConstantsF.getPath 'users', 'login'
UserF.RESET_API = ConstantsF.getPath 'users', 'reset'
UserF.RECOVER_API = ConstantsF.getPath 'users', 'recover'
UserF.getUser = ->
return $q.when UserF.user if UserF.user
return UserF.signIn()
UserF.header = ->
return if !UserF.token
return 'Authorization': 'bearer ' + UserF.token
UserF.signIn = ->
if !UserF.token
UserF.token = LocalStorageF.token.get()
if !UserF.token
UserF.showLogin()
return $q.reject()
return UserF.loadUser UserF.token
UserF.loadUser = (token) ->
options = headers: 'Authorization': "bearer #{token}"
return $http.get UserF.GET_USER_API, options
.then (res) ->
user = res.data.results.user
UserF.setUser user
return user
,(error) ->
UserF.token = null
LocalStorageF.token.unset()
$window.location.reload()
UserF.setUser = (user) ->
UserF.user = user
UserF.showLogin = ->
ngDialog.open
template: 'loginDialog.html'
controller: 'LoginDialogC'
showClose: false
closeByEscape: false
closeByDocument: false
UserF.setAvatar = ->
ngDialog.openConfirm
template: 'users/avatar.html'
controller: 'UserAvatarC'
controllerAs: 'user'
UserF.sendRecoveryEmail = (email) ->
$http.post(UserF.RECOVER_API, email: email)
UserF.resetPassword = (token, password) ->
data =
token: token
password: password
$http.post(UserF.RESET_API, data)
.catch (res) ->
throw new Error res?.data.error
UserF.login = (username, password) ->
data =
username: username
password: password
return $http.post(UserF.LOGIN_USER_API, data)
.then (res) ->
unless res?.data?.results?.token
console.error "Cannot find token from response: ", JSON.stringify(res)
UserF.token = token = res.data.results.token
LocalStorageF.token.set(token)
return true
UserF.logout = ->
delete UserF.user
delete UserF.token
LocalStorageF.token.unset()
$state.go('dashboard')
.then ->
$window.location.reload()
return UserF
| 32978 | app.factory 'UserF', (LocalStorageF, ConstantsF, ngDialog, $window, $http, $q, $state) ->
UserF = {}
UserF.GET_USER_API = ConstantsF.getPath 'users', 'current'
UserF.LOGIN_USER_API = ConstantsF.getPath 'users', 'login'
UserF.RESET_API = ConstantsF.getPath 'users', 'reset'
UserF.RECOVER_API = ConstantsF.getPath 'users', 'recover'
UserF.getUser = ->
return $q.when UserF.user if UserF.user
return UserF.signIn()
UserF.header = ->
return if !UserF.token
return 'Authorization': 'bearer ' + UserF.token
UserF.signIn = ->
if !UserF.token
UserF.token = LocalStorageF.token.get()
if !UserF.token
UserF.showLogin()
return $q.reject()
return UserF.loadUser UserF.token
UserF.loadUser = (token) ->
options = headers: 'Authorization': "bearer #{token}"
return $http.get UserF.GET_USER_API, options
.then (res) ->
user = res.data.results.user
UserF.setUser user
return user
,(error) ->
UserF.token = null
LocalStorageF.token.unset()
$window.location.reload()
UserF.setUser = (user) ->
UserF.user = user
UserF.showLogin = ->
ngDialog.open
template: 'loginDialog.html'
controller: 'LoginDialogC'
showClose: false
closeByEscape: false
closeByDocument: false
UserF.setAvatar = ->
ngDialog.openConfirm
template: 'users/avatar.html'
controller: 'UserAvatarC'
controllerAs: 'user'
UserF.sendRecoveryEmail = (email) ->
$http.post(UserF.RECOVER_API, email: email)
UserF.resetPassword = (token, password) ->
data =
token: token
password: <PASSWORD>
$http.post(UserF.RESET_API, data)
.catch (res) ->
throw new Error res?.data.error
UserF.login = (username, password) ->
data =
username: username
password: <PASSWORD>
return $http.post(UserF.LOGIN_USER_API, data)
.then (res) ->
unless res?.data?.results?.token
console.error "Cannot find token from response: ", JSON.stringify(res)
UserF.token = token = res.data.results.token
LocalStorageF.token.set(token)
return true
UserF.logout = ->
delete UserF.user
delete UserF.token
LocalStorageF.token.unset()
$state.go('dashboard')
.then ->
$window.location.reload()
return UserF
| true | app.factory 'UserF', (LocalStorageF, ConstantsF, ngDialog, $window, $http, $q, $state) ->
UserF = {}
UserF.GET_USER_API = ConstantsF.getPath 'users', 'current'
UserF.LOGIN_USER_API = ConstantsF.getPath 'users', 'login'
UserF.RESET_API = ConstantsF.getPath 'users', 'reset'
UserF.RECOVER_API = ConstantsF.getPath 'users', 'recover'
UserF.getUser = ->
return $q.when UserF.user if UserF.user
return UserF.signIn()
UserF.header = ->
return if !UserF.token
return 'Authorization': 'bearer ' + UserF.token
UserF.signIn = ->
if !UserF.token
UserF.token = LocalStorageF.token.get()
if !UserF.token
UserF.showLogin()
return $q.reject()
return UserF.loadUser UserF.token
UserF.loadUser = (token) ->
options = headers: 'Authorization': "bearer #{token}"
return $http.get UserF.GET_USER_API, options
.then (res) ->
user = res.data.results.user
UserF.setUser user
return user
,(error) ->
UserF.token = null
LocalStorageF.token.unset()
$window.location.reload()
UserF.setUser = (user) ->
UserF.user = user
UserF.showLogin = ->
ngDialog.open
template: 'loginDialog.html'
controller: 'LoginDialogC'
showClose: false
closeByEscape: false
closeByDocument: false
UserF.setAvatar = ->
ngDialog.openConfirm
template: 'users/avatar.html'
controller: 'UserAvatarC'
controllerAs: 'user'
UserF.sendRecoveryEmail = (email) ->
$http.post(UserF.RECOVER_API, email: email)
UserF.resetPassword = (token, password) ->
data =
token: token
password: PI:PASSWORD:<PASSWORD>END_PI
$http.post(UserF.RESET_API, data)
.catch (res) ->
throw new Error res?.data.error
UserF.login = (username, password) ->
data =
username: username
password: PI:PASSWORD:<PASSWORD>END_PI
return $http.post(UserF.LOGIN_USER_API, data)
.then (res) ->
unless res?.data?.results?.token
console.error "Cannot find token from response: ", JSON.stringify(res)
UserF.token = token = res.data.results.token
LocalStorageF.token.set(token)
return true
UserF.logout = ->
delete UserF.user
delete UserF.token
LocalStorageF.token.unset()
$state.go('dashboard')
.then ->
$window.location.reload()
return UserF
|
[
{
"context": "я заполнения.\"\n password:\n required: \"Пароль обязателен для заполнения.\"\n\n $(\"#form-signin_ep",
"end": 7313,
"score": 0.9400880932807922,
"start": 7307,
"tag": "PASSWORD",
"value": "Пароль"
},
{
"context": "ния.\"\n password:\n required:... | static/coffee/stroytorgi.validation.coffee | LordWalmar/betting | 0 | $ ->
# SubmitHandler
submitButton_styled = ($form, disable) ->
$submit_btn = $form.find('button[type=submit], input[type=submit]')
color = if $submit_btn.attr('data-color') then $submit_btn.attr('data-color') else (if $submit_btn.hasClass('btn-submit__red') then 'red' else 'grey')
$submit_btn.attr('data-color', color)
$submit_btn.toggleClass "btn-submit__#{color}", !disable
$submit_btn.toggleClass "btn-loading", disable
$submit_btn.toggleClass "btn-loading__#{color}", disable
$submit_btn.prop('disabled', disable)
#Methods#
$.validator.addMethod "is_phone", ((value, element, param) ->
phone = value.match(/^\+?(\d|-|\(|\)|\s|\.)+$/g)
this.optional(element) || phone
), "Пожалуйста, вводите только цифры и символы (, ), -, +."
$.validator.addMethod "is_email", ((value, element, param) ->
email = value.match(/^([a-z0-9_-]+\.)*[a-z0-9_-]+@[a-z0-9_-]+(\.[a-z0-9_-]+)*\.[a-z]{2,6}$/)
this.optional(element) || email
), "Введите корректный Email."
$.validator.addMethod "is_name", ((value, element, param) ->
name = value.match(/^[а-яёa-z ]+$/gi)
this.optional(element) || name
), "Ф.И.О. не должно содержать цифры."
$.validator.addMethod "is_author", ((value, element, param) ->
author = value.match(/^[а-яёa-z ]+$/gi)
this.optional(element) || author
), "Ф.И.О. не должно содержать цифры."
###
$.validator.addMethod "is_validateLength", ((value, element, param) ->
word_length = value.length
$this = $(element)
definitionMaxLength = ->
$radioBtn = $('.wbt-input-radio__active').find('input')
$numberFace = $radioBtn.val()
if +$numberFace == 0
$this.attr('maxlength', '10')
return 10
else
$this.attr('maxlength', '12')
return 12
this.optional(element) || word_length <= definitionMaxLength()
), "Максимальное количество символов " + $('.input-text[name="inn"]').attr('maxlength') + "."
###
$('input[name="individ"]').on 'change', ->
$radioBtn = $('.wbt-input-radio__active').find('input')
$numberFace = $radioBtn.val()
$inputCurrent = $('input[name="inn"]')
if +$numberFace == 0
countSigns = 10
else
countSigns = 12
$inputCurrent.rules( "remove", "maxlength" )
$inputCurrent.rules( "add", {
maxlength: countSigns,
messages: {
maxlength: "Максимальное количество символов " + countSigns + "."
}
})
$.validator.addMethod "is_number", ((value, element, param) ->
phone = value.match(/^(\d)+$/g)
this.optional(element) || phone
), "Пожалуйста, вводите только цифры."
$.validator.setDefaults({errorClass: 'stroytorgi-error'})
formPointNone = ($elem, radioChoise)->
$elem.rules("remove", "required")
$elem.rules("add", { required: radioChoise})
if radioChoise
$elem.closest('label').css('width','100%').slideDown('fast')
else
$elem.closest('label').css('width','100%').slideUp('fast')
$wbtRadioBtn = $('.registration-info_choise').find('input[type="radio"]')
$currentForm = $wbtRadioBtn.closest('form')
$wbtRadioBtn.on "click", ->
$kpp = $('input[name="kpp"]')
$org_type = $('select[name="org_type"]')
radioChoise = $(this).val() != '1'
formPointNone($kpp, radioChoise)
formPointNone($org_type, radioChoise)
handlerInvalid = (form, validator) ->
$(this).addClass('form_invalid')
btn = $(this).find ".btn-submit"
btn.removeClass "btn-loading"
btn.removeAttr 'disabled'
handlerValid = (form, validator) ->
$(form).removeClass('form_invalid')
$(form).find('.other_errors').hide()
form.submit()
handlerValidSubscribe = (form, validator) ->
$form = $(form)
$.post '/blog/subscribe.json', $form.serialize(), (data)->
if data.success
$form.removeClass('form_invalid')
$form.find('.stroytorgi-error').hide()
$form.find('.blog-updates_confirm').show()
$form[0].reset()
else
error = data.message['email']
error_msg = error
if not (typeof error == "string" || error instanceof String)
$.each error, (error_key)->
error_msg = this
$form.find('.stroytorgi-error').text(error_msg).show()
, 'json'
.fail ->
$form.find('.stroytorgi-error').text('Возникла ошибка. Попробуйте позже.').show()
handlerValidSendAjax = (form, validator) ->
$form = $(form)
$form.attr('data-process', '1')
submitButton_styled($form, true)
show_custom_errors = (errors)->
$other_errors = $form.find('.other_errors')
$other_errors.empty()
$.each errors, (name)->
$label = $form.find("[name=#{name}]").closest('label').find('.form_point')
label = (if $label.length then '<span>'+$label.text()+':</span> ' else '')
error = this
if not (typeof this == "string" || this instanceof String)
$.each this, (error_key)->
error = this
$other_errors.append("<p class='stroytorgi-error'>#{label}#{error}</p>")
$other_errors.show()
$form.removeClass('form_invalid')
$form.find('.other_errors').hide()
if (['form_request', 'form_question'].indexOf($form.attr('id'))>-1)
category_slug = $form.find('select[name=category_id]').find('option:selected').attr('data-slug')
$form.attr('data-url', "http://master-promo.test.stroytorgi.ru/faq/#{category_slug}/question.json")
url = if $form.attr('data-url') then $form.attr('data-url') else $form.attr('action')
ajax_params =
type:'POST'
async: false
dataType: 'json'
url: url
data: $form.serialize()
success: (response)->
if response.success
redirect_url = $form.attr('data-redirect')
if redirect_url
location.href = '/'
else
$form[0].reset()
$thnx = $form.closest('.form_wrapper').find('.thnx')
if $thnx.length
$form.closest('.form_container').hide()
$thnx.show()
else
alert('Спасибо. ' + (response.message || ''))
else
show_custom_errors(response.errors || response.message)
error: (xhr, status_text, err)->
show_custom_errors
nonfielderror: (if xhr.status==413 then 'Прикрепленный файл слишком большой.' else 'Возникла ошибка. Попробуйте позже')
$file = $form.find('[type=file]');
if $file.length and $file.data().files
file_data = $file.data().files[0]
data_f = new FormData()
$.each $form.find('input, select'), ->
data_f.append(this.name, this.value)
data_f.append('file', file_data)
data_f.append('text', $form.find('[name=text]').val())
ajax_params["data"] = data_f
ajax_params["mimeType"] = "multipart/form-data"
ajax_params["contentType"] = false
ajax_params["cache"] = false
ajax_params["processData"] = false
$.ajax ajax_params
submitButton_styled($form, false)
false
# Rules
$("#form-signin_login").validate
invalidHandler: handlerInvalid
submitHandler: handlerValid
rules:
login:
required: true
password:
required: true
messages:
login:
required: "Логин обязателен для заполнения."
password:
required: "Пароль обязателен для заполнения."
$("#form-signin_ep").validate
invalidHandler: handlerInvalid
submitHandler: handlerValid
rules:
pin:
required: true
messages:
pin:
required: "PIN обязателен для заполнения."
$("#form-signin_nopassword").validate
invalidHandler: handlerInvalid
submitHandler: handlerValid
rules:
nopassword:
required: true
messages:
nopassword:
required: "Логин обязателен для заполнения."
$("#form_presentation").validate
invalidHandler: handlerInvalid
submitHandler: handlerValidSendAjax
rules:
name:
required: true
is_name: true
company_name:
required: true
phone:
required: true
is_phone: true
email:
required: true
is_email: true
messages:
name:
required: "Ф.И.О. обязательно для заполнения."
company_name:
required: "Имя компании обязательно для заполнения."
phone:
required: "Телефон обязателен для заполнения."
email:
required: "Email обязателен для заполнения."
email: "Введите корректный Email."
$("#form_seminar").validate
invalidHandler: handlerInvalid
submitHandler: handlerValidSendAjax
rules:
name:
required: true
is_name: true
company_name:
required: true
phone:
required: true
is_phone: true
email:
required: true
is_email: true
messages:
name:
required: "Ф.И.О. обязательно для заполнения."
company_name:
required: "Имя компании обязательно для заполнения."
phone:
required: "Телефон обязателен для заполнения."
email:
required: "Email обязателен для заполнения."
email: "Введите корректный Email."
$("#form_question").validate
invalidHandler: handlerInvalid
submitHandler: handlerValidSendAjax
rules:
author:
required: true
is_author: true
email:
required: true
is_email: true
text:
required: true
messages:
author:
required: "Ф.И.О. обязательно для заполнения."
email:
required: "Email обязателен для заполнения."
email: "Введите корректный Email."
text:
required: "Задайте, пожалуйста, вопрос."
$("#form_request").validate
invalidHandler: handlerInvalid
submitHandler: handlerValidSendAjax
rules:
author:
required: true
is_author: true
email:
required: true
is_email: true
text:
required: true
type:
required: true
title:
required: true
category_id:
required: true
messages:
author:
required: "Ф.И.О. обязательно для заполнения."
email:
required: "Email обязателен для заполнения."
email: "Введите корректный Email."
text:
required: "Задайте, пожалуйста, вопрос."
title:
required: "Задайте тему."
category_id:
required: "Выберите категорию обращения."
type:
required: "Тип вопроса обязателен к заполнению."
$("#form_registration").validate
invalidHandler: handlerInvalid
submitHandler: handlerValidSendAjax
rules:
individ:
required: true
inn:
required: true
maxlength: 12
is_number: true
kpp:
required: true
maxlength: 9
is_number: true
org_type:
required: true
org_name:
required: true
position:
required: true
email:
required: true
is_email: true
phone:
required: true
is_phone: true
messages:
individ:
required: "Это поле обязательно для заполнения."
inn:
required: "Пожалуйста, укажите ИНН"
maxlength: "Максимальное количество символов 12."
kpp:
required: "Пожалуйста, укажите КПП"
maxlength: "Максимальное количество символов 9."
org_type:
required: "Пожалуйста, укажите правовую форму"
org_name:
required: "Имя компании обязательно для заполнения."
position:
required: "Пожалуйста, укажите должность"
email:
required: "Email обязателен для заполнения."
email: "Введите корректный Email."
phone:
required: "Телефон обязателен для заполнения."
$(".blog-updates").validate
invalidHandler: handlerInvalid
submitHandler: handlerValidSubscribe
rules:
email:
required: true
is_email: true
messages:
email:
required: "Введите Email."
| 42599 | $ ->
# SubmitHandler
submitButton_styled = ($form, disable) ->
$submit_btn = $form.find('button[type=submit], input[type=submit]')
color = if $submit_btn.attr('data-color') then $submit_btn.attr('data-color') else (if $submit_btn.hasClass('btn-submit__red') then 'red' else 'grey')
$submit_btn.attr('data-color', color)
$submit_btn.toggleClass "btn-submit__#{color}", !disable
$submit_btn.toggleClass "btn-loading", disable
$submit_btn.toggleClass "btn-loading__#{color}", disable
$submit_btn.prop('disabled', disable)
#Methods#
$.validator.addMethod "is_phone", ((value, element, param) ->
phone = value.match(/^\+?(\d|-|\(|\)|\s|\.)+$/g)
this.optional(element) || phone
), "Пожалуйста, вводите только цифры и символы (, ), -, +."
$.validator.addMethod "is_email", ((value, element, param) ->
email = value.match(/^([a-z0-9_-]+\.)*[a-z0-9_-]+@[a-z0-9_-]+(\.[a-z0-9_-]+)*\.[a-z]{2,6}$/)
this.optional(element) || email
), "Введите корректный Email."
$.validator.addMethod "is_name", ((value, element, param) ->
name = value.match(/^[а-яёa-z ]+$/gi)
this.optional(element) || name
), "Ф.И.О. не должно содержать цифры."
$.validator.addMethod "is_author", ((value, element, param) ->
author = value.match(/^[а-яёa-z ]+$/gi)
this.optional(element) || author
), "Ф.И.О. не должно содержать цифры."
###
$.validator.addMethod "is_validateLength", ((value, element, param) ->
word_length = value.length
$this = $(element)
definitionMaxLength = ->
$radioBtn = $('.wbt-input-radio__active').find('input')
$numberFace = $radioBtn.val()
if +$numberFace == 0
$this.attr('maxlength', '10')
return 10
else
$this.attr('maxlength', '12')
return 12
this.optional(element) || word_length <= definitionMaxLength()
), "Максимальное количество символов " + $('.input-text[name="inn"]').attr('maxlength') + "."
###
$('input[name="individ"]').on 'change', ->
$radioBtn = $('.wbt-input-radio__active').find('input')
$numberFace = $radioBtn.val()
$inputCurrent = $('input[name="inn"]')
if +$numberFace == 0
countSigns = 10
else
countSigns = 12
$inputCurrent.rules( "remove", "maxlength" )
$inputCurrent.rules( "add", {
maxlength: countSigns,
messages: {
maxlength: "Максимальное количество символов " + countSigns + "."
}
})
$.validator.addMethod "is_number", ((value, element, param) ->
phone = value.match(/^(\d)+$/g)
this.optional(element) || phone
), "Пожалуйста, вводите только цифры."
$.validator.setDefaults({errorClass: 'stroytorgi-error'})
formPointNone = ($elem, radioChoise)->
$elem.rules("remove", "required")
$elem.rules("add", { required: radioChoise})
if radioChoise
$elem.closest('label').css('width','100%').slideDown('fast')
else
$elem.closest('label').css('width','100%').slideUp('fast')
$wbtRadioBtn = $('.registration-info_choise').find('input[type="radio"]')
$currentForm = $wbtRadioBtn.closest('form')
$wbtRadioBtn.on "click", ->
$kpp = $('input[name="kpp"]')
$org_type = $('select[name="org_type"]')
radioChoise = $(this).val() != '1'
formPointNone($kpp, radioChoise)
formPointNone($org_type, radioChoise)
handlerInvalid = (form, validator) ->
$(this).addClass('form_invalid')
btn = $(this).find ".btn-submit"
btn.removeClass "btn-loading"
btn.removeAttr 'disabled'
handlerValid = (form, validator) ->
$(form).removeClass('form_invalid')
$(form).find('.other_errors').hide()
form.submit()
handlerValidSubscribe = (form, validator) ->
$form = $(form)
$.post '/blog/subscribe.json', $form.serialize(), (data)->
if data.success
$form.removeClass('form_invalid')
$form.find('.stroytorgi-error').hide()
$form.find('.blog-updates_confirm').show()
$form[0].reset()
else
error = data.message['email']
error_msg = error
if not (typeof error == "string" || error instanceof String)
$.each error, (error_key)->
error_msg = this
$form.find('.stroytorgi-error').text(error_msg).show()
, 'json'
.fail ->
$form.find('.stroytorgi-error').text('Возникла ошибка. Попробуйте позже.').show()
handlerValidSendAjax = (form, validator) ->
$form = $(form)
$form.attr('data-process', '1')
submitButton_styled($form, true)
show_custom_errors = (errors)->
$other_errors = $form.find('.other_errors')
$other_errors.empty()
$.each errors, (name)->
$label = $form.find("[name=#{name}]").closest('label').find('.form_point')
label = (if $label.length then '<span>'+$label.text()+':</span> ' else '')
error = this
if not (typeof this == "string" || this instanceof String)
$.each this, (error_key)->
error = this
$other_errors.append("<p class='stroytorgi-error'>#{label}#{error}</p>")
$other_errors.show()
$form.removeClass('form_invalid')
$form.find('.other_errors').hide()
if (['form_request', 'form_question'].indexOf($form.attr('id'))>-1)
category_slug = $form.find('select[name=category_id]').find('option:selected').attr('data-slug')
$form.attr('data-url', "http://master-promo.test.stroytorgi.ru/faq/#{category_slug}/question.json")
url = if $form.attr('data-url') then $form.attr('data-url') else $form.attr('action')
ajax_params =
type:'POST'
async: false
dataType: 'json'
url: url
data: $form.serialize()
success: (response)->
if response.success
redirect_url = $form.attr('data-redirect')
if redirect_url
location.href = '/'
else
$form[0].reset()
$thnx = $form.closest('.form_wrapper').find('.thnx')
if $thnx.length
$form.closest('.form_container').hide()
$thnx.show()
else
alert('Спасибо. ' + (response.message || ''))
else
show_custom_errors(response.errors || response.message)
error: (xhr, status_text, err)->
show_custom_errors
nonfielderror: (if xhr.status==413 then 'Прикрепленный файл слишком большой.' else 'Возникла ошибка. Попробуйте позже')
$file = $form.find('[type=file]');
if $file.length and $file.data().files
file_data = $file.data().files[0]
data_f = new FormData()
$.each $form.find('input, select'), ->
data_f.append(this.name, this.value)
data_f.append('file', file_data)
data_f.append('text', $form.find('[name=text]').val())
ajax_params["data"] = data_f
ajax_params["mimeType"] = "multipart/form-data"
ajax_params["contentType"] = false
ajax_params["cache"] = false
ajax_params["processData"] = false
$.ajax ajax_params
submitButton_styled($form, false)
false
# Rules
$("#form-signin_login").validate
invalidHandler: handlerInvalid
submitHandler: handlerValid
rules:
login:
required: true
password:
required: true
messages:
login:
required: "Логин обязателен для заполнения."
password:
required: "<PASSWORD> об<PASSWORD> для заполнения."
$("#form-signin_ep").validate
invalidHandler: handlerInvalid
submitHandler: handlerValid
rules:
pin:
required: true
messages:
pin:
required: "PIN обязателен для заполнения."
$("#form-signin_nopassword").validate
invalidHandler: handlerInvalid
submitHandler: handlerValid
rules:
nopassword:
required: true
messages:
nopassword:
required: "Логин обязателен для заполнения."
$("#form_presentation").validate
invalidHandler: handlerInvalid
submitHandler: handlerValidSendAjax
rules:
name:
required: true
is_name: true
company_name:
required: true
phone:
required: true
is_phone: true
email:
required: true
is_email: true
messages:
name:
required: "Ф.И.О. обязательно для заполнения."
company_name:
required: "Имя компании обязательно для заполнения."
phone:
required: "Телефон обязателен для заполнения."
email:
required: "Email обязателен для заполнения."
email: "Введите корректный Email."
$("#form_seminar").validate
invalidHandler: handlerInvalid
submitHandler: handlerValidSendAjax
rules:
name:
required: true
is_name: true
company_name:
required: true
phone:
required: true
is_phone: true
email:
required: true
is_email: true
messages:
name:
required: "Ф.И.О. обязательно для заполнения."
company_name:
required: "Имя компании обязательно для заполнения."
phone:
required: "Телефон обязателен для заполнения."
email:
required: "Email обязателен для заполнения."
email: "Введите корректный Email."
$("#form_question").validate
invalidHandler: handlerInvalid
submitHandler: handlerValidSendAjax
rules:
author:
required: true
is_author: true
email:
required: true
is_email: true
text:
required: true
messages:
author:
required: "Ф.И.О. обязательно для заполнения."
email:
required: "Email обязателен для заполнения."
email: "Введите корректный Email."
text:
required: "Задайте, пожалуйста, вопрос."
$("#form_request").validate
invalidHandler: handlerInvalid
submitHandler: handlerValidSendAjax
rules:
author:
required: true
is_author: true
email:
required: true
is_email: true
text:
required: true
type:
required: true
title:
required: true
category_id:
required: true
messages:
author:
required: "Ф.И.О. обязательно для заполнения."
email:
required: "Email обязателен для заполнения."
email: "Введите корректный Email."
text:
required: "Задайте, пожалуйста, вопрос."
title:
required: "Задайте тему."
category_id:
required: "Выберите категорию обращения."
type:
required: "Тип вопроса обязателен к заполнению."
$("#form_registration").validate
invalidHandler: handlerInvalid
submitHandler: handlerValidSendAjax
rules:
individ:
required: true
inn:
required: true
maxlength: 12
is_number: true
kpp:
required: true
maxlength: 9
is_number: true
org_type:
required: true
org_name:
required: true
position:
required: true
email:
required: true
is_email: true
phone:
required: true
is_phone: true
messages:
individ:
required: "Это поле обязательно для заполнения."
inn:
required: "Пожалуйста, укажите ИНН"
maxlength: "Максимальное количество символов 12."
kpp:
required: "Пожалуйста, укажите КПП"
maxlength: "Максимальное количество символов 9."
org_type:
required: "Пожалуйста, укажите правовую форму"
org_name:
required: "Имя компании обязательно для заполнения."
position:
required: "Пожалуйста, укажите должность"
email:
required: "Email обязателен для заполнения."
email: "Введите корректный Email."
phone:
required: "Телефон обязателен для заполнения."
$(".blog-updates").validate
invalidHandler: handlerInvalid
submitHandler: handlerValidSubscribe
rules:
email:
required: true
is_email: true
messages:
email:
required: "Введите Email."
| true | $ ->
# SubmitHandler
submitButton_styled = ($form, disable) ->
$submit_btn = $form.find('button[type=submit], input[type=submit]')
color = if $submit_btn.attr('data-color') then $submit_btn.attr('data-color') else (if $submit_btn.hasClass('btn-submit__red') then 'red' else 'grey')
$submit_btn.attr('data-color', color)
$submit_btn.toggleClass "btn-submit__#{color}", !disable
$submit_btn.toggleClass "btn-loading", disable
$submit_btn.toggleClass "btn-loading__#{color}", disable
$submit_btn.prop('disabled', disable)
#Methods#
$.validator.addMethod "is_phone", ((value, element, param) ->
phone = value.match(/^\+?(\d|-|\(|\)|\s|\.)+$/g)
this.optional(element) || phone
), "Пожалуйста, вводите только цифры и символы (, ), -, +."
$.validator.addMethod "is_email", ((value, element, param) ->
email = value.match(/^([a-z0-9_-]+\.)*[a-z0-9_-]+@[a-z0-9_-]+(\.[a-z0-9_-]+)*\.[a-z]{2,6}$/)
this.optional(element) || email
), "Введите корректный Email."
$.validator.addMethod "is_name", ((value, element, param) ->
name = value.match(/^[а-яёa-z ]+$/gi)
this.optional(element) || name
), "Ф.И.О. не должно содержать цифры."
$.validator.addMethod "is_author", ((value, element, param) ->
author = value.match(/^[а-яёa-z ]+$/gi)
this.optional(element) || author
), "Ф.И.О. не должно содержать цифры."
###
$.validator.addMethod "is_validateLength", ((value, element, param) ->
word_length = value.length
$this = $(element)
definitionMaxLength = ->
$radioBtn = $('.wbt-input-radio__active').find('input')
$numberFace = $radioBtn.val()
if +$numberFace == 0
$this.attr('maxlength', '10')
return 10
else
$this.attr('maxlength', '12')
return 12
this.optional(element) || word_length <= definitionMaxLength()
), "Максимальное количество символов " + $('.input-text[name="inn"]').attr('maxlength') + "."
###
$('input[name="individ"]').on 'change', ->
$radioBtn = $('.wbt-input-radio__active').find('input')
$numberFace = $radioBtn.val()
$inputCurrent = $('input[name="inn"]')
if +$numberFace == 0
countSigns = 10
else
countSigns = 12
$inputCurrent.rules( "remove", "maxlength" )
$inputCurrent.rules( "add", {
maxlength: countSigns,
messages: {
maxlength: "Максимальное количество символов " + countSigns + "."
}
})
$.validator.addMethod "is_number", ((value, element, param) ->
phone = value.match(/^(\d)+$/g)
this.optional(element) || phone
), "Пожалуйста, вводите только цифры."
$.validator.setDefaults({errorClass: 'stroytorgi-error'})
formPointNone = ($elem, radioChoise)->
$elem.rules("remove", "required")
$elem.rules("add", { required: radioChoise})
if radioChoise
$elem.closest('label').css('width','100%').slideDown('fast')
else
$elem.closest('label').css('width','100%').slideUp('fast')
$wbtRadioBtn = $('.registration-info_choise').find('input[type="radio"]')
$currentForm = $wbtRadioBtn.closest('form')
$wbtRadioBtn.on "click", ->
$kpp = $('input[name="kpp"]')
$org_type = $('select[name="org_type"]')
radioChoise = $(this).val() != '1'
formPointNone($kpp, radioChoise)
formPointNone($org_type, radioChoise)
handlerInvalid = (form, validator) ->
$(this).addClass('form_invalid')
btn = $(this).find ".btn-submit"
btn.removeClass "btn-loading"
btn.removeAttr 'disabled'
handlerValid = (form, validator) ->
$(form).removeClass('form_invalid')
$(form).find('.other_errors').hide()
form.submit()
handlerValidSubscribe = (form, validator) ->
$form = $(form)
$.post '/blog/subscribe.json', $form.serialize(), (data)->
if data.success
$form.removeClass('form_invalid')
$form.find('.stroytorgi-error').hide()
$form.find('.blog-updates_confirm').show()
$form[0].reset()
else
error = data.message['email']
error_msg = error
if not (typeof error == "string" || error instanceof String)
$.each error, (error_key)->
error_msg = this
$form.find('.stroytorgi-error').text(error_msg).show()
, 'json'
.fail ->
$form.find('.stroytorgi-error').text('Возникла ошибка. Попробуйте позже.').show()
handlerValidSendAjax = (form, validator) ->
$form = $(form)
$form.attr('data-process', '1')
submitButton_styled($form, true)
show_custom_errors = (errors)->
$other_errors = $form.find('.other_errors')
$other_errors.empty()
$.each errors, (name)->
$label = $form.find("[name=#{name}]").closest('label').find('.form_point')
label = (if $label.length then '<span>'+$label.text()+':</span> ' else '')
error = this
if not (typeof this == "string" || this instanceof String)
$.each this, (error_key)->
error = this
$other_errors.append("<p class='stroytorgi-error'>#{label}#{error}</p>")
$other_errors.show()
$form.removeClass('form_invalid')
$form.find('.other_errors').hide()
if (['form_request', 'form_question'].indexOf($form.attr('id'))>-1)
category_slug = $form.find('select[name=category_id]').find('option:selected').attr('data-slug')
$form.attr('data-url', "http://master-promo.test.stroytorgi.ru/faq/#{category_slug}/question.json")
url = if $form.attr('data-url') then $form.attr('data-url') else $form.attr('action')
ajax_params =
type:'POST'
async: false
dataType: 'json'
url: url
data: $form.serialize()
success: (response)->
if response.success
redirect_url = $form.attr('data-redirect')
if redirect_url
location.href = '/'
else
$form[0].reset()
$thnx = $form.closest('.form_wrapper').find('.thnx')
if $thnx.length
$form.closest('.form_container').hide()
$thnx.show()
else
alert('Спасибо. ' + (response.message || ''))
else
show_custom_errors(response.errors || response.message)
error: (xhr, status_text, err)->
show_custom_errors
nonfielderror: (if xhr.status==413 then 'Прикрепленный файл слишком большой.' else 'Возникла ошибка. Попробуйте позже')
$file = $form.find('[type=file]');
if $file.length and $file.data().files
file_data = $file.data().files[0]
data_f = new FormData()
$.each $form.find('input, select'), ->
data_f.append(this.name, this.value)
data_f.append('file', file_data)
data_f.append('text', $form.find('[name=text]').val())
ajax_params["data"] = data_f
ajax_params["mimeType"] = "multipart/form-data"
ajax_params["contentType"] = false
ajax_params["cache"] = false
ajax_params["processData"] = false
$.ajax ajax_params
submitButton_styled($form, false)
false
# Rules
$("#form-signin_login").validate
invalidHandler: handlerInvalid
submitHandler: handlerValid
rules:
login:
required: true
password:
required: true
messages:
login:
required: "Логин обязателен для заполнения."
password:
required: "PI:PASSWORD:<PASSWORD>END_PI обPI:PASSWORD:<PASSWORD>END_PI для заполнения."
$("#form-signin_ep").validate
invalidHandler: handlerInvalid
submitHandler: handlerValid
rules:
pin:
required: true
messages:
pin:
required: "PIN обязателен для заполнения."
$("#form-signin_nopassword").validate
invalidHandler: handlerInvalid
submitHandler: handlerValid
rules:
nopassword:
required: true
messages:
nopassword:
required: "Логин обязателен для заполнения."
$("#form_presentation").validate
invalidHandler: handlerInvalid
submitHandler: handlerValidSendAjax
rules:
name:
required: true
is_name: true
company_name:
required: true
phone:
required: true
is_phone: true
email:
required: true
is_email: true
messages:
name:
required: "Ф.И.О. обязательно для заполнения."
company_name:
required: "Имя компании обязательно для заполнения."
phone:
required: "Телефон обязателен для заполнения."
email:
required: "Email обязателен для заполнения."
email: "Введите корректный Email."
$("#form_seminar").validate
invalidHandler: handlerInvalid
submitHandler: handlerValidSendAjax
rules:
name:
required: true
is_name: true
company_name:
required: true
phone:
required: true
is_phone: true
email:
required: true
is_email: true
messages:
name:
required: "Ф.И.О. обязательно для заполнения."
company_name:
required: "Имя компании обязательно для заполнения."
phone:
required: "Телефон обязателен для заполнения."
email:
required: "Email обязателен для заполнения."
email: "Введите корректный Email."
$("#form_question").validate
invalidHandler: handlerInvalid
submitHandler: handlerValidSendAjax
rules:
author:
required: true
is_author: true
email:
required: true
is_email: true
text:
required: true
messages:
author:
required: "Ф.И.О. обязательно для заполнения."
email:
required: "Email обязателен для заполнения."
email: "Введите корректный Email."
text:
required: "Задайте, пожалуйста, вопрос."
$("#form_request").validate
invalidHandler: handlerInvalid
submitHandler: handlerValidSendAjax
rules:
author:
required: true
is_author: true
email:
required: true
is_email: true
text:
required: true
type:
required: true
title:
required: true
category_id:
required: true
messages:
author:
required: "Ф.И.О. обязательно для заполнения."
email:
required: "Email обязателен для заполнения."
email: "Введите корректный Email."
text:
required: "Задайте, пожалуйста, вопрос."
title:
required: "Задайте тему."
category_id:
required: "Выберите категорию обращения."
type:
required: "Тип вопроса обязателен к заполнению."
$("#form_registration").validate
invalidHandler: handlerInvalid
submitHandler: handlerValidSendAjax
rules:
individ:
required: true
inn:
required: true
maxlength: 12
is_number: true
kpp:
required: true
maxlength: 9
is_number: true
org_type:
required: true
org_name:
required: true
position:
required: true
email:
required: true
is_email: true
phone:
required: true
is_phone: true
messages:
individ:
required: "Это поле обязательно для заполнения."
inn:
required: "Пожалуйста, укажите ИНН"
maxlength: "Максимальное количество символов 12."
kpp:
required: "Пожалуйста, укажите КПП"
maxlength: "Максимальное количество символов 9."
org_type:
required: "Пожалуйста, укажите правовую форму"
org_name:
required: "Имя компании обязательно для заполнения."
position:
required: "Пожалуйста, укажите должность"
email:
required: "Email обязателен для заполнения."
email: "Введите корректный Email."
phone:
required: "Телефон обязателен для заполнения."
$(".blog-updates").validate
invalidHandler: handlerInvalid
submitHandler: handlerValidSubscribe
rules:
email:
required: true
is_email: true
messages:
email:
required: "Введите Email."
|
[
{
"context": "_add_user = false\n $scope.password = \n new_pwd: '',\n confirm_pwd: ''\n\n $scope.errors",
"end": 1076,
"score": 0.6672096252441406,
"start": 1069,
"tag": "PASSWORD",
"value": "new_pwd"
},
{
"context": "_val\n return\n $scope.errors.... | frontend/javascripts/app/directives/v2/controllers/setting-manage-user-panel.controller.js.coffee | MakerButt/chaipcr | 1 | window.App.controller 'SettingManageUserPanelCtrl', [
'$scope'
'User'
'Device'
($scope, User, Device) ->
$scope.users = []
$scope.errors = {}
selected_user = {}
$scope.login_user = {}
$scope.open_confirm = false
init = () ->
$scope.current_user = null
$scope.is_add_user = false
$scope.errors =
password: '',
confirm_password: ''
$scope.password =
new_pwd: '',
confirm_pwd: ''
$scope.has_changes = false
init()
User.fetch().then (users) ->
$scope.users = users
if selected_user.id
$scope.onSelectUser(selected_user)
selected_user = {}
User.getCurrent().then (resp) ->
$scope.login_user = resp.data.user
$scope.onSelectUser = (user) ->
$scope.current_user = angular.copy(user)
$scope.current_user.is_admin = if $scope.current_user.role == 'admin' then true else false
$scope.is_reset_password = false
$scope.has_changes = false
$scope.is_add_user = false
$scope.password =
new_pwd: '',
confirm_pwd: ''
$scope.errors =
email: '',
name: '',
password: '',
confirm_password: ''
$scope.onResetPassword = () ->
$scope.is_reset_password = true
$scope.has_changes = false
validatorForNewPasswd = () ->
if $scope.password.new_pwd.length > 0 and $scope.password.new_pwd.length < 4
return "Too short, minimum 4 characters required"
if $scope.password.new_pwd.length == 0 and $scope.password.confirm_pwd
return "Cannot be left blank."
return ""
validatorForConfirmPasswd = () ->
if $scope.password.confirm_pwd.length and $scope.password.confirm_pwd != $scope.password.new_pwd
return "Password must match."
return ""
$scope.$watchCollection 'current_user', (new_val, old_val)->
if !new_val || !old_val
return
$scope.errors.password = validatorForNewPasswd()
$scope.errors.confirm_password = validatorForConfirmPasswd()
$scope.has_changes = true and (!$scope.is_reset_password || ($scope.is_reset_password && !$scope.errors.password && !$scope.errors.confirm_password && $scope.password.confirm_pwd && $scope.password.new_pwd))
$scope.onUserCancel = () ->
if $scope.is_reset_password
$scope.is_reset_password = false
$scope.password =
new_pwd: '',
confirm_pwd: ''
$scope.errors.password = ''
$scope.errors.confirm_password = ''
else
init()
$scope.onAddUser = () ->
$scope.is_add_user = true
$scope.is_reset_password = true
$scope.has_changes = false
$scope.password =
new_pwd: '',
confirm_pwd: ''
$scope.current_user =
email: '',
role: '',
name: '',
is_admin: false,
show_banner: true
$scope.errors =
email: '',
name: '',
password: '',
confirm_password: ''
$scope.onUserFieldChanged = () ->
$scope.errors.password = validatorForNewPasswd()
$scope.errors.confirm_password = validatorForConfirmPasswd()
$scope.has_changes = true and (!$scope.is_reset_password || ($scope.is_reset_password && !$scope.errors.password && !$scope.errors.confirm_password && $scope.password.confirm_pwd && $scope.password.new_pwd))
$scope.onSaveChanges = () ->
if !$scope.has_changes
return
if $scope.is_reset_password
$scope.current_user.password = $scope.password.new_pwd
$scope.current_user.password_confirmation = $scope.password.confirm_pwd
$scope.current_user.role = if $scope.current_user.is_admin then 'admin' else 'default'
if $scope.current_user.id
User.updateUser($scope.current_user.id, user: $scope.current_user)
.then (user) ->
for index in [0...$scope.users.length]
if $scope.users[index].user.id == user.id
$scope.users[index].user = user
break
$scope.current_user = null
.catch (data) ->
$scope.errors.email = data.user.errors.email?[0]
$scope.errors.name = data.user.errors.name?[0]
$scope.errors.password = data.user.errors.password?[0]
else
User.save($scope.current_user)
.then (user) ->
$scope.users.push(user: user)
$scope.current_user = null
.catch (data) ->
$scope.errors.email = data.user.errors.email?[0]
$scope.errors.name = data.user.errors.name?[0]
$scope.errors.password = data.user.errors.password?[0]
$scope.onConfirmDeleteUser = () ->
$scope.open_confirm = true
$scope.delete_error = ''
$scope.onConfirmCancel = () ->
$scope.open_confirm = false
$scope.delete_error = ''
$scope.onDeleteUser = () ->
$scope.delete_error = ''
User.remove($scope.current_user.id)
.then (resp) ->
for index in [0...$scope.users.length]
if $scope.users[index].user.id == $scope.current_user.id
$scope.users.splice(index, 1)
break
$scope.current_user = null
$scope.open_confirm = false
.catch (error) ->
$scope.delete_error = error.errors.base?[0]
$scope.$on 'modal:edit-user', (e, data, oldData) ->
if $scope.users.length
$scope.onSelectUser(data.user)
else
selected_user = data.user
]
| 162177 | window.App.controller 'SettingManageUserPanelCtrl', [
'$scope'
'User'
'Device'
($scope, User, Device) ->
$scope.users = []
$scope.errors = {}
selected_user = {}
$scope.login_user = {}
$scope.open_confirm = false
init = () ->
$scope.current_user = null
$scope.is_add_user = false
$scope.errors =
password: '',
confirm_password: ''
$scope.password =
new_pwd: '',
confirm_pwd: ''
$scope.has_changes = false
init()
User.fetch().then (users) ->
$scope.users = users
if selected_user.id
$scope.onSelectUser(selected_user)
selected_user = {}
User.getCurrent().then (resp) ->
$scope.login_user = resp.data.user
$scope.onSelectUser = (user) ->
$scope.current_user = angular.copy(user)
$scope.current_user.is_admin = if $scope.current_user.role == 'admin' then true else false
$scope.is_reset_password = false
$scope.has_changes = false
$scope.is_add_user = false
$scope.password =
<PASSWORD>: '',
confirm_pwd: ''
$scope.errors =
email: '',
name: '',
password: '',
confirm_password: ''
$scope.onResetPassword = () ->
$scope.is_reset_password = true
$scope.has_changes = false
validatorForNewPasswd = () ->
if $scope.password.new_pwd.length > 0 and $scope.password.new_pwd.length < 4
return "Too short, minimum 4 characters required"
if $scope.password.new_pwd.length == 0 and $scope.password.confirm_pwd
return "Cannot be left blank."
return ""
validatorForConfirmPasswd = () ->
if $scope.password.confirm_pwd.length and $scope.password.confirm_pwd != $scope.password.new_pwd
return "Password must match."
return ""
$scope.$watchCollection 'current_user', (new_val, old_val)->
if !new_val || !old_val
return
$scope.errors.password = <PASSWORD>For<PASSWORD>()
$scope.errors.confirm_password = validatorForConfirmPasswd()
$scope.has_changes = true and (!$scope.is_reset_password || ($scope.is_reset_password && !$scope.errors.password && !$scope.errors.confirm_password && $scope.password.confirm_pwd && $scope.password.new_pwd))
$scope.onUserCancel = () ->
if $scope.is_reset_password
$scope.is_reset_password = false
$scope.password =
new_pwd: '',
confirm_pwd: ''
$scope.errors.password = ''
$scope.errors.confirm_password = ''
else
init()
$scope.onAddUser = () ->
$scope.is_add_user = true
$scope.is_reset_password = true
$scope.has_changes = false
$scope.password =
new_pwd: '',
confirm_pwd: ''
$scope.current_user =
email: '',
role: '',
name: '',
is_admin: false,
show_banner: true
$scope.errors =
email: '',
name: '',
password: '',
confirm_password: ''
$scope.onUserFieldChanged = () ->
$scope.errors.password = <PASSWORD>()
$scope.errors.confirm_password = validatorForConfirmPasswd()
$scope.has_changes = true and (!$scope.is_reset_password || ($scope.is_reset_password && !$scope.errors.password && !$scope.errors.confirm_password && $scope.password.confirm_pwd && $scope.password.new_pwd))
$scope.onSaveChanges = () ->
if !$scope.has_changes
return
if $scope.is_reset_password
$scope.current_user.password = $scope.<PASSWORD>.<PASSWORD>
$scope.current_user.password_confirmation = $scope.password.confirm_pwd
$scope.current_user.role = if $scope.current_user.is_admin then 'admin' else 'default'
if $scope.current_user.id
User.updateUser($scope.current_user.id, user: $scope.current_user)
.then (user) ->
for index in [0...$scope.users.length]
if $scope.users[index].user.id == user.id
$scope.users[index].user = user
break
$scope.current_user = null
.catch (data) ->
$scope.errors.email = data.user.errors.email?[0]
$scope.errors.name = data.user.errors.name?[0]
$scope.errors.password = data.user.errors.password?[0]
else
User.save($scope.current_user)
.then (user) ->
$scope.users.push(user: user)
$scope.current_user = null
.catch (data) ->
$scope.errors.email = data.user.errors.email?[0]
$scope.errors.name = data.user.errors.name?[0]
$scope.errors.password = data.user.errors.password?[0]
$scope.onConfirmDeleteUser = () ->
$scope.open_confirm = true
$scope.delete_error = ''
$scope.onConfirmCancel = () ->
$scope.open_confirm = false
$scope.delete_error = ''
$scope.onDeleteUser = () ->
$scope.delete_error = ''
User.remove($scope.current_user.id)
.then (resp) ->
for index in [0...$scope.users.length]
if $scope.users[index].user.id == $scope.current_user.id
$scope.users.splice(index, 1)
break
$scope.current_user = null
$scope.open_confirm = false
.catch (error) ->
$scope.delete_error = error.errors.base?[0]
$scope.$on 'modal:edit-user', (e, data, oldData) ->
if $scope.users.length
$scope.onSelectUser(data.user)
else
selected_user = data.user
]
| true | window.App.controller 'SettingManageUserPanelCtrl', [
'$scope'
'User'
'Device'
($scope, User, Device) ->
$scope.users = []
$scope.errors = {}
selected_user = {}
$scope.login_user = {}
$scope.open_confirm = false
init = () ->
$scope.current_user = null
$scope.is_add_user = false
$scope.errors =
password: '',
confirm_password: ''
$scope.password =
new_pwd: '',
confirm_pwd: ''
$scope.has_changes = false
init()
User.fetch().then (users) ->
$scope.users = users
if selected_user.id
$scope.onSelectUser(selected_user)
selected_user = {}
User.getCurrent().then (resp) ->
$scope.login_user = resp.data.user
$scope.onSelectUser = (user) ->
$scope.current_user = angular.copy(user)
$scope.current_user.is_admin = if $scope.current_user.role == 'admin' then true else false
$scope.is_reset_password = false
$scope.has_changes = false
$scope.is_add_user = false
$scope.password =
PI:PASSWORD:<PASSWORD>END_PI: '',
confirm_pwd: ''
$scope.errors =
email: '',
name: '',
password: '',
confirm_password: ''
$scope.onResetPassword = () ->
$scope.is_reset_password = true
$scope.has_changes = false
validatorForNewPasswd = () ->
if $scope.password.new_pwd.length > 0 and $scope.password.new_pwd.length < 4
return "Too short, minimum 4 characters required"
if $scope.password.new_pwd.length == 0 and $scope.password.confirm_pwd
return "Cannot be left blank."
return ""
validatorForConfirmPasswd = () ->
if $scope.password.confirm_pwd.length and $scope.password.confirm_pwd != $scope.password.new_pwd
return "Password must match."
return ""
$scope.$watchCollection 'current_user', (new_val, old_val)->
if !new_val || !old_val
return
$scope.errors.password = PI:PASSWORD:<PASSWORD>END_PIForPI:PASSWORD:<PASSWORD>END_PI()
$scope.errors.confirm_password = validatorForConfirmPasswd()
$scope.has_changes = true and (!$scope.is_reset_password || ($scope.is_reset_password && !$scope.errors.password && !$scope.errors.confirm_password && $scope.password.confirm_pwd && $scope.password.new_pwd))
$scope.onUserCancel = () ->
if $scope.is_reset_password
$scope.is_reset_password = false
$scope.password =
new_pwd: '',
confirm_pwd: ''
$scope.errors.password = ''
$scope.errors.confirm_password = ''
else
init()
$scope.onAddUser = () ->
$scope.is_add_user = true
$scope.is_reset_password = true
$scope.has_changes = false
$scope.password =
new_pwd: '',
confirm_pwd: ''
$scope.current_user =
email: '',
role: '',
name: '',
is_admin: false,
show_banner: true
$scope.errors =
email: '',
name: '',
password: '',
confirm_password: ''
$scope.onUserFieldChanged = () ->
$scope.errors.password = PI:PASSWORD:<PASSWORD>END_PI()
$scope.errors.confirm_password = validatorForConfirmPasswd()
$scope.has_changes = true and (!$scope.is_reset_password || ($scope.is_reset_password && !$scope.errors.password && !$scope.errors.confirm_password && $scope.password.confirm_pwd && $scope.password.new_pwd))
$scope.onSaveChanges = () ->
if !$scope.has_changes
return
if $scope.is_reset_password
$scope.current_user.password = $scope.PI:PASSWORD:<PASSWORD>END_PI.PI:PASSWORD:<PASSWORD>END_PI
$scope.current_user.password_confirmation = $scope.password.confirm_pwd
$scope.current_user.role = if $scope.current_user.is_admin then 'admin' else 'default'
if $scope.current_user.id
User.updateUser($scope.current_user.id, user: $scope.current_user)
.then (user) ->
for index in [0...$scope.users.length]
if $scope.users[index].user.id == user.id
$scope.users[index].user = user
break
$scope.current_user = null
.catch (data) ->
$scope.errors.email = data.user.errors.email?[0]
$scope.errors.name = data.user.errors.name?[0]
$scope.errors.password = data.user.errors.password?[0]
else
User.save($scope.current_user)
.then (user) ->
$scope.users.push(user: user)
$scope.current_user = null
.catch (data) ->
$scope.errors.email = data.user.errors.email?[0]
$scope.errors.name = data.user.errors.name?[0]
$scope.errors.password = data.user.errors.password?[0]
$scope.onConfirmDeleteUser = () ->
$scope.open_confirm = true
$scope.delete_error = ''
$scope.onConfirmCancel = () ->
$scope.open_confirm = false
$scope.delete_error = ''
$scope.onDeleteUser = () ->
$scope.delete_error = ''
User.remove($scope.current_user.id)
.then (resp) ->
for index in [0...$scope.users.length]
if $scope.users[index].user.id == $scope.current_user.id
$scope.users.splice(index, 1)
break
$scope.current_user = null
$scope.open_confirm = false
.catch (error) ->
$scope.delete_error = error.errors.base?[0]
$scope.$on 'modal:edit-user', (e, data, oldData) ->
if $scope.users.length
$scope.onSelectUser(data.user)
else
selected_user = data.user
]
|
[
{
"context": "browser uploading a file.\"\n\tmsg += \"Please contact info@mooqita.org.\"\n\tsAlert.error msg\n\n\tthrow new Meteor.Error msg\n",
"end": 639,
"score": 0.999928891658783,
"start": 623,
"tag": "EMAIL",
"value": "info@mooqita.org"
}
] | client/components/script/upload.coffee | MooqitaSFH/worklearn | 0 | ###############################################################################
#
# Upload
#
##############################################
###############################################################################
_files = {}
###############################################################################
_get_file_data_from_event = (event) ->
if event.srcElement
crm_data = event.srcElement.result
if crm_data
return crm_data
if event.target
moz_data = event.target.result
if moz_data
return moz_data
msg = "We encountered a problem with your browser uploading a file."
msg += "Please contact info@mooqita.org."
sAlert.error msg
throw new Meteor.Error msg
###############################################################################
_get_file_size_text = (byte) ->
kb = Math.round(byte / 1024)
if kb < 500
return kb + " Kbyte"
mb = Math.round(kb / 1024)
if mb < 1
return Math.round(kb / 1024, 2)
return mb + " Mbyte"
###############################################################################
_get_meta_data = (box_id) ->
if not box_id
sAlert.error('_get_meta_data: Object does not have a box_id')
res = _files[box_id]
return res
###############################################################################
_set_meta_data = (self, box_id) ->
max = self.max_size
if not self.max_size
max = 4*1024*1024
if not box_id
sAlert.error('_set_meta_data: Object does not have a box_id')
_files[box_id] =
files: []
cumulative_size: 0
max_size: max
files_to_read: 0
files_read: 0
files_up: 0
collection_name: self.collection_name
upload_method: self.method
item_id: self.item_id
field: self.field
res = _files[box_id]
return res
###############################################################################
_set_files_to_read = (size, box_id) ->
if not box_id
sAlert.error('_set_files_to_read: Object does not have a box_id')
_files[box_id].files_to_read = size
###############################################################################
_set_cumulative_size = (size, box_id) ->
if not box_id
sAlert.error('_set_cumulative_size: Object does not have a box_id')
_files[box_id].cumulative_size = size
###############################################################################
_get_cumulative_size = (box_id) ->
if not box_id
sAlert.error('_get_cumulative_size: Object does not have a box_id')
return _files[box_id].cumulative_size
###############################################################################
_increment_files_uploaded = (box_id) ->
if not box_id
sAlert.error('_increment_files_uploaded: Object does not have a box_id')
_files[box_id].files_up = _files[box_id].files_up + 1
###############################################################################
_get_files_uploaded = (box_id) ->
if not box_id
sAlert.error('_get_files_uploaded: Object does not have a box_id')
return _files[box_id].files_up
###############################################################################
_add_files = (n, box_id) ->
if not box_id
sAlert.error('_add_files: Object does not have a box_id')
d = _files[box_id].files
Array::push.apply d, n
_files[box_id].files = d
Session.set('_files', Math.random())
###############################################################################
_get_form = (box_id) ->
if not box_id
sAlert.error('_get_form: Object does not have a box_id')
frm = $('#dropbox_' + box_id)
return frm
###############################################################################
_upload_file = (self, file) ->
box_id = self.box_id.get()
if not box_id
sAlert.error('_upload_file: Object does not have a box_id')
frm = _get_form(box_id)
fileReader = new FileReader()
type = file.name.split(".")
type = type[type.length-1]
type = extension_to_mime(type)
if not typeof file == "object"
sAlert.error 'File upload failed not a valid file.'
return
fileReader.onload = (ev) ->
raw = _get_file_data_from_event(ev)
base = binary_string_to_base64(raw)
data = "data:" + type + ";base64," + base
meta = _get_meta_data(box_id)
_set_cumulative_size meta.cumulative_size + data.length, box_id
if _get_cumulative_size(box_id) > meta.max_size
frm.removeClass('is-uploading')
fs_t = _get_file_size_text _get_cumulative_size(box_id)
ms_t = _get_file_size_text meta.max_size
tx = "File upload failed. Cumulative file size is: "
tx += fs_t + "."
tx += "Maximum allowed is "
tx += ms_t + "."
sAlert.error(tx)
frm.addClass("is-error")
return
Meteor.call meta.upload_method, meta.collection_name, meta.item_id, meta.field, data, type,
(err, rsp)->
_increment_files_uploaded box_id
if err
sAlert.error('File upload failed: ' + err)
frm.addClass('is-error')
if _get_files_uploaded(box_id) == meta.files_to_read
frm.removeClass('is-uploading')
self.uploaded.set _files[box_id].files[0].name
_set_meta_data(self.data, box_id)
if not err
sAlert.success('Upload done!')
try
fileReader.readAsBinaryString(file)
catch error
sAlert.error 'File upload failed: ' + error
###############################################################################
# Upload
###############################################################################
###############################################################################
Template.upload.onCreated ->
this.uploaded = new ReactiveVar("")
files = Session.get('_files')
if not files
Session.set('_files', Math.random())
box_id = Math.floor(Math.random()*10000000)
this.box_id = new ReactiveVar(box_id)
_set_meta_data(this.data, box_id)
###############################################################################
Template.upload.onRendered ->
self = this
box_id = self.box_id.get()
submit_file = (event) ->
event.preventDefault()
frm = _get_form(box_id)
if frm.hasClass('is-uploading')
return false
if !Meteor.userId()
sAlert.error "Please login to upload files."
return
files = _get_meta_data(box_id).files
if !files
sAlert.error "No files selected to upload."
return
if files.length == 0
sAlert.error ("No files selected to upload.")
return
frm.addClass('is-uploading').removeClass('is-error')
_set_files_to_read files.length, box_id
for file in files
_upload_file(self, file)
event.target.files = null
id = "#dropbox_#{box_id}"
$(id).on "submit", submit_file
###############################################################################
Template.upload.helpers
uploaded: ->
return Template.instance().uploaded.get()
files: ->
box_id = Template.instance().box_id.get()
if Session.get('_files') != 0
return _get_meta_data(box_id).files
box_id: ->
box_id = Template.instance().box_id.get()
return box_id
upload_style: ()->
div = document.createElement('div')
do_drag = (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div))
can_do = do_drag && 'FormData' in window && 'FileReader' in window
can_do = true
if can_do == true
return('has-advanced-upload')
else
return('')
###############################################################################
Template.upload.events
'dropped .dropbox': (event) ->
box_id = Template.instance().box_id.get()
n = event.originalEvent.dataTransfer.files
_add_files n, box_id
if not this.multiple
_get_form(box_id).trigger('submit')
'change .dropbox_file': (event)->
box_id = Template.instance().box_id.get()
n = event.target.files
_add_files n, box_id
if not this.multiple
_get_form(box_id).trigger('submit')
'dragover .dropbox, dragenter .dropbox': (event)->
box_id = Template.instance().box_id.get()
_get_form(box_id).addClass('is-dragover')
'dragleave .dropbox, dragend .dropbox, drop .dropbox': (event)->
box_id = Template.instance().box_id.get()
_get_form(box_id).removeClass('is-dragover')
'click .dropbox_restart': (event) ->
box_id = Template.instance().box_id.get()
_set_meta_data(Template.instance().data, box_id)
_get_form(box_id).removeClass('is-uploading').removeClass('is-error')
'dragexit .dropbox': (event) ->
sAlert.info('exit')
| 90937 | ###############################################################################
#
# Upload
#
##############################################
###############################################################################
_files = {}
###############################################################################
_get_file_data_from_event = (event) ->
if event.srcElement
crm_data = event.srcElement.result
if crm_data
return crm_data
if event.target
moz_data = event.target.result
if moz_data
return moz_data
msg = "We encountered a problem with your browser uploading a file."
msg += "Please contact <EMAIL>."
sAlert.error msg
throw new Meteor.Error msg
###############################################################################
_get_file_size_text = (byte) ->
kb = Math.round(byte / 1024)
if kb < 500
return kb + " Kbyte"
mb = Math.round(kb / 1024)
if mb < 1
return Math.round(kb / 1024, 2)
return mb + " Mbyte"
###############################################################################
_get_meta_data = (box_id) ->
if not box_id
sAlert.error('_get_meta_data: Object does not have a box_id')
res = _files[box_id]
return res
###############################################################################
_set_meta_data = (self, box_id) ->
max = self.max_size
if not self.max_size
max = 4*1024*1024
if not box_id
sAlert.error('_set_meta_data: Object does not have a box_id')
_files[box_id] =
files: []
cumulative_size: 0
max_size: max
files_to_read: 0
files_read: 0
files_up: 0
collection_name: self.collection_name
upload_method: self.method
item_id: self.item_id
field: self.field
res = _files[box_id]
return res
###############################################################################
_set_files_to_read = (size, box_id) ->
if not box_id
sAlert.error('_set_files_to_read: Object does not have a box_id')
_files[box_id].files_to_read = size
###############################################################################
_set_cumulative_size = (size, box_id) ->
if not box_id
sAlert.error('_set_cumulative_size: Object does not have a box_id')
_files[box_id].cumulative_size = size
###############################################################################
_get_cumulative_size = (box_id) ->
if not box_id
sAlert.error('_get_cumulative_size: Object does not have a box_id')
return _files[box_id].cumulative_size
###############################################################################
_increment_files_uploaded = (box_id) ->
if not box_id
sAlert.error('_increment_files_uploaded: Object does not have a box_id')
_files[box_id].files_up = _files[box_id].files_up + 1
###############################################################################
_get_files_uploaded = (box_id) ->
if not box_id
sAlert.error('_get_files_uploaded: Object does not have a box_id')
return _files[box_id].files_up
###############################################################################
_add_files = (n, box_id) ->
if not box_id
sAlert.error('_add_files: Object does not have a box_id')
d = _files[box_id].files
Array::push.apply d, n
_files[box_id].files = d
Session.set('_files', Math.random())
###############################################################################
_get_form = (box_id) ->
if not box_id
sAlert.error('_get_form: Object does not have a box_id')
frm = $('#dropbox_' + box_id)
return frm
###############################################################################
_upload_file = (self, file) ->
box_id = self.box_id.get()
if not box_id
sAlert.error('_upload_file: Object does not have a box_id')
frm = _get_form(box_id)
fileReader = new FileReader()
type = file.name.split(".")
type = type[type.length-1]
type = extension_to_mime(type)
if not typeof file == "object"
sAlert.error 'File upload failed not a valid file.'
return
fileReader.onload = (ev) ->
raw = _get_file_data_from_event(ev)
base = binary_string_to_base64(raw)
data = "data:" + type + ";base64," + base
meta = _get_meta_data(box_id)
_set_cumulative_size meta.cumulative_size + data.length, box_id
if _get_cumulative_size(box_id) > meta.max_size
frm.removeClass('is-uploading')
fs_t = _get_file_size_text _get_cumulative_size(box_id)
ms_t = _get_file_size_text meta.max_size
tx = "File upload failed. Cumulative file size is: "
tx += fs_t + "."
tx += "Maximum allowed is "
tx += ms_t + "."
sAlert.error(tx)
frm.addClass("is-error")
return
Meteor.call meta.upload_method, meta.collection_name, meta.item_id, meta.field, data, type,
(err, rsp)->
_increment_files_uploaded box_id
if err
sAlert.error('File upload failed: ' + err)
frm.addClass('is-error')
if _get_files_uploaded(box_id) == meta.files_to_read
frm.removeClass('is-uploading')
self.uploaded.set _files[box_id].files[0].name
_set_meta_data(self.data, box_id)
if not err
sAlert.success('Upload done!')
try
fileReader.readAsBinaryString(file)
catch error
sAlert.error 'File upload failed: ' + error
###############################################################################
# Upload
###############################################################################
###############################################################################
Template.upload.onCreated ->
this.uploaded = new ReactiveVar("")
files = Session.get('_files')
if not files
Session.set('_files', Math.random())
box_id = Math.floor(Math.random()*10000000)
this.box_id = new ReactiveVar(box_id)
_set_meta_data(this.data, box_id)
###############################################################################
Template.upload.onRendered ->
self = this
box_id = self.box_id.get()
submit_file = (event) ->
event.preventDefault()
frm = _get_form(box_id)
if frm.hasClass('is-uploading')
return false
if !Meteor.userId()
sAlert.error "Please login to upload files."
return
files = _get_meta_data(box_id).files
if !files
sAlert.error "No files selected to upload."
return
if files.length == 0
sAlert.error ("No files selected to upload.")
return
frm.addClass('is-uploading').removeClass('is-error')
_set_files_to_read files.length, box_id
for file in files
_upload_file(self, file)
event.target.files = null
id = "#dropbox_#{box_id}"
$(id).on "submit", submit_file
###############################################################################
Template.upload.helpers
uploaded: ->
return Template.instance().uploaded.get()
files: ->
box_id = Template.instance().box_id.get()
if Session.get('_files') != 0
return _get_meta_data(box_id).files
box_id: ->
box_id = Template.instance().box_id.get()
return box_id
upload_style: ()->
div = document.createElement('div')
do_drag = (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div))
can_do = do_drag && 'FormData' in window && 'FileReader' in window
can_do = true
if can_do == true
return('has-advanced-upload')
else
return('')
###############################################################################
Template.upload.events
'dropped .dropbox': (event) ->
box_id = Template.instance().box_id.get()
n = event.originalEvent.dataTransfer.files
_add_files n, box_id
if not this.multiple
_get_form(box_id).trigger('submit')
'change .dropbox_file': (event)->
box_id = Template.instance().box_id.get()
n = event.target.files
_add_files n, box_id
if not this.multiple
_get_form(box_id).trigger('submit')
'dragover .dropbox, dragenter .dropbox': (event)->
box_id = Template.instance().box_id.get()
_get_form(box_id).addClass('is-dragover')
'dragleave .dropbox, dragend .dropbox, drop .dropbox': (event)->
box_id = Template.instance().box_id.get()
_get_form(box_id).removeClass('is-dragover')
'click .dropbox_restart': (event) ->
box_id = Template.instance().box_id.get()
_set_meta_data(Template.instance().data, box_id)
_get_form(box_id).removeClass('is-uploading').removeClass('is-error')
'dragexit .dropbox': (event) ->
sAlert.info('exit')
| true | ###############################################################################
#
# Upload
#
##############################################
###############################################################################
_files = {}
###############################################################################
_get_file_data_from_event = (event) ->
if event.srcElement
crm_data = event.srcElement.result
if crm_data
return crm_data
if event.target
moz_data = event.target.result
if moz_data
return moz_data
msg = "We encountered a problem with your browser uploading a file."
msg += "Please contact PI:EMAIL:<EMAIL>END_PI."
sAlert.error msg
throw new Meteor.Error msg
###############################################################################
_get_file_size_text = (byte) ->
kb = Math.round(byte / 1024)
if kb < 500
return kb + " Kbyte"
mb = Math.round(kb / 1024)
if mb < 1
return Math.round(kb / 1024, 2)
return mb + " Mbyte"
###############################################################################
_get_meta_data = (box_id) ->
if not box_id
sAlert.error('_get_meta_data: Object does not have a box_id')
res = _files[box_id]
return res
###############################################################################
_set_meta_data = (self, box_id) ->
max = self.max_size
if not self.max_size
max = 4*1024*1024
if not box_id
sAlert.error('_set_meta_data: Object does not have a box_id')
_files[box_id] =
files: []
cumulative_size: 0
max_size: max
files_to_read: 0
files_read: 0
files_up: 0
collection_name: self.collection_name
upload_method: self.method
item_id: self.item_id
field: self.field
res = _files[box_id]
return res
###############################################################################
_set_files_to_read = (size, box_id) ->
if not box_id
sAlert.error('_set_files_to_read: Object does not have a box_id')
_files[box_id].files_to_read = size
###############################################################################
_set_cumulative_size = (size, box_id) ->
if not box_id
sAlert.error('_set_cumulative_size: Object does not have a box_id')
_files[box_id].cumulative_size = size
###############################################################################
_get_cumulative_size = (box_id) ->
if not box_id
sAlert.error('_get_cumulative_size: Object does not have a box_id')
return _files[box_id].cumulative_size
###############################################################################
_increment_files_uploaded = (box_id) ->
if not box_id
sAlert.error('_increment_files_uploaded: Object does not have a box_id')
_files[box_id].files_up = _files[box_id].files_up + 1
###############################################################################
_get_files_uploaded = (box_id) ->
if not box_id
sAlert.error('_get_files_uploaded: Object does not have a box_id')
return _files[box_id].files_up
###############################################################################
_add_files = (n, box_id) ->
if not box_id
sAlert.error('_add_files: Object does not have a box_id')
d = _files[box_id].files
Array::push.apply d, n
_files[box_id].files = d
Session.set('_files', Math.random())
###############################################################################
_get_form = (box_id) ->
if not box_id
sAlert.error('_get_form: Object does not have a box_id')
frm = $('#dropbox_' + box_id)
return frm
###############################################################################
_upload_file = (self, file) ->
box_id = self.box_id.get()
if not box_id
sAlert.error('_upload_file: Object does not have a box_id')
frm = _get_form(box_id)
fileReader = new FileReader()
type = file.name.split(".")
type = type[type.length-1]
type = extension_to_mime(type)
if not typeof file == "object"
sAlert.error 'File upload failed not a valid file.'
return
fileReader.onload = (ev) ->
raw = _get_file_data_from_event(ev)
base = binary_string_to_base64(raw)
data = "data:" + type + ";base64," + base
meta = _get_meta_data(box_id)
_set_cumulative_size meta.cumulative_size + data.length, box_id
if _get_cumulative_size(box_id) > meta.max_size
frm.removeClass('is-uploading')
fs_t = _get_file_size_text _get_cumulative_size(box_id)
ms_t = _get_file_size_text meta.max_size
tx = "File upload failed. Cumulative file size is: "
tx += fs_t + "."
tx += "Maximum allowed is "
tx += ms_t + "."
sAlert.error(tx)
frm.addClass("is-error")
return
Meteor.call meta.upload_method, meta.collection_name, meta.item_id, meta.field, data, type,
(err, rsp)->
_increment_files_uploaded box_id
if err
sAlert.error('File upload failed: ' + err)
frm.addClass('is-error')
if _get_files_uploaded(box_id) == meta.files_to_read
frm.removeClass('is-uploading')
self.uploaded.set _files[box_id].files[0].name
_set_meta_data(self.data, box_id)
if not err
sAlert.success('Upload done!')
try
fileReader.readAsBinaryString(file)
catch error
sAlert.error 'File upload failed: ' + error
###############################################################################
# Upload
###############################################################################
###############################################################################
Template.upload.onCreated ->
this.uploaded = new ReactiveVar("")
files = Session.get('_files')
if not files
Session.set('_files', Math.random())
box_id = Math.floor(Math.random()*10000000)
this.box_id = new ReactiveVar(box_id)
_set_meta_data(this.data, box_id)
###############################################################################
Template.upload.onRendered ->
self = this
box_id = self.box_id.get()
submit_file = (event) ->
event.preventDefault()
frm = _get_form(box_id)
if frm.hasClass('is-uploading')
return false
if !Meteor.userId()
sAlert.error "Please login to upload files."
return
files = _get_meta_data(box_id).files
if !files
sAlert.error "No files selected to upload."
return
if files.length == 0
sAlert.error ("No files selected to upload.")
return
frm.addClass('is-uploading').removeClass('is-error')
_set_files_to_read files.length, box_id
for file in files
_upload_file(self, file)
event.target.files = null
id = "#dropbox_#{box_id}"
$(id).on "submit", submit_file
###############################################################################
Template.upload.helpers
uploaded: ->
return Template.instance().uploaded.get()
files: ->
box_id = Template.instance().box_id.get()
if Session.get('_files') != 0
return _get_meta_data(box_id).files
box_id: ->
box_id = Template.instance().box_id.get()
return box_id
upload_style: ()->
div = document.createElement('div')
do_drag = (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div))
can_do = do_drag && 'FormData' in window && 'FileReader' in window
can_do = true
if can_do == true
return('has-advanced-upload')
else
return('')
###############################################################################
Template.upload.events
'dropped .dropbox': (event) ->
box_id = Template.instance().box_id.get()
n = event.originalEvent.dataTransfer.files
_add_files n, box_id
if not this.multiple
_get_form(box_id).trigger('submit')
'change .dropbox_file': (event)->
box_id = Template.instance().box_id.get()
n = event.target.files
_add_files n, box_id
if not this.multiple
_get_form(box_id).trigger('submit')
'dragover .dropbox, dragenter .dropbox': (event)->
box_id = Template.instance().box_id.get()
_get_form(box_id).addClass('is-dragover')
'dragleave .dropbox, dragend .dropbox, drop .dropbox': (event)->
box_id = Template.instance().box_id.get()
_get_form(box_id).removeClass('is-dragover')
'click .dropbox_restart': (event) ->
box_id = Template.instance().box_id.get()
_set_meta_data(Template.instance().data, box_id)
_get_form(box_id).removeClass('is-uploading').removeClass('is-error')
'dragexit .dropbox': (event) ->
sAlert.info('exit')
|
[
{
"context": "one) ->\n\t\t\trequest.get\n\t\t\t\turl: \"#{url}/crud?name=Andrew\"\n\t\t\t, (err, response, body) ->\n\t\t\t\tshould.not.exi",
"end": 2361,
"score": 0.9930901527404785,
"start": 2355,
"tag": "NAME",
"value": "Andrew"
},
{
"context": "should.be.exactly 1\n\t\t\t\t(res[... | test/lib/crud-test.coffee | winnlab/Optimeal | 0 | _ = require 'underscore'
async = require 'async'
should = require 'should'
request = require 'request'
express = require 'express'
mongoose = require 'mongoose'
supertest = require 'supertest'
url = 'http://localhost:3000'
data = require '../../test-helpers/migrate'
TestModel = require '../../test-helpers/model'
Server = require '../../test-helpers/server'
Model = require '../../lib/model'
Crud = require '../../lib/crud'
crud = new Crud modelName: 'Test'
routing = ->
Router = express.Router()
REST = crud.request.bind crud
Router.get '/crud', REST
Router.get '/crud/:id?', REST
Router.post '/crud', REST
Router.put '/crud/:id?', REST
Router.delete '/crud/:id?', REST
return Router
beforeData = (done) ->
async.each data.data, (entity, proceed) ->
TestModel.findByIdAndUpdate entity._id, entity, upsert: true, ->
proceed()
, done
afterData = (done) ->
mongoose.connection.db.dropCollection 'test', done
###
Spec describes
###
describe.skip 'CRUD library', ->
before (done) ->
Server.app.use '/', routing()
Server.startServer 3000, done
after (done) ->
Server.stopServer done
beforeEach (done) ->
beforeData done
afterEach (done) ->
afterData done
describe '- utils', ->
query = null
beforeEach ->
query =
queryOptions:
skip: 10
limit: 10
fields: "name description"
id: 'some id'
it 'should getOptions from query', ->
crud._getOptions(query).should.be.exactly query.queryOptions
it 'should get "fields" attribute from query and remove it', ->
crud._parseFields(query).should.be.exactly 'name description'
(query.queryOptions).should.not.have.property 'fields'
it 'should get "queryOptions" attribute from query and remove it', ->
crud._parseOptions(query).should.be.eql {
skip: 10
limit: 10
fields: "name description"
}
(query).should.not.have.property 'queryOptions'
describe '- findAll', ->
it 'should have findAll() method', ->
crud.should.have.property '_findAll'
crud.should.have.property 'findAll'
it 'should return all objects from test', (done) ->
request.get
url: "#{url}/crud"
, (err, response, body) ->
should.not.exist err
res = JSON.parse(body).data
(res.length).should.be.exactly 3
done()
it 'should return Andrew entity', (done) ->
request.get
url: "#{url}/crud?name=Andrew"
, (err, response, body) ->
should.not.exist err
res = JSON.parse(body).data
(res.length).should.be.exactly 1
(res[0].name).should.eql 'Andrew'
done()
it 'should return just one entity', (done) ->
request.get
url: "#{url}/crud?queryOptions%5Blimit%5D=1"
, (err, response, body) ->
should.not.exist err
res = JSON.parse(body).data
(res.length).should.be.exactly 1
done()
it 'should return one entity ofseted entity only with "_id" and "name" attribute', (done) ->
request.get
url: "#{url}/crud?queryOptions%5Blimit%5D=1&queryOptions%5Bskip%5D=1&queryOptions%5Bfields%5D=name"
, (err, response, body) ->
should.not.exist err
res = JSON.parse(body).data[0]
(res).should.have.keys '_id', 'name'
(res).should.not.have.keys 'position'
(res).should.containEql _.pick data.data[1], '_id', 'name'
done()
it 'should sort entities by name', (done) ->
request.get
url: "#{url}/crud?queryOptions%5Bsort%5D=name"
, (err, response, body) ->
should.not.exist err
res = JSON.parse(body).data
sorted = _.sortBy data.data, (entity) ->
return entity.name
(res.length).should.be.exactly 3
(res).should.containDeep sorted
done()
describe '- findOne', ->
it 'should have findOne method', ->
crud.should.have.property '_findOne'
crud.should.have.property 'findOne'
it 'should find entity by id', (done) ->
randEtity = data.data[_.random 0, data.data.length - 1]
request.get
url: "#{url}/crud/#{randEtity._id}"
, (err, response, body) ->
should.not.exist err
res = JSON.parse(body).data
(res).should.containDeep randEtity
done()
describe '- save', ->
it 'should have save method', ->
crud.should.have.property '_save'
crud.should.have.property 'add'
crud.should.have.property 'update'
it 'should add entity to collection', (done) ->
newTest =
name: 'Mark'
email: 'kasyanov.mark@gmail.com'
position: 4
supertest(Server.app)
.post('/crud')
.send(newTest)
# .expect('Content-Type', /json/)
# .expect(200)
.end (err, res) ->
should.not.exist err
should.exist res.body.data
res.body.data.should.be.a.String
done()
it 'should update entity in collection', (done) ->
updateData =
name: 'Andrew update'
email: 'andrew.updated.sygyda@gmail.com'
position: 5
updatedData = _.extend data.data[0], updateData
supertest(Server.app)
.put("/crud/#{updatedData._id}")
.send(updatedData)
.expect('Content-Type', /json/)
.expect(200)
.end (err, res) ->
should.not.exist err
should.exist res.body.data
(res.body.data).should.eql updatedData
done()
describe '- remove', ->
it 'should have findOne method', ->
crud.should.have.property '_remove'
crud.should.have.property 'remove'
it 'should remove document from collection', (done) ->
supertest(Server.app)
.delete("/crud/#{data.data[0]._id}")
.expect('Content-Type', /json/)
.expect(200)
.end (err, res) ->
should.not.exist err
should.exist res.body.data
(res.body.data._id).should.eql data.data[0]._id
done()
it 'should return error if no "id" param is pass', (done) ->
supertest(Server.app)
.delete("/crud")
.expect('Content-Type', /json/)
.expect(500)
.end (err, res) ->
should.not.exist err
res.body.success.should.eql false
res.body.err.should.eql 'There no "id" param in a query'
done()
| 15714 | _ = require 'underscore'
async = require 'async'
should = require 'should'
request = require 'request'
express = require 'express'
mongoose = require 'mongoose'
supertest = require 'supertest'
url = 'http://localhost:3000'
data = require '../../test-helpers/migrate'
TestModel = require '../../test-helpers/model'
Server = require '../../test-helpers/server'
Model = require '../../lib/model'
Crud = require '../../lib/crud'
crud = new Crud modelName: 'Test'
routing = ->
Router = express.Router()
REST = crud.request.bind crud
Router.get '/crud', REST
Router.get '/crud/:id?', REST
Router.post '/crud', REST
Router.put '/crud/:id?', REST
Router.delete '/crud/:id?', REST
return Router
beforeData = (done) ->
async.each data.data, (entity, proceed) ->
TestModel.findByIdAndUpdate entity._id, entity, upsert: true, ->
proceed()
, done
afterData = (done) ->
mongoose.connection.db.dropCollection 'test', done
###
Spec describes
###
describe.skip 'CRUD library', ->
before (done) ->
Server.app.use '/', routing()
Server.startServer 3000, done
after (done) ->
Server.stopServer done
beforeEach (done) ->
beforeData done
afterEach (done) ->
afterData done
describe '- utils', ->
query = null
beforeEach ->
query =
queryOptions:
skip: 10
limit: 10
fields: "name description"
id: 'some id'
it 'should getOptions from query', ->
crud._getOptions(query).should.be.exactly query.queryOptions
it 'should get "fields" attribute from query and remove it', ->
crud._parseFields(query).should.be.exactly 'name description'
(query.queryOptions).should.not.have.property 'fields'
it 'should get "queryOptions" attribute from query and remove it', ->
crud._parseOptions(query).should.be.eql {
skip: 10
limit: 10
fields: "name description"
}
(query).should.not.have.property 'queryOptions'
describe '- findAll', ->
it 'should have findAll() method', ->
crud.should.have.property '_findAll'
crud.should.have.property 'findAll'
it 'should return all objects from test', (done) ->
request.get
url: "#{url}/crud"
, (err, response, body) ->
should.not.exist err
res = JSON.parse(body).data
(res.length).should.be.exactly 3
done()
it 'should return Andrew entity', (done) ->
request.get
url: "#{url}/crud?name=<NAME>"
, (err, response, body) ->
should.not.exist err
res = JSON.parse(body).data
(res.length).should.be.exactly 1
(res[0].name).should.eql '<NAME>'
done()
it 'should return just one entity', (done) ->
request.get
url: "#{url}/crud?queryOptions%5Blimit%5D=1"
, (err, response, body) ->
should.not.exist err
res = JSON.parse(body).data
(res.length).should.be.exactly 1
done()
it 'should return one entity ofseted entity only with "_id" and "name" attribute', (done) ->
request.get
url: "#{url}/crud?queryOptions%5Blimit%5D=1&queryOptions%5Bskip%5D=1&queryOptions%5Bfields%5D=name"
, (err, response, body) ->
should.not.exist err
res = JSON.parse(body).data[0]
(res).should.have.keys '_id', 'name'
(res).should.not.have.keys 'position'
(res).should.containEql _.pick data.data[1], '_id', 'name'
done()
it 'should sort entities by name', (done) ->
request.get
url: "#{url}/crud?queryOptions%5Bsort%5D=name"
, (err, response, body) ->
should.not.exist err
res = JSON.parse(body).data
sorted = _.sortBy data.data, (entity) ->
return entity.name
(res.length).should.be.exactly 3
(res).should.containDeep sorted
done()
describe '- findOne', ->
it 'should have findOne method', ->
crud.should.have.property '_findOne'
crud.should.have.property 'findOne'
it 'should find entity by id', (done) ->
randEtity = data.data[_.random 0, data.data.length - 1]
request.get
url: "#{url}/crud/#{randEtity._id}"
, (err, response, body) ->
should.not.exist err
res = JSON.parse(body).data
(res).should.containDeep randEtity
done()
describe '- save', ->
it 'should have save method', ->
crud.should.have.property '_save'
crud.should.have.property 'add'
crud.should.have.property 'update'
it 'should add entity to collection', (done) ->
newTest =
name: '<NAME>'
email: '<EMAIL>'
position: 4
supertest(Server.app)
.post('/crud')
.send(newTest)
# .expect('Content-Type', /json/)
# .expect(200)
.end (err, res) ->
should.not.exist err
should.exist res.body.data
res.body.data.should.be.a.String
done()
it 'should update entity in collection', (done) ->
updateData =
name: '<NAME>'
email: '<EMAIL>'
position: 5
updatedData = _.extend data.data[0], updateData
supertest(Server.app)
.put("/crud/#{updatedData._id}")
.send(updatedData)
.expect('Content-Type', /json/)
.expect(200)
.end (err, res) ->
should.not.exist err
should.exist res.body.data
(res.body.data).should.eql updatedData
done()
describe '- remove', ->
it 'should have findOne method', ->
crud.should.have.property '_remove'
crud.should.have.property 'remove'
it 'should remove document from collection', (done) ->
supertest(Server.app)
.delete("/crud/#{data.data[0]._id}")
.expect('Content-Type', /json/)
.expect(200)
.end (err, res) ->
should.not.exist err
should.exist res.body.data
(res.body.data._id).should.eql data.data[0]._id
done()
it 'should return error if no "id" param is pass', (done) ->
supertest(Server.app)
.delete("/crud")
.expect('Content-Type', /json/)
.expect(500)
.end (err, res) ->
should.not.exist err
res.body.success.should.eql false
res.body.err.should.eql 'There no "id" param in a query'
done()
| true | _ = require 'underscore'
async = require 'async'
should = require 'should'
request = require 'request'
express = require 'express'
mongoose = require 'mongoose'
supertest = require 'supertest'
url = 'http://localhost:3000'
data = require '../../test-helpers/migrate'
TestModel = require '../../test-helpers/model'
Server = require '../../test-helpers/server'
Model = require '../../lib/model'
Crud = require '../../lib/crud'
crud = new Crud modelName: 'Test'
routing = ->
Router = express.Router()
REST = crud.request.bind crud
Router.get '/crud', REST
Router.get '/crud/:id?', REST
Router.post '/crud', REST
Router.put '/crud/:id?', REST
Router.delete '/crud/:id?', REST
return Router
beforeData = (done) ->
async.each data.data, (entity, proceed) ->
TestModel.findByIdAndUpdate entity._id, entity, upsert: true, ->
proceed()
, done
afterData = (done) ->
mongoose.connection.db.dropCollection 'test', done
###
Spec describes
###
describe.skip 'CRUD library', ->
before (done) ->
Server.app.use '/', routing()
Server.startServer 3000, done
after (done) ->
Server.stopServer done
beforeEach (done) ->
beforeData done
afterEach (done) ->
afterData done
describe '- utils', ->
query = null
beforeEach ->
query =
queryOptions:
skip: 10
limit: 10
fields: "name description"
id: 'some id'
it 'should getOptions from query', ->
crud._getOptions(query).should.be.exactly query.queryOptions
it 'should get "fields" attribute from query and remove it', ->
crud._parseFields(query).should.be.exactly 'name description'
(query.queryOptions).should.not.have.property 'fields'
it 'should get "queryOptions" attribute from query and remove it', ->
crud._parseOptions(query).should.be.eql {
skip: 10
limit: 10
fields: "name description"
}
(query).should.not.have.property 'queryOptions'
describe '- findAll', ->
it 'should have findAll() method', ->
crud.should.have.property '_findAll'
crud.should.have.property 'findAll'
it 'should return all objects from test', (done) ->
request.get
url: "#{url}/crud"
, (err, response, body) ->
should.not.exist err
res = JSON.parse(body).data
(res.length).should.be.exactly 3
done()
it 'should return Andrew entity', (done) ->
request.get
url: "#{url}/crud?name=PI:NAME:<NAME>END_PI"
, (err, response, body) ->
should.not.exist err
res = JSON.parse(body).data
(res.length).should.be.exactly 1
(res[0].name).should.eql 'PI:NAME:<NAME>END_PI'
done()
it 'should return just one entity', (done) ->
request.get
url: "#{url}/crud?queryOptions%5Blimit%5D=1"
, (err, response, body) ->
should.not.exist err
res = JSON.parse(body).data
(res.length).should.be.exactly 1
done()
it 'should return one entity ofseted entity only with "_id" and "name" attribute', (done) ->
request.get
url: "#{url}/crud?queryOptions%5Blimit%5D=1&queryOptions%5Bskip%5D=1&queryOptions%5Bfields%5D=name"
, (err, response, body) ->
should.not.exist err
res = JSON.parse(body).data[0]
(res).should.have.keys '_id', 'name'
(res).should.not.have.keys 'position'
(res).should.containEql _.pick data.data[1], '_id', 'name'
done()
it 'should sort entities by name', (done) ->
request.get
url: "#{url}/crud?queryOptions%5Bsort%5D=name"
, (err, response, body) ->
should.not.exist err
res = JSON.parse(body).data
sorted = _.sortBy data.data, (entity) ->
return entity.name
(res.length).should.be.exactly 3
(res).should.containDeep sorted
done()
describe '- findOne', ->
it 'should have findOne method', ->
crud.should.have.property '_findOne'
crud.should.have.property 'findOne'
it 'should find entity by id', (done) ->
randEtity = data.data[_.random 0, data.data.length - 1]
request.get
url: "#{url}/crud/#{randEtity._id}"
, (err, response, body) ->
should.not.exist err
res = JSON.parse(body).data
(res).should.containDeep randEtity
done()
describe '- save', ->
it 'should have save method', ->
crud.should.have.property '_save'
crud.should.have.property 'add'
crud.should.have.property 'update'
it 'should add entity to collection', (done) ->
newTest =
name: 'PI:NAME:<NAME>END_PI'
email: 'PI:EMAIL:<EMAIL>END_PI'
position: 4
supertest(Server.app)
.post('/crud')
.send(newTest)
# .expect('Content-Type', /json/)
# .expect(200)
.end (err, res) ->
should.not.exist err
should.exist res.body.data
res.body.data.should.be.a.String
done()
it 'should update entity in collection', (done) ->
updateData =
name: 'PI:NAME:<NAME>END_PI'
email: 'PI:EMAIL:<EMAIL>END_PI'
position: 5
updatedData = _.extend data.data[0], updateData
supertest(Server.app)
.put("/crud/#{updatedData._id}")
.send(updatedData)
.expect('Content-Type', /json/)
.expect(200)
.end (err, res) ->
should.not.exist err
should.exist res.body.data
(res.body.data).should.eql updatedData
done()
describe '- remove', ->
it 'should have findOne method', ->
crud.should.have.property '_remove'
crud.should.have.property 'remove'
it 'should remove document from collection', (done) ->
supertest(Server.app)
.delete("/crud/#{data.data[0]._id}")
.expect('Content-Type', /json/)
.expect(200)
.end (err, res) ->
should.not.exist err
should.exist res.body.data
(res.body.data._id).should.eql data.data[0]._id
done()
it 'should return error if no "id" param is pass', (done) ->
supertest(Server.app)
.delete("/crud")
.expect('Content-Type', /json/)
.expect(500)
.end (err, res) ->
should.not.exist err
res.body.success.should.eql false
res.body.err.should.eql 'There no "id" param in a query'
done()
|
[
{
"context": "bol(\"http://xmlns.com/foaf/0.1/name\")\n o: \"Bob Builder\"\n expect: '<http://example.com/btb> <http:",
"end": 230,
"score": 0.9998116493225098,
"start": 219,
"tag": "NAME",
"value": "Bob Builder"
},
{
"context": "xample.com/btb> <http://xmlns.com/foaf/0... | tests/term.coffee | nicola/rdflib.js | 4 | ###
# nodeunit tests for term.js
###
$rdf = require '../term.js'
tests =
statement: [{
s: new $rdf.Symbol("http://example.com/btb")
p: new $rdf.Symbol("http://xmlns.com/foaf/0.1/name")
o: "Bob Builder"
expect: '<http://example.com/btb> <http://xmlns.com/foaf/0.1/name> "Bob Builder" .'
}]
formula: [{
s: new $rdf.Symbol("http://example.com/btb")
p: new $rdf.Symbol("http://xmlns.com/foaf/0.1/name")
o: "Builder"
expect: '{<http://example.com/btb> <http://xmlns.com/foaf/0.1/name> "Builder" .}'
},{
s: new $rdf.BlankNode()
p: new $rdf.Symbol("http://xmlns.com/foaf/0.1/firstname")
o: "Bob"
expect: '{_:n0 <http://xmlns.com/foaf/0.1/firstname> "Bob" .}'
},{
s: new $rdf.Symbol("http://example.com/btb")
p: new $rdf.Symbol("http://xmlns.com/foaf/0.1/lastname")
o: new $rdf.Literal("Builder", "en")
expect: '{<http://example.com/btb> <http://xmlns.com/foaf/0.1/lastname> "Builder"@en .}'
},{
s: new $rdf.Symbol("http://example.com/btb")
p: new $rdf.Symbol("http://example.org/vocab#shoeSize")
o: new $rdf.Literal("30", undefined, (new $rdf.Namespace("http://www.w3.org/2001/XMLSchema#"))('integer'))
expect: '{<http://example.com/btb> <http://example.org/vocab#shoeSize> "30"^^<http://www.w3.org/2001/XMLSchema#integer> .}'
}]
statementTest = (s, p, o, expect) ->
(test) ->
triple = new $rdf.Statement s, p, o, undefined
test.equal triple.toString(), expect
test.done()
formulaTest = (s, p, o, expect) ->
(test) ->
kb = new $rdf.Formula
kb.add s, p, o
test.equal kb.toNT(), expect
test.done()
module.exports =
Statement: {}
Formula: {}
for {s, p, o, expect} in tests.statement
module.exports.Statement["(#{s}, #{p}, #{o}) == '#{expect}'"] = statementTest s, p, o, expect
for {s, p, o, expect} in tests.formula
module.exports.Formula["(#{s}, #{p}, #{o}) == '#{expect}'"] = formulaTest s, p, o, expect
| 97180 | ###
# nodeunit tests for term.js
###
$rdf = require '../term.js'
tests =
statement: [{
s: new $rdf.Symbol("http://example.com/btb")
p: new $rdf.Symbol("http://xmlns.com/foaf/0.1/name")
o: "<NAME>"
expect: '<http://example.com/btb> <http://xmlns.com/foaf/0.1/name> "<NAME>" .'
}]
formula: [{
s: new $rdf.Symbol("http://example.com/btb")
p: new $rdf.Symbol("http://xmlns.com/foaf/0.1/name")
o: "Builder"
expect: '{<http://example.com/btb> <http://xmlns.com/foaf/0.1/name> "Builder" .}'
},{
s: new $rdf.BlankNode()
p: new $rdf.Symbol("http://xmlns.com/foaf/0.1/firstname")
o: "<NAME>"
expect: '{_:n0 <http://xmlns.com/foaf/0.1/firstname> "<NAME>" .}'
},{
s: new $rdf.Symbol("http://example.com/btb")
p: new $rdf.Symbol("http://xmlns.com/foaf/0.1/lastname")
o: new $rdf.Literal("Builder", "en")
expect: '{<http://example.com/btb> <http://xmlns.com/foaf/0.1/lastname> "Builder"@en .}'
},{
s: new $rdf.Symbol("http://example.com/btb")
p: new $rdf.Symbol("http://example.org/vocab#shoeSize")
o: new $rdf.Literal("30", undefined, (new $rdf.Namespace("http://www.w3.org/2001/XMLSchema#"))('integer'))
expect: '{<http://example.com/btb> <http://example.org/vocab#shoeSize> "30"^^<http://www.w3.org/2001/XMLSchema#integer> .}'
}]
statementTest = (s, p, o, expect) ->
(test) ->
triple = new $rdf.Statement s, p, o, undefined
test.equal triple.toString(), expect
test.done()
formulaTest = (s, p, o, expect) ->
(test) ->
kb = new $rdf.Formula
kb.add s, p, o
test.equal kb.toNT(), expect
test.done()
module.exports =
Statement: {}
Formula: {}
for {s, p, o, expect} in tests.statement
module.exports.Statement["(#{s}, #{p}, #{o}) == '#{expect}'"] = statementTest s, p, o, expect
for {s, p, o, expect} in tests.formula
module.exports.Formula["(#{s}, #{p}, #{o}) == '#{expect}'"] = formulaTest s, p, o, expect
| true | ###
# nodeunit tests for term.js
###
$rdf = require '../term.js'
tests =
statement: [{
s: new $rdf.Symbol("http://example.com/btb")
p: new $rdf.Symbol("http://xmlns.com/foaf/0.1/name")
o: "PI:NAME:<NAME>END_PI"
expect: '<http://example.com/btb> <http://xmlns.com/foaf/0.1/name> "PI:NAME:<NAME>END_PI" .'
}]
formula: [{
s: new $rdf.Symbol("http://example.com/btb")
p: new $rdf.Symbol("http://xmlns.com/foaf/0.1/name")
o: "Builder"
expect: '{<http://example.com/btb> <http://xmlns.com/foaf/0.1/name> "Builder" .}'
},{
s: new $rdf.BlankNode()
p: new $rdf.Symbol("http://xmlns.com/foaf/0.1/firstname")
o: "PI:NAME:<NAME>END_PI"
expect: '{_:n0 <http://xmlns.com/foaf/0.1/firstname> "PI:NAME:<NAME>END_PI" .}'
},{
s: new $rdf.Symbol("http://example.com/btb")
p: new $rdf.Symbol("http://xmlns.com/foaf/0.1/lastname")
o: new $rdf.Literal("Builder", "en")
expect: '{<http://example.com/btb> <http://xmlns.com/foaf/0.1/lastname> "Builder"@en .}'
},{
s: new $rdf.Symbol("http://example.com/btb")
p: new $rdf.Symbol("http://example.org/vocab#shoeSize")
o: new $rdf.Literal("30", undefined, (new $rdf.Namespace("http://www.w3.org/2001/XMLSchema#"))('integer'))
expect: '{<http://example.com/btb> <http://example.org/vocab#shoeSize> "30"^^<http://www.w3.org/2001/XMLSchema#integer> .}'
}]
statementTest = (s, p, o, expect) ->
(test) ->
triple = new $rdf.Statement s, p, o, undefined
test.equal triple.toString(), expect
test.done()
formulaTest = (s, p, o, expect) ->
(test) ->
kb = new $rdf.Formula
kb.add s, p, o
test.equal kb.toNT(), expect
test.done()
module.exports =
Statement: {}
Formula: {}
for {s, p, o, expect} in tests.statement
module.exports.Statement["(#{s}, #{p}, #{o}) == '#{expect}'"] = statementTest s, p, o, expect
for {s, p, o, expect} in tests.formula
module.exports.Formula["(#{s}, #{p}, #{o}) == '#{expect}'"] = formulaTest s, p, o, expect
|
[
{
"context": "' '\n\n# Word wrap to given width.\n#\n# (c) Copyright James Padolsey\n# http://james.padolsey.com/javascript/wordwrap-f",
"end": 1859,
"score": 0.9998466372489929,
"start": 1845,
"tag": "NAME",
"value": "James Padolsey"
}
] | src/word.coffee | vesln/word | 3 | # Dependencies.
lingo = require 'lingo'
extend = require('super').merge
slug = require 'slug'
en = lingo.en
# The main namespace
module.exports = word = extend [{}, lingo]
# Strips slashes from a string.
word.stripSlashes = (str) ->
str = str.replace /\\'/g, '\''
str = str.replace /\\"/g, '"'
str = str.replace /\\0/g, '\0'
str = str.replace /\\\\/g, '\\'
# Strips quotes.
word.stripQuotes = (str) ->
str = str.replace /\'/g, ''
str = str.replace /\"/g, ''
# Converts quotes to entities.
word.quotesEntities = (str) ->
str = str.replace /\'/g, '''
str = str.replace /\"/g, '"'
# Returns random string with given length.
word.random = (length) ->
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
random = ''
i = 0
while i < length
random += chars.charAt(Math.floor(Math.random() * chars.length))
i++
random
# Repeats word n times.
word.repeat = (str, times) ->
new Array(times + 1).join(str)
# Censors given words.
word.censor = (str, bad, replace) ->
bad = [bad] if not Array.isArray bad
for text in bad
regExp = new RegExp('\\b' + text + '\\b', 'g')
str = str.replace regExp, replace
str
# Strips links from string.
word.stripLinks = (str) ->
str = str.replace /<a\s+[^>]+>/im, ''
str = str.replace /<\/a>/im, ''
# Converts url addresses to clickable links.
word.autoLink = (str) ->
str.replace /((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g, '<a href="$1">$1</a>'
# Extracts an excerpt from string
word.excerpt = (str, length, ending = '...') ->
return str if str.length <= length
str.substring(0, length) + ending
# Limits text to n words.
word.limit = (str, count) ->
words = str.split /\s+/g
return str if words.length <= count
words.slice(0, count).join ' '
# Word wrap to given width.
#
# (c) Copyright James Padolsey
# http://james.padolsey.com/javascript/wordwrap-for-javascript/
word.wrap = (str, width, br = '\n', cut = false) ->
reg = '.{1,' + width + '}(\\s|$)'
if cut is true
reg += '|.{' + width + '}|.+$'
else
reg += '|\\S+?(\\s|$)'
str.match(new RegExp(reg, 'g')).join(br)
# Pluralizes a word if count is not 1.
word.pluralize = (count, singular, plural = null) ->
return singular if count == 1
plural = en.pluralize(singular) if not plural
plural
# Joins words
word.join = (words, last) ->
words = words.split /\s+/g if Array.isArray(words) is false
lingo.join words, last
# Converts string to slug
word.slug = slug
# Exporting version number.
module.exports.version = require('../package.json').version
| 96591 | # Dependencies.
lingo = require 'lingo'
extend = require('super').merge
slug = require 'slug'
en = lingo.en
# The main namespace
module.exports = word = extend [{}, lingo]
# Strips slashes from a string.
word.stripSlashes = (str) ->
str = str.replace /\\'/g, '\''
str = str.replace /\\"/g, '"'
str = str.replace /\\0/g, '\0'
str = str.replace /\\\\/g, '\\'
# Strips quotes.
word.stripQuotes = (str) ->
str = str.replace /\'/g, ''
str = str.replace /\"/g, ''
# Converts quotes to entities.
word.quotesEntities = (str) ->
str = str.replace /\'/g, '''
str = str.replace /\"/g, '"'
# Returns random string with given length.
word.random = (length) ->
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
random = ''
i = 0
while i < length
random += chars.charAt(Math.floor(Math.random() * chars.length))
i++
random
# Repeats word n times.
word.repeat = (str, times) ->
new Array(times + 1).join(str)
# Censors given words.
word.censor = (str, bad, replace) ->
bad = [bad] if not Array.isArray bad
for text in bad
regExp = new RegExp('\\b' + text + '\\b', 'g')
str = str.replace regExp, replace
str
# Strips links from string.
word.stripLinks = (str) ->
str = str.replace /<a\s+[^>]+>/im, ''
str = str.replace /<\/a>/im, ''
# Converts url addresses to clickable links.
word.autoLink = (str) ->
str.replace /((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g, '<a href="$1">$1</a>'
# Extracts an excerpt from string
word.excerpt = (str, length, ending = '...') ->
return str if str.length <= length
str.substring(0, length) + ending
# Limits text to n words.
word.limit = (str, count) ->
words = str.split /\s+/g
return str if words.length <= count
words.slice(0, count).join ' '
# Word wrap to given width.
#
# (c) Copyright <NAME>
# http://james.padolsey.com/javascript/wordwrap-for-javascript/
word.wrap = (str, width, br = '\n', cut = false) ->
reg = '.{1,' + width + '}(\\s|$)'
if cut is true
reg += '|.{' + width + '}|.+$'
else
reg += '|\\S+?(\\s|$)'
str.match(new RegExp(reg, 'g')).join(br)
# Pluralizes a word if count is not 1.
word.pluralize = (count, singular, plural = null) ->
return singular if count == 1
plural = en.pluralize(singular) if not plural
plural
# Joins words
word.join = (words, last) ->
words = words.split /\s+/g if Array.isArray(words) is false
lingo.join words, last
# Converts string to slug
word.slug = slug
# Exporting version number.
module.exports.version = require('../package.json').version
| true | # Dependencies.
lingo = require 'lingo'
extend = require('super').merge
slug = require 'slug'
en = lingo.en
# The main namespace
module.exports = word = extend [{}, lingo]
# Strips slashes from a string.
word.stripSlashes = (str) ->
str = str.replace /\\'/g, '\''
str = str.replace /\\"/g, '"'
str = str.replace /\\0/g, '\0'
str = str.replace /\\\\/g, '\\'
# Strips quotes.
word.stripQuotes = (str) ->
str = str.replace /\'/g, ''
str = str.replace /\"/g, ''
# Converts quotes to entities.
word.quotesEntities = (str) ->
str = str.replace /\'/g, '''
str = str.replace /\"/g, '"'
# Returns random string with given length.
word.random = (length) ->
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
random = ''
i = 0
while i < length
random += chars.charAt(Math.floor(Math.random() * chars.length))
i++
random
# Repeats word n times.
word.repeat = (str, times) ->
new Array(times + 1).join(str)
# Censors given words.
word.censor = (str, bad, replace) ->
bad = [bad] if not Array.isArray bad
for text in bad
regExp = new RegExp('\\b' + text + '\\b', 'g')
str = str.replace regExp, replace
str
# Strips links from string.
word.stripLinks = (str) ->
str = str.replace /<a\s+[^>]+>/im, ''
str = str.replace /<\/a>/im, ''
# Converts url addresses to clickable links.
word.autoLink = (str) ->
str.replace /((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g, '<a href="$1">$1</a>'
# Extracts an excerpt from string
word.excerpt = (str, length, ending = '...') ->
return str if str.length <= length
str.substring(0, length) + ending
# Limits text to n words.
word.limit = (str, count) ->
words = str.split /\s+/g
return str if words.length <= count
words.slice(0, count).join ' '
# Word wrap to given width.
#
# (c) Copyright PI:NAME:<NAME>END_PI
# http://james.padolsey.com/javascript/wordwrap-for-javascript/
word.wrap = (str, width, br = '\n', cut = false) ->
reg = '.{1,' + width + '}(\\s|$)'
if cut is true
reg += '|.{' + width + '}|.+$'
else
reg += '|\\S+?(\\s|$)'
str.match(new RegExp(reg, 'g')).join(br)
# Pluralizes a word if count is not 1.
word.pluralize = (count, singular, plural = null) ->
return singular if count == 1
plural = en.pluralize(singular) if not plural
plural
# Joins words
word.join = (words, last) ->
words = words.split /\s+/g if Array.isArray(words) is false
lingo.join words, last
# Converts string to slug
word.slug = slug
# Exporting version number.
module.exports.version = require('../package.json').version
|
[
{
"context": "# IP Address Widget\n# Vidur Murali, 2017\n# \n\n# ------------------------------ CONFIG",
"end": 34,
"score": 0.9998887181282043,
"start": 22,
"tag": "NAME",
"value": "Vidur Murali"
}
] | ip-address.widget/index.coffee | vyder/uebersicht-widgets | 0 | # IP Address Widget
# Vidur Murali, 2017
#
# ------------------------------ CONFIG ------------------------------
# milliseconds
refreshFrequency: 10 * 1000
# ---------------------------- END CONFIG ----------------------------
command: "ip-address.widget/get_ip"
get_local_ip: (cb) ->
@run("ifconfig | grep inet | grep broadcast | cut -d' ' -f2", cb)
render: (output) -> """
<span id="local_toggle" class="hidden">
LOCAL <span id="local"></span> EXT
</span>
<span id="ext"></span>
"""
update: (output) ->
$('#ext').text output.slice(0, -1)
$('#ext').click ->
$('#local_toggle').toggleClass 'hidden'
@get_local_ip (err, ip) ->
$('#local').text ip.slice(0, -1)
style: """
bottom 10px
right 390px
font-family 'San Francisco Display'
font-weight 500
font-size 9pt
font-smooth always
color #B7BCBE
#local, #ext
font-size 14pt
font-family 'Ubuntu Mono'
#local
padding-right 10px
.hidden
display none
"""
| 161545 | # IP Address Widget
# <NAME>, 2017
#
# ------------------------------ CONFIG ------------------------------
# milliseconds
refreshFrequency: 10 * 1000
# ---------------------------- END CONFIG ----------------------------
command: "ip-address.widget/get_ip"
get_local_ip: (cb) ->
@run("ifconfig | grep inet | grep broadcast | cut -d' ' -f2", cb)
render: (output) -> """
<span id="local_toggle" class="hidden">
LOCAL <span id="local"></span> EXT
</span>
<span id="ext"></span>
"""
update: (output) ->
$('#ext').text output.slice(0, -1)
$('#ext').click ->
$('#local_toggle').toggleClass 'hidden'
@get_local_ip (err, ip) ->
$('#local').text ip.slice(0, -1)
style: """
bottom 10px
right 390px
font-family 'San Francisco Display'
font-weight 500
font-size 9pt
font-smooth always
color #B7BCBE
#local, #ext
font-size 14pt
font-family 'Ubuntu Mono'
#local
padding-right 10px
.hidden
display none
"""
| true | # IP Address Widget
# PI:NAME:<NAME>END_PI, 2017
#
# ------------------------------ CONFIG ------------------------------
# milliseconds
refreshFrequency: 10 * 1000
# ---------------------------- END CONFIG ----------------------------
command: "ip-address.widget/get_ip"
get_local_ip: (cb) ->
@run("ifconfig | grep inet | grep broadcast | cut -d' ' -f2", cb)
render: (output) -> """
<span id="local_toggle" class="hidden">
LOCAL <span id="local"></span> EXT
</span>
<span id="ext"></span>
"""
update: (output) ->
$('#ext').text output.slice(0, -1)
$('#ext').click ->
$('#local_toggle').toggleClass 'hidden'
@get_local_ip (err, ip) ->
$('#local').text ip.slice(0, -1)
style: """
bottom 10px
right 390px
font-family 'San Francisco Display'
font-weight 500
font-size 9pt
font-smooth always
color #B7BCBE
#local, #ext
font-size 14pt
font-family 'Ubuntu Mono'
#local
padding-right 10px
.hidden
display none
"""
|
[
{
"context": "\n if password then options.password = \"****\"\n log.debug options\n if pas",
"end": 1938,
"score": 0.6874740123748779,
"start": 1938,
"tag": "PASSWORD",
"value": ""
},
{
"context": "ns\n if password then options.password = p... | server/imap/pool.coffee | cozy-labs/emails | 58 | errors = require '../utils/errors'
{AccountConfigError, TimeoutError, PasswordEncryptedError} = errors
log = require('../utils/logging')(prefix: 'imap:pool')
rawImapLog = require('../utils/logging')(prefix: 'imap:raw')
Account = require '../models/account'
Imap = require './connection'
xoauth2 = require 'xoauth2'
async = require "async"
accountConfigTools = require '../imap/account2config'
{makeIMAPConfig, forceOauthRefresh, forceAccountFetch} = accountConfigTools
Scheduler = require '../processes/_scheduler'
RecoverChangedUIDValidity = require '../processes/recover_change_uidvalidity'
connectionID = 1
module.exports = class ImapPool
constructor: (account) ->
log.debug @id, "new pool Object##{account.id}"
@id = account.id or 'tmp'
@account = account
@parallelism = 1
@tasks = [] # tasks waiting to be processed
@pending = {} # tasks being processed
@failConnectionCounter = 0
@connecting = 0
@connections = [] # all connections
@freeConnections = [] # connections not in use
destroy: ->
log.debug @id, "destroy"
clearTimeout @closingTimer if @closingTimer
@_closeConnections()
_removeFromPool: (connection) ->
log.debug @id, "remove #{connection.connectionID} from pool"
index = @connections.indexOf connection
@connections.splice index, 1 if index > -1
index = @freeConnections.indexOf connection
@freeConnections.splice index, 1
_makeConnection: ->
log.debug @id, "makeConnection"
@connecting++
makeIMAPConfig @account, (err, options) =>
log.error "oauth generation error", err if err
return @_onConnectionError connectionName: '', err if err
log.debug "Attempting connection"
password = options.password
if password then options.password = "****"
log.debug options
if password then options.password = password
imap = new Imap options
onConnError = @_onConnectionError.bind this, imap
imap.connectionID = 'conn' + connectionID++
imap.connectionName = "#{options.host}:#{options.port}"
imap.on 'error', onConnError
imap.once 'ready', =>
imap.removeListener 'error', onConnError
clearTimeout @wrongPortTimeout
@_onConnectionSuccess imap
imap.connect()
# timeout when wrong port is too high
# bring it to 10s
@wrongPortTimeout = setTimeout =>
log.debug @id, "timeout 10s"
imap.removeListener 'error', onConnError
onConnError new TimeoutError "Timeout connecting to " +
"#{@account?.imapServer}:#{@account?.imapPort}"
imap.destroy()
, 10000
_onConnectionError: (connection, err) ->
log.debug @id, "connection error on #{connection.connectionName}"
log.debug "RAW ERROR", err
# we failed to establish a new connection
clearTimeout @wrongPortTimeout
@connecting--
@failConnectionCounter++
isAuth = err.textCode is 'AUTHENTICATIONFAILED'
if err instanceof PasswordEncryptedError
@_giveUp err
else if @failConnectionCounter > 2
# give up
@_giveUp _typeConnectionError err
else if err.source is 'autentification' and
@account.oauthProvider is 'GMAIL'
# refresh accessToken
forceOauthRefresh @account, @_deQueue
# TMP : this should be removed when data-system#161 is widely deployed
else if isAuth and @account.id and @failConnectionCounter is 1
forceAccountFetch @account, @_deQueue
else
# try again in 5s
setTimeout @_deQueue, 5000
_onConnectionSuccess: (connection) ->
log.debug @id, "connection success"
connection.once 'close', @_onActiveClose.bind this, connection
connection.once 'error', @_onActiveError.bind this, connection
@connections.push connection
@freeConnections.push connection
@connecting--
@failConnectionCounter = 0
process.nextTick @_deQueue
_onActiveError: (connection, err) ->
name = connection.connectionName
log.error "error on active imap socket on #{name}", err
@_removeFromPool connection
try connection.destroy()
_onActiveClose: (connection, err) ->
log.error "active connection #{connection.connectionName} closed", err
task = @pending[connection.connectionID]
if task
delete @pending[connection.connectionID]
task.callback? err or new Error 'connection was closed'
task.callback = null
@_removeFromPool connection
_closeConnections: =>
log.debug @id, "closeConnections"
@closingTimer = null
connection = @connections.pop()
while connection
connection.expectedClosing = true
connection.end()
connection = @connections.pop()
@freeConnections = []
_giveUp: (err) ->
log.debug @id, "giveup", err
task = @tasks.pop()
while task
task.callback err
task = @tasks.pop()
_deQueue: =>
free = @freeConnections.length > 0
full = @connections.length + @connecting >= @parallelism
moreTasks = @tasks.length > 0
if @account.isTest()
# log.debug @id, "_deQueue/test"
if moreTasks
task = @tasks.pop()
task.callback? null
process.nextTick @_deQueue
return
if moreTasks
if @closingTimer
# log.debug @id, "_deQueue/stopTimer"
clearTimeout @closingTimer
if free
# log.debug @id, "_deQueue/free"
imap = @freeConnections.pop()
task = @tasks.pop()
@pending[imap.connectionID] = task
task.operation imap, (err) =>
args = (arg for arg in arguments)
@freeConnections.push imap
delete @pending[imap.connectionID]
# prevent imap catching callback errors
process.nextTick ->
task.callback?.apply null, args
task.callback = null
process.nextTick @_deQueue
else if not full
# log.debug @id, "_deQueue/notfull"
@_makeConnection()
# else queue is full, just wait
else
# log.debug @id, "_deQueue/startTimer"
@closingTimer ?= setTimeout @_closeConnections, 5000
_typeConnectionError = (err) ->
# if the know the type of error, clean it up for the user
typed = err
if err.textCode is 'AUTHENTICATIONFAILED'
typed = new AccountConfigError 'auth', err
if err.code is 'ENOTFOUND' and err.syscall is 'getaddrinfo'
typed = new AccountConfigError 'imapServer', err
if err.code is 'EHOSTUNREACH'
typed = new AccountConfigError 'imapServer', err
if err.source is 'timeout-auth'
# @TODO : this can happen for other reason,
# we need to retry before throwing
typed = new AccountConfigError 'imapTLS', err
if err instanceof TimeoutError
typed = new AccountConfigError 'imapPort', err
return typed
_wrapOpenBox: (cozybox, operation) ->
return wrapped = (imap, callback) =>
# log.debug @id, "begin wrapped task"
imap.openBox cozybox.path, (err, imapbox) =>
# log.debug @id, "wrapped box opened", err
return callback err if err
unless imapbox.persistentUIDs
return callback new Error 'UNPERSISTENT UID'
# check the uidvalidity
oldUidvalidity = cozybox.uidvalidity
newUidvalidity = imapbox.uidvalidity
if oldUidvalidity and oldUidvalidity isnt newUidvalidity
log.error "uidvalidity has changed"
recover = new RecoverChangedUIDValidity
newUidvalidity: newUidvalidity
mailbox: cozybox
imap: imap
recover.run (err) ->
log.error err if err
wrapped imap, callback
else
# perform the wrapped operation
operation imap, imapbox, (err, arg1, arg2, arg3) =>
log.debug @id, "wrapped operation completed"
return callback err if err
# store the uid validity
unless oldUidvalidity
changes = uidvalidity: newUidvalidity
cozybox.updateAttributes changes, (err) ->
return callback err if err
callback null, arg1, arg2, arg3
else
callback null, arg1, arg2, arg3
doASAP: (operation, callback) ->
@tasks.unshift {operation, callback}
@_deQueue()
doLater: (operation, callback) ->
@tasks.push {operation, callback}
@_deQueue()
doASAPWithBox: (cozybox, operation, callback) ->
operation = @_wrapOpenBox cozybox, operation
@tasks.unshift {operation, callback}
@_deQueue()
doLaterWithBox: (cozybox, operation, callback) ->
operation = @_wrapOpenBox cozybox, operation
@tasks.push {operation, callback}
@_deQueue()
| 18214 | errors = require '../utils/errors'
{AccountConfigError, TimeoutError, PasswordEncryptedError} = errors
log = require('../utils/logging')(prefix: 'imap:pool')
rawImapLog = require('../utils/logging')(prefix: 'imap:raw')
Account = require '../models/account'
Imap = require './connection'
xoauth2 = require 'xoauth2'
async = require "async"
accountConfigTools = require '../imap/account2config'
{makeIMAPConfig, forceOauthRefresh, forceAccountFetch} = accountConfigTools
Scheduler = require '../processes/_scheduler'
RecoverChangedUIDValidity = require '../processes/recover_change_uidvalidity'
connectionID = 1
module.exports = class ImapPool
constructor: (account) ->
log.debug @id, "new pool Object##{account.id}"
@id = account.id or 'tmp'
@account = account
@parallelism = 1
@tasks = [] # tasks waiting to be processed
@pending = {} # tasks being processed
@failConnectionCounter = 0
@connecting = 0
@connections = [] # all connections
@freeConnections = [] # connections not in use
destroy: ->
log.debug @id, "destroy"
clearTimeout @closingTimer if @closingTimer
@_closeConnections()
_removeFromPool: (connection) ->
log.debug @id, "remove #{connection.connectionID} from pool"
index = @connections.indexOf connection
@connections.splice index, 1 if index > -1
index = @freeConnections.indexOf connection
@freeConnections.splice index, 1
_makeConnection: ->
log.debug @id, "makeConnection"
@connecting++
makeIMAPConfig @account, (err, options) =>
log.error "oauth generation error", err if err
return @_onConnectionError connectionName: '', err if err
log.debug "Attempting connection"
password = options.password
if password then options.password = "<PASSWORD>****"
log.debug options
if password then options.password = <PASSWORD>
imap = new Imap options
onConnError = @_onConnectionError.bind this, imap
imap.connectionID = 'conn' + connectionID++
imap.connectionName = "#{options.host}:#{options.port}"
imap.on 'error', onConnError
imap.once 'ready', =>
imap.removeListener 'error', onConnError
clearTimeout @wrongPortTimeout
@_onConnectionSuccess imap
imap.connect()
# timeout when wrong port is too high
# bring it to 10s
@wrongPortTimeout = setTimeout =>
log.debug @id, "timeout 10s"
imap.removeListener 'error', onConnError
onConnError new TimeoutError "Timeout connecting to " +
"#{@account?.imapServer}:#{@account?.imapPort}"
imap.destroy()
, 10000
_onConnectionError: (connection, err) ->
log.debug @id, "connection error on #{connection.connectionName}"
log.debug "RAW ERROR", err
# we failed to establish a new connection
clearTimeout @wrongPortTimeout
@connecting--
@failConnectionCounter++
isAuth = err.textCode is 'AUTHENTICATIONFAILED'
if err instanceof PasswordEncryptedError
@_giveUp err
else if @failConnectionCounter > 2
# give up
@_giveUp _typeConnectionError err
else if err.source is 'autentification' and
@account.oauthProvider is 'GMAIL'
# refresh accessToken
forceOauthRefresh @account, @_deQueue
# TMP : this should be removed when data-system#161 is widely deployed
else if isAuth and @account.id and @failConnectionCounter is 1
forceAccountFetch @account, @_deQueue
else
# try again in 5s
setTimeout @_deQueue, 5000
_onConnectionSuccess: (connection) ->
log.debug @id, "connection success"
connection.once 'close', @_onActiveClose.bind this, connection
connection.once 'error', @_onActiveError.bind this, connection
@connections.push connection
@freeConnections.push connection
@connecting--
@failConnectionCounter = 0
process.nextTick @_deQueue
_onActiveError: (connection, err) ->
name = connection.connectionName
log.error "error on active imap socket on #{name}", err
@_removeFromPool connection
try connection.destroy()
_onActiveClose: (connection, err) ->
log.error "active connection #{connection.connectionName} closed", err
task = @pending[connection.connectionID]
if task
delete @pending[connection.connectionID]
task.callback? err or new Error 'connection was closed'
task.callback = null
@_removeFromPool connection
_closeConnections: =>
log.debug @id, "closeConnections"
@closingTimer = null
connection = @connections.pop()
while connection
connection.expectedClosing = true
connection.end()
connection = @connections.pop()
@freeConnections = []
_giveUp: (err) ->
log.debug @id, "giveup", err
task = @tasks.pop()
while task
task.callback err
task = @tasks.pop()
_deQueue: =>
free = @freeConnections.length > 0
full = @connections.length + @connecting >= @parallelism
moreTasks = @tasks.length > 0
if @account.isTest()
# log.debug @id, "_deQueue/test"
if moreTasks
task = @tasks.pop()
task.callback? null
process.nextTick @_deQueue
return
if moreTasks
if @closingTimer
# log.debug @id, "_deQueue/stopTimer"
clearTimeout @closingTimer
if free
# log.debug @id, "_deQueue/free"
imap = @freeConnections.pop()
task = @tasks.pop()
@pending[imap.connectionID] = task
task.operation imap, (err) =>
args = (arg for arg in arguments)
@freeConnections.push imap
delete @pending[imap.connectionID]
# prevent imap catching callback errors
process.nextTick ->
task.callback?.apply null, args
task.callback = null
process.nextTick @_deQueue
else if not full
# log.debug @id, "_deQueue/notfull"
@_makeConnection()
# else queue is full, just wait
else
# log.debug @id, "_deQueue/startTimer"
@closingTimer ?= setTimeout @_closeConnections, 5000
_typeConnectionError = (err) ->
# if the know the type of error, clean it up for the user
typed = err
if err.textCode is 'AUTHENTICATIONFAILED'
typed = new AccountConfigError 'auth', err
if err.code is 'ENOTFOUND' and err.syscall is 'getaddrinfo'
typed = new AccountConfigError 'imapServer', err
if err.code is 'EHOSTUNREACH'
typed = new AccountConfigError 'imapServer', err
if err.source is 'timeout-auth'
# @TODO : this can happen for other reason,
# we need to retry before throwing
typed = new AccountConfigError 'imapTLS', err
if err instanceof TimeoutError
typed = new AccountConfigError 'imapPort', err
return typed
_wrapOpenBox: (cozybox, operation) ->
return wrapped = (imap, callback) =>
# log.debug @id, "begin wrapped task"
imap.openBox cozybox.path, (err, imapbox) =>
# log.debug @id, "wrapped box opened", err
return callback err if err
unless imapbox.persistentUIDs
return callback new Error 'UNPERSISTENT UID'
# check the uidvalidity
oldUidvalidity = cozybox.uidvalidity
newUidvalidity = imapbox.uidvalidity
if oldUidvalidity and oldUidvalidity isnt newUidvalidity
log.error "uidvalidity has changed"
recover = new RecoverChangedUIDValidity
newUidvalidity: newUidvalidity
mailbox: cozybox
imap: imap
recover.run (err) ->
log.error err if err
wrapped imap, callback
else
# perform the wrapped operation
operation imap, imapbox, (err, arg1, arg2, arg3) =>
log.debug @id, "wrapped operation completed"
return callback err if err
# store the uid validity
unless oldUidvalidity
changes = uidvalidity: newUidvalidity
cozybox.updateAttributes changes, (err) ->
return callback err if err
callback null, arg1, arg2, arg3
else
callback null, arg1, arg2, arg3
doASAP: (operation, callback) ->
@tasks.unshift {operation, callback}
@_deQueue()
doLater: (operation, callback) ->
@tasks.push {operation, callback}
@_deQueue()
doASAPWithBox: (cozybox, operation, callback) ->
operation = @_wrapOpenBox cozybox, operation
@tasks.unshift {operation, callback}
@_deQueue()
doLaterWithBox: (cozybox, operation, callback) ->
operation = @_wrapOpenBox cozybox, operation
@tasks.push {operation, callback}
@_deQueue()
| true | errors = require '../utils/errors'
{AccountConfigError, TimeoutError, PasswordEncryptedError} = errors
log = require('../utils/logging')(prefix: 'imap:pool')
rawImapLog = require('../utils/logging')(prefix: 'imap:raw')
Account = require '../models/account'
Imap = require './connection'
xoauth2 = require 'xoauth2'
async = require "async"
accountConfigTools = require '../imap/account2config'
{makeIMAPConfig, forceOauthRefresh, forceAccountFetch} = accountConfigTools
Scheduler = require '../processes/_scheduler'
RecoverChangedUIDValidity = require '../processes/recover_change_uidvalidity'
connectionID = 1
module.exports = class ImapPool
constructor: (account) ->
log.debug @id, "new pool Object##{account.id}"
@id = account.id or 'tmp'
@account = account
@parallelism = 1
@tasks = [] # tasks waiting to be processed
@pending = {} # tasks being processed
@failConnectionCounter = 0
@connecting = 0
@connections = [] # all connections
@freeConnections = [] # connections not in use
destroy: ->
log.debug @id, "destroy"
clearTimeout @closingTimer if @closingTimer
@_closeConnections()
_removeFromPool: (connection) ->
log.debug @id, "remove #{connection.connectionID} from pool"
index = @connections.indexOf connection
@connections.splice index, 1 if index > -1
index = @freeConnections.indexOf connection
@freeConnections.splice index, 1
_makeConnection: ->
log.debug @id, "makeConnection"
@connecting++
makeIMAPConfig @account, (err, options) =>
log.error "oauth generation error", err if err
return @_onConnectionError connectionName: '', err if err
log.debug "Attempting connection"
password = options.password
if password then options.password = "PI:PASSWORD:<PASSWORD>END_PI****"
log.debug options
if password then options.password = PI:PASSWORD:<PASSWORD>END_PI
imap = new Imap options
onConnError = @_onConnectionError.bind this, imap
imap.connectionID = 'conn' + connectionID++
imap.connectionName = "#{options.host}:#{options.port}"
imap.on 'error', onConnError
imap.once 'ready', =>
imap.removeListener 'error', onConnError
clearTimeout @wrongPortTimeout
@_onConnectionSuccess imap
imap.connect()
# timeout when wrong port is too high
# bring it to 10s
@wrongPortTimeout = setTimeout =>
log.debug @id, "timeout 10s"
imap.removeListener 'error', onConnError
onConnError new TimeoutError "Timeout connecting to " +
"#{@account?.imapServer}:#{@account?.imapPort}"
imap.destroy()
, 10000
_onConnectionError: (connection, err) ->
log.debug @id, "connection error on #{connection.connectionName}"
log.debug "RAW ERROR", err
# we failed to establish a new connection
clearTimeout @wrongPortTimeout
@connecting--
@failConnectionCounter++
isAuth = err.textCode is 'AUTHENTICATIONFAILED'
if err instanceof PasswordEncryptedError
@_giveUp err
else if @failConnectionCounter > 2
# give up
@_giveUp _typeConnectionError err
else if err.source is 'autentification' and
@account.oauthProvider is 'GMAIL'
# refresh accessToken
forceOauthRefresh @account, @_deQueue
# TMP : this should be removed when data-system#161 is widely deployed
else if isAuth and @account.id and @failConnectionCounter is 1
forceAccountFetch @account, @_deQueue
else
# try again in 5s
setTimeout @_deQueue, 5000
_onConnectionSuccess: (connection) ->
log.debug @id, "connection success"
connection.once 'close', @_onActiveClose.bind this, connection
connection.once 'error', @_onActiveError.bind this, connection
@connections.push connection
@freeConnections.push connection
@connecting--
@failConnectionCounter = 0
process.nextTick @_deQueue
_onActiveError: (connection, err) ->
name = connection.connectionName
log.error "error on active imap socket on #{name}", err
@_removeFromPool connection
try connection.destroy()
_onActiveClose: (connection, err) ->
log.error "active connection #{connection.connectionName} closed", err
task = @pending[connection.connectionID]
if task
delete @pending[connection.connectionID]
task.callback? err or new Error 'connection was closed'
task.callback = null
@_removeFromPool connection
_closeConnections: =>
log.debug @id, "closeConnections"
@closingTimer = null
connection = @connections.pop()
while connection
connection.expectedClosing = true
connection.end()
connection = @connections.pop()
@freeConnections = []
_giveUp: (err) ->
log.debug @id, "giveup", err
task = @tasks.pop()
while task
task.callback err
task = @tasks.pop()
_deQueue: =>
free = @freeConnections.length > 0
full = @connections.length + @connecting >= @parallelism
moreTasks = @tasks.length > 0
if @account.isTest()
# log.debug @id, "_deQueue/test"
if moreTasks
task = @tasks.pop()
task.callback? null
process.nextTick @_deQueue
return
if moreTasks
if @closingTimer
# log.debug @id, "_deQueue/stopTimer"
clearTimeout @closingTimer
if free
# log.debug @id, "_deQueue/free"
imap = @freeConnections.pop()
task = @tasks.pop()
@pending[imap.connectionID] = task
task.operation imap, (err) =>
args = (arg for arg in arguments)
@freeConnections.push imap
delete @pending[imap.connectionID]
# prevent imap catching callback errors
process.nextTick ->
task.callback?.apply null, args
task.callback = null
process.nextTick @_deQueue
else if not full
# log.debug @id, "_deQueue/notfull"
@_makeConnection()
# else queue is full, just wait
else
# log.debug @id, "_deQueue/startTimer"
@closingTimer ?= setTimeout @_closeConnections, 5000
_typeConnectionError = (err) ->
# if the know the type of error, clean it up for the user
typed = err
if err.textCode is 'AUTHENTICATIONFAILED'
typed = new AccountConfigError 'auth', err
if err.code is 'ENOTFOUND' and err.syscall is 'getaddrinfo'
typed = new AccountConfigError 'imapServer', err
if err.code is 'EHOSTUNREACH'
typed = new AccountConfigError 'imapServer', err
if err.source is 'timeout-auth'
# @TODO : this can happen for other reason,
# we need to retry before throwing
typed = new AccountConfigError 'imapTLS', err
if err instanceof TimeoutError
typed = new AccountConfigError 'imapPort', err
return typed
_wrapOpenBox: (cozybox, operation) ->
return wrapped = (imap, callback) =>
# log.debug @id, "begin wrapped task"
imap.openBox cozybox.path, (err, imapbox) =>
# log.debug @id, "wrapped box opened", err
return callback err if err
unless imapbox.persistentUIDs
return callback new Error 'UNPERSISTENT UID'
# check the uidvalidity
oldUidvalidity = cozybox.uidvalidity
newUidvalidity = imapbox.uidvalidity
if oldUidvalidity and oldUidvalidity isnt newUidvalidity
log.error "uidvalidity has changed"
recover = new RecoverChangedUIDValidity
newUidvalidity: newUidvalidity
mailbox: cozybox
imap: imap
recover.run (err) ->
log.error err if err
wrapped imap, callback
else
# perform the wrapped operation
operation imap, imapbox, (err, arg1, arg2, arg3) =>
log.debug @id, "wrapped operation completed"
return callback err if err
# store the uid validity
unless oldUidvalidity
changes = uidvalidity: newUidvalidity
cozybox.updateAttributes changes, (err) ->
return callback err if err
callback null, arg1, arg2, arg3
else
callback null, arg1, arg2, arg3
doASAP: (operation, callback) ->
@tasks.unshift {operation, callback}
@_deQueue()
doLater: (operation, callback) ->
@tasks.push {operation, callback}
@_deQueue()
doASAPWithBox: (cozybox, operation, callback) ->
operation = @_wrapOpenBox cozybox, operation
@tasks.unshift {operation, callback}
@_deQueue()
doLaterWithBox: (cozybox, operation, callback) ->
operation = @_wrapOpenBox cozybox, operation
@tasks.push {operation, callback}
@_deQueue()
|
[
{
"context": "key: 'password', type: 'password' }\n { key: 'confirm_password', type: 'password' }\n { type: 'subm",
"end": 839,
"score": 0.5033683776855469,
"start": 832,
"tag": "PASSWORD",
"value": "confirm"
}
] | app/assets/javascripts/controllers/users/edit_password.coffee | ryanzhou/coledger | 1 | angular.module("coledger").controller("EditPasswordController", ['$scope', '$location', '$window', 'Resources', 'flash',
($scope, $location, $window, Resources, flash) ->
$scope.user = Resources.User.get(id: "current")
$scope.schema =
type: 'object'
title: 'User'
properties:
current_password:
title: 'Current Password'
type: 'string'
minLength: 6
required: true
password:
title: 'New Password'
type: 'string'
minLength: 6
required: true
confirm_password:
title: 'Repeat New Password'
type: 'string'
minLength: 6
required: true
$scope.form = [
{ key: 'current_password', type: 'password' }
{ key: 'password', type: 'password' }
{ key: 'confirm_password', type: 'password' }
{ type: 'submit', style: 'btn btn-primary', title: 'Update Password' }]
$scope.$watch("user.current_password", (value) ->
if (!value)
#Form possibly set to pristine, ignore
return
else
$scope.$broadcast('schemaForm.error.current_password', 'incorrect', true)
)
$scope.$watch("user.confirm_password", (value) ->
if (!value)
#Form possibly set to pristine, ignore
return
else if (value != $scope.user.password)
$scope.$broadcast('schemaForm.error.confirm_password', 'matchPassword', "Passwords must match")
else
$scope.$broadcast('schemaForm.error.confirm_password', 'matchPassword', true)
)
$scope.submitForm = (form) ->
$scope.$broadcast("schemaFormValidate")
if (form.$valid)
Resources.User.update(id: "current", $scope.user, (success) ->
flash.success = "You have successfully updated your password!"
$scope.user = {}
form.$setPristine()
$scope.$parent.refreshUser()
, (failure) ->
if failure.data.error_code == "VALIDATION_ERROR"
$scope.errorMessages = failure.data.errors
)
])
| 170406 | angular.module("coledger").controller("EditPasswordController", ['$scope', '$location', '$window', 'Resources', 'flash',
($scope, $location, $window, Resources, flash) ->
$scope.user = Resources.User.get(id: "current")
$scope.schema =
type: 'object'
title: 'User'
properties:
current_password:
title: 'Current Password'
type: 'string'
minLength: 6
required: true
password:
title: 'New Password'
type: 'string'
minLength: 6
required: true
confirm_password:
title: 'Repeat New Password'
type: 'string'
minLength: 6
required: true
$scope.form = [
{ key: 'current_password', type: 'password' }
{ key: 'password', type: 'password' }
{ key: '<PASSWORD>_password', type: 'password' }
{ type: 'submit', style: 'btn btn-primary', title: 'Update Password' }]
$scope.$watch("user.current_password", (value) ->
if (!value)
#Form possibly set to pristine, ignore
return
else
$scope.$broadcast('schemaForm.error.current_password', 'incorrect', true)
)
$scope.$watch("user.confirm_password", (value) ->
if (!value)
#Form possibly set to pristine, ignore
return
else if (value != $scope.user.password)
$scope.$broadcast('schemaForm.error.confirm_password', 'matchPassword', "Passwords must match")
else
$scope.$broadcast('schemaForm.error.confirm_password', 'matchPassword', true)
)
$scope.submitForm = (form) ->
$scope.$broadcast("schemaFormValidate")
if (form.$valid)
Resources.User.update(id: "current", $scope.user, (success) ->
flash.success = "You have successfully updated your password!"
$scope.user = {}
form.$setPristine()
$scope.$parent.refreshUser()
, (failure) ->
if failure.data.error_code == "VALIDATION_ERROR"
$scope.errorMessages = failure.data.errors
)
])
| true | angular.module("coledger").controller("EditPasswordController", ['$scope', '$location', '$window', 'Resources', 'flash',
($scope, $location, $window, Resources, flash) ->
$scope.user = Resources.User.get(id: "current")
$scope.schema =
type: 'object'
title: 'User'
properties:
current_password:
title: 'Current Password'
type: 'string'
minLength: 6
required: true
password:
title: 'New Password'
type: 'string'
minLength: 6
required: true
confirm_password:
title: 'Repeat New Password'
type: 'string'
minLength: 6
required: true
$scope.form = [
{ key: 'current_password', type: 'password' }
{ key: 'password', type: 'password' }
{ key: 'PI:PASSWORD:<PASSWORD>END_PI_password', type: 'password' }
{ type: 'submit', style: 'btn btn-primary', title: 'Update Password' }]
$scope.$watch("user.current_password", (value) ->
if (!value)
#Form possibly set to pristine, ignore
return
else
$scope.$broadcast('schemaForm.error.current_password', 'incorrect', true)
)
$scope.$watch("user.confirm_password", (value) ->
if (!value)
#Form possibly set to pristine, ignore
return
else if (value != $scope.user.password)
$scope.$broadcast('schemaForm.error.confirm_password', 'matchPassword', "Passwords must match")
else
$scope.$broadcast('schemaForm.error.confirm_password', 'matchPassword', true)
)
$scope.submitForm = (form) ->
$scope.$broadcast("schemaFormValidate")
if (form.$valid)
Resources.User.update(id: "current", $scope.user, (success) ->
flash.success = "You have successfully updated your password!"
$scope.user = {}
form.$setPristine()
$scope.$parent.refreshUser()
, (failure) ->
if failure.data.error_code == "VALIDATION_ERROR"
$scope.errorMessages = failure.data.errors
)
])
|
[
{
"context": "js\n\n PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.",
"end": 197,
"score": 0.9998763203620911,
"start": 180,
"tag": "NAME",
"value": "Benjamin Blundell"
},
{
"context": " PXL.js\n ... | examples/plane.coffee | OniDaito/pxljs | 1 | ### ABOUT
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
Benjamin Blundell - ben@pxljs.com
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
###
init = () ->
@top_node = new PXL.Node()
# A basic Z/X aligned plane
plane = new PXL.Geometry.Plane(8,8)
@plane_node = new PXL.Node()
@plane_node.add plane
# A higher resolution flat plane
@flat_node = new PXL.Node()
flat_plane = new PXL.Geometry.PlaneFlat(128,128)
@flat_node.add(new PXL.Material.BasicColourMaterial(new PXL.Colour.RGB(1,0,0))).add(flat_plane)
@flat_node.matrix.translate(new PXL.Math.Vec3(0,-2.0,0))
# A Hexagon based plane
@hex_node = new PXL.Node()
hex_plane = new PXL.Geometry.PlaneHexagonFlat(12,12)
@hex_node.add(new PXL.Material.BasicColourMaterial(new PXL.Colour.RGB(0,1,0))).add(hex_plane)
@hex_node.matrix.translate(new PXL.Math.Vec3(0,2.0,0))
@top_node.add hex_node
@top_node.add plane_node
@top_node.add flat_node
camera = new PXL.Camera.MousePerspCamera(new PXL.Math.Vec3(0,2.0,20.0))
@top_node.add camera
got_texture = (texture) =>
material = new PXL.Material.TextureMaterial(texture)
@plane_node.add material
uber = new PXL.GL.UberShader(@top_node)
@top_node.add uber
# Example of setting the parameters
params =
min : GL.NEAREST
PXL.GL.textureFromURL("/textures/chessboard.png", got_texture, undefined, params)
GL.enable GL.DEPTH_TEST
draw = () ->
GL.clearColor(0.15, 0.15, 0.15, 1.0)
GL.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT)
@top_node.draw()
params =
canvas : 'webgl-canvas'
context : @
init : init
draw : draw
cgl = new PXL.App params
| 163299 | ### ABOUT
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
<NAME> - <EMAIL>
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
###
init = () ->
@top_node = new PXL.Node()
# A basic Z/X aligned plane
plane = new PXL.Geometry.Plane(8,8)
@plane_node = new PXL.Node()
@plane_node.add plane
# A higher resolution flat plane
@flat_node = new PXL.Node()
flat_plane = new PXL.Geometry.PlaneFlat(128,128)
@flat_node.add(new PXL.Material.BasicColourMaterial(new PXL.Colour.RGB(1,0,0))).add(flat_plane)
@flat_node.matrix.translate(new PXL.Math.Vec3(0,-2.0,0))
# A Hexagon based plane
@hex_node = new PXL.Node()
hex_plane = new PXL.Geometry.PlaneHexagonFlat(12,12)
@hex_node.add(new PXL.Material.BasicColourMaterial(new PXL.Colour.RGB(0,1,0))).add(hex_plane)
@hex_node.matrix.translate(new PXL.Math.Vec3(0,2.0,0))
@top_node.add hex_node
@top_node.add plane_node
@top_node.add flat_node
camera = new PXL.Camera.MousePerspCamera(new PXL.Math.Vec3(0,2.0,20.0))
@top_node.add camera
got_texture = (texture) =>
material = new PXL.Material.TextureMaterial(texture)
@plane_node.add material
uber = new PXL.GL.UberShader(@top_node)
@top_node.add uber
# Example of setting the parameters
params =
min : GL.NEAREST
PXL.GL.textureFromURL("/textures/chessboard.png", got_texture, undefined, params)
GL.enable GL.DEPTH_TEST
draw = () ->
GL.clearColor(0.15, 0.15, 0.15, 1.0)
GL.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT)
@top_node.draw()
params =
canvas : 'webgl-canvas'
context : @
init : init
draw : draw
cgl = new PXL.App params
| true | ### ABOUT
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
PI:NAME:<NAME>END_PI - PI:EMAIL:<EMAIL>END_PI
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
###
init = () ->
@top_node = new PXL.Node()
# A basic Z/X aligned plane
plane = new PXL.Geometry.Plane(8,8)
@plane_node = new PXL.Node()
@plane_node.add plane
# A higher resolution flat plane
@flat_node = new PXL.Node()
flat_plane = new PXL.Geometry.PlaneFlat(128,128)
@flat_node.add(new PXL.Material.BasicColourMaterial(new PXL.Colour.RGB(1,0,0))).add(flat_plane)
@flat_node.matrix.translate(new PXL.Math.Vec3(0,-2.0,0))
# A Hexagon based plane
@hex_node = new PXL.Node()
hex_plane = new PXL.Geometry.PlaneHexagonFlat(12,12)
@hex_node.add(new PXL.Material.BasicColourMaterial(new PXL.Colour.RGB(0,1,0))).add(hex_plane)
@hex_node.matrix.translate(new PXL.Math.Vec3(0,2.0,0))
@top_node.add hex_node
@top_node.add plane_node
@top_node.add flat_node
camera = new PXL.Camera.MousePerspCamera(new PXL.Math.Vec3(0,2.0,20.0))
@top_node.add camera
got_texture = (texture) =>
material = new PXL.Material.TextureMaterial(texture)
@plane_node.add material
uber = new PXL.GL.UberShader(@top_node)
@top_node.add uber
# Example of setting the parameters
params =
min : GL.NEAREST
PXL.GL.textureFromURL("/textures/chessboard.png", got_texture, undefined, params)
GL.enable GL.DEPTH_TEST
draw = () ->
GL.clearColor(0.15, 0.15, 0.15, 1.0)
GL.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT)
@top_node.draw()
params =
canvas : 'webgl-canvas'
context : @
init : init
draw : draw
cgl = new PXL.App params
|
[
{
"context": "submit'\n\n render: ->\n data =\n password: 'password' in @model.get('loginTypes')\n\n @$el.html(@temp",
"end": 208,
"score": 0.999494194984436,
"start": 200,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "data = _.extend @model.toJSON(),\n pas... | app/views/account.coffee | micirclek/cki-portal | 0 | AppView = require('views/appview')
PopoverView = require('views/popover')
class ChangePasswordView extends PopoverView
events:
'submit form': 'submit'
render: ->
data =
password: 'password' in @model.get('loginTypes')
@$el.html(@template('change_password', data))
return @
submit: ->
oldPass = @$('#old-password')?.val?() ? ''
newPass = @$('#new-password').val()
newPass2 = @$('#new-password-again').val()
if newPass != newPass2
Util.showAlert('Passwords do not match')
return false
@model.setPassword(oldPass, newPass)
.then =>
Util.showAlert('Password changed', 'alert-success')
@close()
.catch =>
return
.done()
return false
close: ->
@parent.closeSetPassword()
class EditProfileView extends PopoverView
events:
'submit form': 'submit'
render: ->
@$el.html(@template('edit_profile', @model.toJSON()))
return @
submit: ->
name = @$('#name').val() ? ''
@model.save({ name })
.then =>
@close()
.catch =>
return
.done()
return false
close: ->
@parent.closeEditProfile()
class AccountView extends AppView
events:
'click .js-set-password': 'openSetPassword'
'click .js-edit-profile': 'openEditProfile'
initialize: ->
@changePassword = new ChangePasswordView({ @model, parent: @ })
@editProfile = new EditProfileView({ @model, parent: @ })
@listenTo @model,
'change:loginTypes change:name': @render
super
render: ->
data = _.extend @model.toJSON(),
password: 'password' in @model.get('loginTypes')
@$el.html(@template('account', data))
title = if data.password
'Change Password'
else
'Set Password'
@$('.js-set-password').popover
html: true
title: title
content: @changePassword.render().el
trigger: 'manual'
.popover('hide')
@$('.js-edit-profile').popover
html: true
title: 'Edit Profile'
content: @editProfile.render().el
trigger: 'manual'
.popover('hide')
return @
openSetPassword: ->
if !@changePassword.visible
@changePassword.render()
@$('.js-set-password').popover('show')
@changePassword.delegateEvents()
@changePassword.visible = true
return false
closeSetPassword: ->
@changePassword.visible = false
@changePassword.undelegateEvents()
@$('.js-set-password').popover('hide')
openEditProfile: ->
if !@editProfile.visible
@editProfile.render()
@$('.js-edit-profile').popover('show')
@editProfile.delegateEvents()
@editProfile.visible = true
return false
closeEditProfile: ->
@editProfile.visible = false
@editProfile.undelegateEvents()
@$('.js-edit-profile').popover('hide')
module.exports = AccountView
| 187565 | AppView = require('views/appview')
PopoverView = require('views/popover')
class ChangePasswordView extends PopoverView
events:
'submit form': 'submit'
render: ->
data =
password: '<PASSWORD>' in @model.get('loginTypes')
@$el.html(@template('change_password', data))
return @
submit: ->
oldPass = @$('#old-password')?.val?() ? ''
newPass = @$('#new-password').val()
newPass2 = @$('#new-password-again').val()
if newPass != newPass2
Util.showAlert('Passwords do not match')
return false
@model.setPassword(oldPass, newPass)
.then =>
Util.showAlert('Password changed', 'alert-success')
@close()
.catch =>
return
.done()
return false
close: ->
@parent.closeSetPassword()
class EditProfileView extends PopoverView
events:
'submit form': 'submit'
render: ->
@$el.html(@template('edit_profile', @model.toJSON()))
return @
submit: ->
name = @$('#name').val() ? ''
@model.save({ name })
.then =>
@close()
.catch =>
return
.done()
return false
close: ->
@parent.closeEditProfile()
class AccountView extends AppView
events:
'click .js-set-password': 'openSetPassword'
'click .js-edit-profile': 'openEditProfile'
initialize: ->
@changePassword = new ChangePasswordView({ @model, parent: @ })
@editProfile = new EditProfileView({ @model, parent: @ })
@listenTo @model,
'change:loginTypes change:name': @render
super
render: ->
data = _.extend @model.toJSON(),
password: '<PASSWORD>' in @model.get('loginTypes')
@$el.html(@template('account', data))
title = if data.password
'Change Password'
else
'Set Password'
@$('.js-set-password').popover
html: true
title: title
content: @changePassword.render().el
trigger: 'manual'
.popover('hide')
@$('.js-edit-profile').popover
html: true
title: 'Edit Profile'
content: @editProfile.render().el
trigger: 'manual'
.popover('hide')
return @
openSetPassword: ->
if !@changePassword.visible
@changePassword.render()
@$('.js-set-password').popover('show')
@changePassword.delegateEvents()
@changePassword.visible = true
return false
closeSetPassword: ->
@changePassword.visible = false
@changePassword.undelegateEvents()
@$('.js-set-password').popover('hide')
openEditProfile: ->
if !@editProfile.visible
@editProfile.render()
@$('.js-edit-profile').popover('show')
@editProfile.delegateEvents()
@editProfile.visible = true
return false
closeEditProfile: ->
@editProfile.visible = false
@editProfile.undelegateEvents()
@$('.js-edit-profile').popover('hide')
module.exports = AccountView
| true | AppView = require('views/appview')
PopoverView = require('views/popover')
class ChangePasswordView extends PopoverView
events:
'submit form': 'submit'
render: ->
data =
password: 'PI:PASSWORD:<PASSWORD>END_PI' in @model.get('loginTypes')
@$el.html(@template('change_password', data))
return @
submit: ->
oldPass = @$('#old-password')?.val?() ? ''
newPass = @$('#new-password').val()
newPass2 = @$('#new-password-again').val()
if newPass != newPass2
Util.showAlert('Passwords do not match')
return false
@model.setPassword(oldPass, newPass)
.then =>
Util.showAlert('Password changed', 'alert-success')
@close()
.catch =>
return
.done()
return false
close: ->
@parent.closeSetPassword()
class EditProfileView extends PopoverView
events:
'submit form': 'submit'
render: ->
@$el.html(@template('edit_profile', @model.toJSON()))
return @
submit: ->
name = @$('#name').val() ? ''
@model.save({ name })
.then =>
@close()
.catch =>
return
.done()
return false
close: ->
@parent.closeEditProfile()
class AccountView extends AppView
events:
'click .js-set-password': 'openSetPassword'
'click .js-edit-profile': 'openEditProfile'
initialize: ->
@changePassword = new ChangePasswordView({ @model, parent: @ })
@editProfile = new EditProfileView({ @model, parent: @ })
@listenTo @model,
'change:loginTypes change:name': @render
super
render: ->
data = _.extend @model.toJSON(),
password: 'PI:PASSWORD:<PASSWORD>END_PI' in @model.get('loginTypes')
@$el.html(@template('account', data))
title = if data.password
'Change Password'
else
'Set Password'
@$('.js-set-password').popover
html: true
title: title
content: @changePassword.render().el
trigger: 'manual'
.popover('hide')
@$('.js-edit-profile').popover
html: true
title: 'Edit Profile'
content: @editProfile.render().el
trigger: 'manual'
.popover('hide')
return @
openSetPassword: ->
if !@changePassword.visible
@changePassword.render()
@$('.js-set-password').popover('show')
@changePassword.delegateEvents()
@changePassword.visible = true
return false
closeSetPassword: ->
@changePassword.visible = false
@changePassword.undelegateEvents()
@$('.js-set-password').popover('hide')
openEditProfile: ->
if !@editProfile.visible
@editProfile.render()
@$('.js-edit-profile').popover('show')
@editProfile.delegateEvents()
@editProfile.visible = true
return false
closeEditProfile: ->
@editProfile.visible = false
@editProfile.undelegateEvents()
@$('.js-edit-profile').popover('hide')
module.exports = AccountView
|
[
{
"context": " no idea\n#\n# Notes:\n# No idea...\n#\n# Author:\n# Brian Shumate <brian@couchbase.com>\n\nnoidea = \"http://i.imgur.c",
"end": 210,
"score": 0.9998841285705566,
"start": 197,
"tag": "NAME",
"value": "Brian Shumate"
},
{
"context": "es:\n# No idea...\n#\n# Author... | files/scripts/dogatcomputer.coffee | AAROC/the-boss-role | 0 | # Description:
# Displays a "I Have No Idea What I'm Doing" image
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot no idea
#
# Notes:
# No idea...
#
# Author:
# Brian Shumate <brian@couchbase.com>
noidea = "http://i.imgur.com/hmTeehN.jpg"
module.exports = (robot) ->
robot.hear /(dunno|I don\'t know|beats me|no idea)/i, (msg)->
r = Math.random()
if r <= 0.10
msg.send noidea
robot.respond /dunno|I don\'t know|beats me|no idea/i, (msg) ->
msg.send noidea
| 83421 | # Description:
# Displays a "I Have No Idea What I'm Doing" image
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot no idea
#
# Notes:
# No idea...
#
# Author:
# <NAME> <<EMAIL>>
noidea = "http://i.imgur.com/hmTeehN.jpg"
module.exports = (robot) ->
robot.hear /(dunno|I don\'t know|beats me|no idea)/i, (msg)->
r = Math.random()
if r <= 0.10
msg.send noidea
robot.respond /dunno|I don\'t know|beats me|no idea/i, (msg) ->
msg.send noidea
| true | # Description:
# Displays a "I Have No Idea What I'm Doing" image
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot no idea
#
# Notes:
# No idea...
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
noidea = "http://i.imgur.com/hmTeehN.jpg"
module.exports = (robot) ->
robot.hear /(dunno|I don\'t know|beats me|no idea)/i, (msg)->
r = Math.random()
if r <= 0.10
msg.send noidea
robot.respond /dunno|I don\'t know|beats me|no idea/i, (msg) ->
msg.send noidea
|
[
{
"context": "##\n knockback.js 1.2.3\n Copyright (c) 2011-2016 Kevin Malakoff.\n License: MIT (http://www.opensource.org/licens",
"end": 66,
"score": 0.9997802376747131,
"start": 52,
"tag": "NAME",
"value": "Kevin Malakoff"
},
{
"context": "ses/mit-license.php)\n Source: https:... | src/core/functions/collapse_options.coffee | kmalakoff/knockback | 160 | ###
knockback.js 1.2.3
Copyright (c) 2011-2016 Kevin Malakoff.
License: MIT (http://www.opensource.org/licenses/mit-license.php)
Source: https://github.com/kmalakoff/knockback
Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js).
Optional dependencies: Backbone.ModelRef.js and BackboneORM.
###
{_} = require '../kb'
# @nodoc
_mergeArray = (result, key, value) ->
result[key] or= []
value = [value] unless _.isArray(value)
result[key] = if result[key].length then _.union(result[key], value) else value
return result
# @nodoc
_mergeObject = (result, key, value) -> result[key] or= {}; return _.extend(result[key], value)
# @nodoc
_keyArrayToObject = (value) -> result = {}; result[item] = {key: item} for item in value; return result
_mergeOptions = (result, options) ->
return result unless options
for key, value of options
switch key
when 'internals', 'requires', 'excludes', 'statics' then _mergeArray(result, key, value)
when 'keys'
# an object
if (_.isObject(value) and not _.isArray(value)) or (_.isObject(result[key]) and not _.isArray(result[key]))
value = [value] unless _.isObject(value)
value = _keyArrayToObject(value) if _.isArray(value)
result[key] = _keyArrayToObject(result[key]) if _.isArray(result[key])
_mergeObject(result, key, value)
# an array
else
_mergeArray(result, key, value)
when 'factories'
if _.isFunction(value) then result[key] = value else _mergeObject(result, key, value)
when 'static_defaults' then _mergeObject(result, key, value)
when 'options' then
else
result[key] = value
return _mergeOptions(result, options.options)
# @nodoc
module.exports = (options) -> _mergeOptions({}, options)
| 55433 | ###
knockback.js 1.2.3
Copyright (c) 2011-2016 <NAME>.
License: MIT (http://www.opensource.org/licenses/mit-license.php)
Source: https://github.com/kmalakoff/knockback
Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js).
Optional dependencies: Backbone.ModelRef.js and BackboneORM.
###
{_} = require '../kb'
# @nodoc
_mergeArray = (result, key, value) ->
result[key] or= []
value = [value] unless _.isArray(value)
result[key] = if result[key].length then _.union(result[key], value) else value
return result
# @nodoc
_mergeObject = (result, key, value) -> result[key] or= {}; return _.extend(result[key], value)
# @nodoc
_keyArrayToObject = (value) -> result = {}; result[item] = {key: item} for item in value; return result
_mergeOptions = (result, options) ->
return result unless options
for key, value of options
switch key
when 'internals', 'requires', 'excludes', 'statics' then _mergeArray(result, key, value)
when 'keys'
# an object
if (_.isObject(value) and not _.isArray(value)) or (_.isObject(result[key]) and not _.isArray(result[key]))
value = [value] unless _.isObject(value)
value = _keyArrayToObject(value) if _.isArray(value)
result[key] = _keyArrayToObject(result[key]) if _.isArray(result[key])
_mergeObject(result, key, value)
# an array
else
_mergeArray(result, key, value)
when 'factories'
if _.isFunction(value) then result[key] = value else _mergeObject(result, key, value)
when 'static_defaults' then _mergeObject(result, key, value)
when 'options' then
else
result[key] = value
return _mergeOptions(result, options.options)
# @nodoc
module.exports = (options) -> _mergeOptions({}, options)
| true | ###
knockback.js 1.2.3
Copyright (c) 2011-2016 PI:NAME:<NAME>END_PI.
License: MIT (http://www.opensource.org/licenses/mit-license.php)
Source: https://github.com/kmalakoff/knockback
Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js).
Optional dependencies: Backbone.ModelRef.js and BackboneORM.
###
{_} = require '../kb'
# @nodoc
_mergeArray = (result, key, value) ->
result[key] or= []
value = [value] unless _.isArray(value)
result[key] = if result[key].length then _.union(result[key], value) else value
return result
# @nodoc
_mergeObject = (result, key, value) -> result[key] or= {}; return _.extend(result[key], value)
# @nodoc
_keyArrayToObject = (value) -> result = {}; result[item] = {key: item} for item in value; return result
_mergeOptions = (result, options) ->
return result unless options
for key, value of options
switch key
when 'internals', 'requires', 'excludes', 'statics' then _mergeArray(result, key, value)
when 'keys'
# an object
if (_.isObject(value) and not _.isArray(value)) or (_.isObject(result[key]) and not _.isArray(result[key]))
value = [value] unless _.isObject(value)
value = _keyArrayToObject(value) if _.isArray(value)
result[key] = _keyArrayToObject(result[key]) if _.isArray(result[key])
_mergeObject(result, key, value)
# an array
else
_mergeArray(result, key, value)
when 'factories'
if _.isFunction(value) then result[key] = value else _mergeObject(result, key, value)
when 'static_defaults' then _mergeObject(result, key, value)
when 'options' then
else
result[key] = value
return _mergeOptions(result, options.options)
# @nodoc
module.exports = (options) -> _mergeOptions({}, options)
|
[
{
"context": "BOT_MINECRAFT_USERNAME\n password = process.env.HUBOT_MINECRAFT_PASSWORD\n\n bot = new Client(port, host, username, passw",
"end": 634,
"score": 0.8495400547981262,
"start": 610,
"tag": "PASSWORD",
"value": "HUBOT_MINECRAFT_PASSWORD"
}
] | src/minecraft.coffee | sittiaminah/hubot-minecraft | 161 | Adapter = require('hubot').adapter()
Robot = require('hubot').robot()
Parser = require('./parser').Parser
Packet = require('./packet').Packet
Client = require('./client').Client
class Minecraft extends Adapter
send: (user, strings...) ->
strings.forEach (str) => @bot.say(str)
reply: (user, strings...) ->
strings.map((str) -> "#{user.name}: #{str}").forEach (str) =>
@bot.say(str)
run: ->
self = @
port = parseInt(process.env.HUBOT_MINECRAFT_PORT, 10)
host = process.env.HUBOT_MINECRAFT_HOST
username = process.env.HUBOT_MINECRAFT_USERNAME
password = process.env.HUBOT_MINECRAFT_PASSWORD
bot = new Client(port, host, username, password)
@bot = bot
# Hack to get around NPM loading in multiple copies of Robot and instanceof failing to match up.
r = @robot.constructor
bot.on 'end', -> process.exit()
bot.on 'chat', (str) ->
userChatMatch = str.match(/^<(\w{1,16})>\s(.*)$/)
if userChatMatch?
[_, username, msg] = userChatMatch
user = self.userForId(username)
self.receive new r.TextMessage(user, msg)
joinedMatch = str.match(/^§e(\w{1,16}) joined the game.$/)
if joinedMatch?
user = self.userForId(joinedMatch[1])
self.receive(new r.EnterMessage(user))
leftMatch = str.match(/^§e(\w{1,16}) left the game.$/)
if leftMatch?
user = self.userForId(leftMatch[1])
self.receive(new r.LeaveMessage(user))
userForUsername: (username) ->
@userForName(username) or new User(username)
exports.use = (robot) ->
new Minecraft robot
| 107498 | Adapter = require('hubot').adapter()
Robot = require('hubot').robot()
Parser = require('./parser').Parser
Packet = require('./packet').Packet
Client = require('./client').Client
class Minecraft extends Adapter
send: (user, strings...) ->
strings.forEach (str) => @bot.say(str)
reply: (user, strings...) ->
strings.map((str) -> "#{user.name}: #{str}").forEach (str) =>
@bot.say(str)
run: ->
self = @
port = parseInt(process.env.HUBOT_MINECRAFT_PORT, 10)
host = process.env.HUBOT_MINECRAFT_HOST
username = process.env.HUBOT_MINECRAFT_USERNAME
password = process.env.<PASSWORD>
bot = new Client(port, host, username, password)
@bot = bot
# Hack to get around NPM loading in multiple copies of Robot and instanceof failing to match up.
r = @robot.constructor
bot.on 'end', -> process.exit()
bot.on 'chat', (str) ->
userChatMatch = str.match(/^<(\w{1,16})>\s(.*)$/)
if userChatMatch?
[_, username, msg] = userChatMatch
user = self.userForId(username)
self.receive new r.TextMessage(user, msg)
joinedMatch = str.match(/^§e(\w{1,16}) joined the game.$/)
if joinedMatch?
user = self.userForId(joinedMatch[1])
self.receive(new r.EnterMessage(user))
leftMatch = str.match(/^§e(\w{1,16}) left the game.$/)
if leftMatch?
user = self.userForId(leftMatch[1])
self.receive(new r.LeaveMessage(user))
userForUsername: (username) ->
@userForName(username) or new User(username)
exports.use = (robot) ->
new Minecraft robot
| true | Adapter = require('hubot').adapter()
Robot = require('hubot').robot()
Parser = require('./parser').Parser
Packet = require('./packet').Packet
Client = require('./client').Client
class Minecraft extends Adapter
send: (user, strings...) ->
strings.forEach (str) => @bot.say(str)
reply: (user, strings...) ->
strings.map((str) -> "#{user.name}: #{str}").forEach (str) =>
@bot.say(str)
run: ->
self = @
port = parseInt(process.env.HUBOT_MINECRAFT_PORT, 10)
host = process.env.HUBOT_MINECRAFT_HOST
username = process.env.HUBOT_MINECRAFT_USERNAME
password = process.env.PI:PASSWORD:<PASSWORD>END_PI
bot = new Client(port, host, username, password)
@bot = bot
# Hack to get around NPM loading in multiple copies of Robot and instanceof failing to match up.
r = @robot.constructor
bot.on 'end', -> process.exit()
bot.on 'chat', (str) ->
userChatMatch = str.match(/^<(\w{1,16})>\s(.*)$/)
if userChatMatch?
[_, username, msg] = userChatMatch
user = self.userForId(username)
self.receive new r.TextMessage(user, msg)
joinedMatch = str.match(/^§e(\w{1,16}) joined the game.$/)
if joinedMatch?
user = self.userForId(joinedMatch[1])
self.receive(new r.EnterMessage(user))
leftMatch = str.match(/^§e(\w{1,16}) left the game.$/)
if leftMatch?
user = self.userForId(leftMatch[1])
self.receive(new r.LeaveMessage(user))
userForUsername: (username) ->
@userForName(username) or new User(username)
exports.use = (robot) ->
new Minecraft robot
|
[
{
"context": "ittle Mocha Reference ========\nhttps://github.com/visionmedia/should.js\nhttps://github.com/visionmedia/mocha\n##",
"end": 235,
"score": 0.9992910623550415,
"start": 224,
"tag": "USERNAME",
"value": "visionmedia"
},
{
"context": "thub.com/visionmedia/should.js\nhttps:/... | nodejs/flarebyte.net/0.8/node/magma/node_modules/magma-user/test/magma-user_test.coffee | flarebyte/wonderful-bazar | 0 | 'use strict'
magma_user = require('magma-user')
should = require('should')
CT = require('magma-constant')
_ = require('lodash')
util = require('util')
###
======== A Handy Little Mocha Reference ========
https://github.com/visionmedia/should.js
https://github.com/visionmedia/mocha
###
validUser =
additionalName: "Pierre"
addressCountry: "gb"
addressLocality: "london"
contactType: "business"
familyName: "Baudelaire"
#gateId: CT.EX_GATE_ID
gender: CT.GENDER_MALE
givenName: "Charles"
honorificPrefix: "Mr"
honorificSuffix: "Phd"
id: CT.EX_USER_ID
jobTitle: "Software engineer"
languages: "en"
organization: "Flarebyte.com"
organizationUnit: "creative unit"
profileRef: CT.EX_EMAIL_U1
roles: [CT.EX_ROLE_ID]
skills: []
summary: "special summary"
websites: ["http://flarebyte.com","http://flarebyte.com/b"]
yearOfBirth: "1921"
validUser1 = _.cloneDeep(validUser)
validUser1.profileRef= CT.EX_EMAIL_U1
validUser1.givenName= "Charles"
validUser2 = _.cloneDeep(validUser)
validUser2.profileRef= CT.EX_EMAIL_U2
validUser2.givenName= "CharlesII"
validUser3 = _.cloneDeep(validUser)
validUser3.profileRef= CT.EX_EMAIL_U3
validUser3.givenName= "CharlesIII"
myself=
ownerRef: CT.EX_OWNER_U1
gateId: CT.EX_GATE_ID
ownerRefs: [CT.EX_OWNER_U1,CT.EX_OWNER_U2]
userCtx=
my: myself
describe "magma-user", ->
describe 'pkGenerator()', ()->
it 'generate id', ()->
v= magma_user.pkGenerator(userCtx, validUser)
v.should.be.eql(
'magma:f/user/123456789/'+
'059315e79a4f75dba659e45aec49d4f2bcbf15dfb9efcf9e17aea950133c602c')
| 219242 | 'use strict'
magma_user = require('magma-user')
should = require('should')
CT = require('magma-constant')
_ = require('lodash')
util = require('util')
###
======== A Handy Little Mocha Reference ========
https://github.com/visionmedia/should.js
https://github.com/visionmedia/mocha
###
validUser =
additionalName: "<NAME>"
addressCountry: "gb"
addressLocality: "london"
contactType: "business"
familyName: "<NAME>"
#gateId: CT.EX_GATE_ID
gender: CT.GENDER_MALE
givenName: "<NAME>"
honorificPrefix: "Mr"
honorificSuffix: "Phd"
id: CT.EX_USER_ID
jobTitle: "Software engineer"
languages: "en"
organization: "Flarebyte.com"
organizationUnit: "creative unit"
profileRef: CT.EX_EMAIL_U1
roles: [CT.EX_ROLE_ID]
skills: []
summary: "special summary"
websites: ["http://flarebyte.com","http://flarebyte.com/b"]
yearOfBirth: "1921"
validUser1 = _.cloneDeep(validUser)
validUser1.profileRef= CT.EX_EMAIL_U1
validUser1.givenName= "<NAME>"
validUser2 = _.cloneDeep(validUser)
validUser2.profileRef= CT.EX_EMAIL_U2
validUser2.givenName= "<NAME>"
validUser3 = _.cloneDeep(validUser)
validUser3.profileRef= CT.EX_EMAIL_U3
validUser3.givenName= "<NAME>"
myself=
ownerRef: CT.EX_OWNER_U1
gateId: CT.EX_GATE_ID
ownerRefs: [CT.EX_OWNER_U1,CT.EX_OWNER_U2]
userCtx=
my: myself
describe "magma-user", ->
describe 'pkGenerator()', ()->
it 'generate id', ()->
v= magma_user.pkGenerator(userCtx, validUser)
v.should.be.eql(
'magma:f/user/123456789/'+
'059315e79a4f75dba659e45aec49d4f2bcbf15dfb9efcf9e17aea950133c602c')
| true | 'use strict'
magma_user = require('magma-user')
should = require('should')
CT = require('magma-constant')
_ = require('lodash')
util = require('util')
###
======== A Handy Little Mocha Reference ========
https://github.com/visionmedia/should.js
https://github.com/visionmedia/mocha
###
validUser =
additionalName: "PI:NAME:<NAME>END_PI"
addressCountry: "gb"
addressLocality: "london"
contactType: "business"
familyName: "PI:NAME:<NAME>END_PI"
#gateId: CT.EX_GATE_ID
gender: CT.GENDER_MALE
givenName: "PI:NAME:<NAME>END_PI"
honorificPrefix: "Mr"
honorificSuffix: "Phd"
id: CT.EX_USER_ID
jobTitle: "Software engineer"
languages: "en"
organization: "Flarebyte.com"
organizationUnit: "creative unit"
profileRef: CT.EX_EMAIL_U1
roles: [CT.EX_ROLE_ID]
skills: []
summary: "special summary"
websites: ["http://flarebyte.com","http://flarebyte.com/b"]
yearOfBirth: "1921"
validUser1 = _.cloneDeep(validUser)
validUser1.profileRef= CT.EX_EMAIL_U1
validUser1.givenName= "PI:NAME:<NAME>END_PI"
validUser2 = _.cloneDeep(validUser)
validUser2.profileRef= CT.EX_EMAIL_U2
validUser2.givenName= "PI:NAME:<NAME>END_PI"
validUser3 = _.cloneDeep(validUser)
validUser3.profileRef= CT.EX_EMAIL_U3
validUser3.givenName= "PI:NAME:<NAME>END_PI"
myself=
ownerRef: CT.EX_OWNER_U1
gateId: CT.EX_GATE_ID
ownerRefs: [CT.EX_OWNER_U1,CT.EX_OWNER_U2]
userCtx=
my: myself
describe "magma-user", ->
describe 'pkGenerator()', ()->
it 'generate id', ()->
v= magma_user.pkGenerator(userCtx, validUser)
v.should.be.eql(
'magma:f/user/123456789/'+
'059315e79a4f75dba659e45aec49d4f2bcbf15dfb9efcf9e17aea950133c602c')
|
[
{
"context": "ion', ->\n @req.query.reset_password_token = 'existy'\n routes.resetPassword @req, @res\n @res",
"end": 835,
"score": 0.9979457855224609,
"start": 829,
"tag": "PASSWORD",
"value": "existy"
},
{
"context": " @req.session.reset_password_token.should.equal ... | src/desktop/apps/auth/test/routes.coffee | kanaabe/force | 0 | _ = require 'underscore'
sinon = require 'sinon'
Backbone = require 'backbone'
rewire = require 'rewire'
routes = rewire '../routes'
describe 'Auth routes', ->
beforeEach ->
routes.__set__ 'request', del: @del = sinon.stub().returns(send: @send = sinon.stub().returns(end: (cb) -> cb()))
routes.__set__ 'sanitizeRedirect', (route) -> route
@req =
params: {}
body: {}
query: {}
session: {}
get: sinon.stub()
logout: sinon.stub()
user: new Backbone.Model accessToken: 'secret'
@res =
locals: sd: {}
redirect: sinon.stub()
render: sinon.stub()
send: sinon.stub()
@next = sinon.stub()
describe '#resetPassword', ->
it 'redirects to the reset password page; setting the token in the session', ->
@req.query.reset_password_token = 'existy'
routes.resetPassword @req, @res
@res.redirect.called.should.be.true()
@req.session.reset_password_token.should.equal 'existy'
@res.redirect.args[0][0].should.equal '/reset_password'
it 'renders the reset password page when there is no reset_password_token query param', ->
routes.resetPassword @req, @res
@res.render.args[0][0].should.equal 'reset_password'
describe '#twitterLastStep', ->
it 'renders the last step email page', ->
routes.twitterLastStep @req, @res
@res.render.args[0][0].should.equal 'twitter_email'
| 46717 | _ = require 'underscore'
sinon = require 'sinon'
Backbone = require 'backbone'
rewire = require 'rewire'
routes = rewire '../routes'
describe 'Auth routes', ->
beforeEach ->
routes.__set__ 'request', del: @del = sinon.stub().returns(send: @send = sinon.stub().returns(end: (cb) -> cb()))
routes.__set__ 'sanitizeRedirect', (route) -> route
@req =
params: {}
body: {}
query: {}
session: {}
get: sinon.stub()
logout: sinon.stub()
user: new Backbone.Model accessToken: 'secret'
@res =
locals: sd: {}
redirect: sinon.stub()
render: sinon.stub()
send: sinon.stub()
@next = sinon.stub()
describe '#resetPassword', ->
it 'redirects to the reset password page; setting the token in the session', ->
@req.query.reset_password_token = '<PASSWORD>'
routes.resetPassword @req, @res
@res.redirect.called.should.be.true()
@req.session.reset_password_token.should.equal '<PASSWORD>'
@res.redirect.args[0][0].should.equal '/reset_password'
it 'renders the reset password page when there is no reset_password_token query param', ->
routes.resetPassword @req, @res
@res.render.args[0][0].should.equal 'reset_password'
describe '#twitterLastStep', ->
it 'renders the last step email page', ->
routes.twitterLastStep @req, @res
@res.render.args[0][0].should.equal 'twitter_email'
| true | _ = require 'underscore'
sinon = require 'sinon'
Backbone = require 'backbone'
rewire = require 'rewire'
routes = rewire '../routes'
describe 'Auth routes', ->
beforeEach ->
routes.__set__ 'request', del: @del = sinon.stub().returns(send: @send = sinon.stub().returns(end: (cb) -> cb()))
routes.__set__ 'sanitizeRedirect', (route) -> route
@req =
params: {}
body: {}
query: {}
session: {}
get: sinon.stub()
logout: sinon.stub()
user: new Backbone.Model accessToken: 'secret'
@res =
locals: sd: {}
redirect: sinon.stub()
render: sinon.stub()
send: sinon.stub()
@next = sinon.stub()
describe '#resetPassword', ->
it 'redirects to the reset password page; setting the token in the session', ->
@req.query.reset_password_token = 'PI:PASSWORD:<PASSWORD>END_PI'
routes.resetPassword @req, @res
@res.redirect.called.should.be.true()
@req.session.reset_password_token.should.equal 'PI:PASSWORD:<PASSWORD>END_PI'
@res.redirect.args[0][0].should.equal '/reset_password'
it 'renders the reset password page when there is no reset_password_token query param', ->
routes.resetPassword @req, @res
@res.render.args[0][0].should.equal 'reset_password'
describe '#twitterLastStep', ->
it 'renders the last step email page', ->
routes.twitterLastStep @req, @res
@res.render.args[0][0].should.equal 'twitter_email'
|
[
{
"context": "\n\t\telse\n\t\t\topt.observeEach (time) !->\n\t\t\t\toptKey = oDay+'-'+time.key()\n\t\t\t\toptionsO.set optKey, true\n\t",
"end": 6331,
"score": 0.641789436340332,
"start": 6330,
"tag": "KEY",
"value": "o"
},
{
"context": "\n\t\t\topt.observeEach (time) !->\n\t\t\t\top... | client.coffee | Happening/Event | 0 | App = require 'app'
Comments = require 'comments'
Datepicker = require 'datepicker'
Db = require 'db'
Dom = require 'dom'
Event = require 'event'
Form = require 'form'
Icon = require 'icon'
Modal = require 'modal'
Obs = require 'obs'
Page = require 'page'
Server = require 'server'
Time = require 'time'
Ui = require 'ui'
{tr} = require 'i18n'
today = 0|(((new Date()).getTime() - (new Date()).getTimezoneOffset()*6e4) / 864e5)
attendanceTypes =
1: tr "Going"
2: tr "Maybe"
3: tr "Not going"
if Db.shared
shared = Db.shared.ref()
else
shared = Obs.create()
exports.render = !->
if shared.get('date')
renderEvent()
else
renderPlanner()
Comments.enable
messages:
remind: (c) ->
remind = shared.get('remind') || 0
if remind <= 0
tr("This event is happening right now!")
else if remind is 600
tr("This event is happening in 10 minutes")
else if remind is 3600
tr("This event is happening in 1 hour")
else if remind is 86400
tr("This event is happening in 1 day")
else if remind is 604800
tr("This event is happening in 1 week")
picked: (c) ->
whenText = (if (time = Db.shared.get('time'))? and time isnt -1 then Datepicker.timeToString(time)+' ' else '')
whenText += Datepicker.dayToString(Db.shared.get('date'))
"Event date picked: #{whenText} (#{App.title()})"
renderEvent = !->
Ui.top !->
Dom.cls 'top1'
Dom.style margin: 0
Dom.div !->
Dom.span !->
Dom.style fontSize: '160%', fontWeight: 'bold'
Dom.userText App.title()
Dom.div !->
append = ''
if duration = shared.get('duration')
append = ' - ' + Datepicker.timeToString(+shared.get('time')+duration)
Dom.text Datepicker.timeToString(shared.get('time'))+append
Dom.span !->
Dom.style padding: '0 4px'
Dom.text ' • '
Dom.text Datepicker.dayToString(shared.get('date'))
Dom.div !->
Dom.style
display: 'inline-block'
padding: '6px 8px'
fontSize: '75%'
color: '#fff'
marginTop: '8px'
textTransform: 'uppercase'
border: '1px solid #fff'
borderRadius: '2px'
Dom.text tr "Add to calendar"
Dom.onTap !->
if App.agent().android
beginTime = Datepicker.dayToDate(shared.get('date'))
time = Db.shared.get('time')
if time>=0
beginTime.setHours(Math.floor(time/3600))
beginTime.setMinutes(Math.floor((time%3600)/60))
beginTime.setSeconds(Math.floor(time%60))
description = Db.shared.get('details') || ''
intentOpts =
_action: "android.intent.action.INSERT"
_data: "content://com.android.calendar/events"
_activity: 0
allDay: time<0
beginTime: beginTime.getTime()
title: App.title()
description: description
availability: 0 # busy
if duration = Db.shared.get('duration')
intentOpts.endTime = beginTime.getTime() + duration * 1000
ok = App.intent intentOpts
else
App.openUrl App.inboundUrl()
Dom.div !->
Dom.style
fontSize: '75%'
color: '#ddd'
marginTop: '16px'
Dom.text tr("Added by %1", App.userName(shared.get('by')))
Dom.text " • "
Time.deltaText shared.get('created')
# details
if details = shared.get('details')
Form.label !->
Dom.text tr("Details")
Dom.div !->
Dom.userText details
# attendance info..
if shared.get('rsvp')
Form.label tr("Attendance")
Dom.div !->
attendance =
1: []
2: []
3: []
shared.forEach 'attendance', (user) !->
attendance[user.get()].push user.key()
userAtt = shared.get('attendance', App.userId())
for type in [1, 2, 3] then do (type) !->
chosen = userAtt is type
Dom.div !->
Dom.style Box: 'top', margin: '12px 0', fontSize: '85%'
Ui.button !->
Dom.style margin: 0, width: '70px', textAlign: 'center', border: '1px solid '+App.colors().highlight
if chosen
Dom.style backgroundColor: App.colors().highlight, color: '#fff'
else
Dom.style backgroundColor: 'transparent', color: App.colors().highlight
Dom.text attendanceTypes[type]
, !->
Server.sync 'attendance', (if chosen then 0 else type), !->
shared.set 'attendance', App.userId(), (if chosen then null else type)
Dom.div !->
Dom.style fontWeight: 'bold', padding: '6px 8px'
Dom.text ' (' + attendance[type].length + ')'
Dom.div !->
Dom.style Flex: 1, fontWeight: 'bold', padding: '6px 0'
for uid, k in attendance[type] then do (uid) !->
if k
Dom.span !->
Dom.style color: '#999'
Dom.text ', '
Dom.span !->
Dom.style
whiteSpace: 'nowrap'
color: (if App.userId() is +uid then 'inherit' else '#999')
padding: '2px 4px'
margin: '-2px -4px'
Dom.text App.userName(uid)
Dom.onTap (!-> App.showMemberInfo(uid))
renderPlanner = !->
getState = (optionId, userId) -> shared.get('answers', optionId, userId||App.userId()) || 0
renderIcon = (optionId, userId, edit, content) !->
Dom.div !->
Dom.style
Box: 'middle center'
padding: '10px'
minWidth: '29px'
minHeight: '29px'
margin: if edit then 0 else '-9px 0'
opacity: if edit then 1 else 0.3
Dom.img !->
icon = ['unknown', 'yes', 'no', 'maybe'][getState(optionId, userId)]
Dom.prop src: App.resourceUri("#{icon}.png")
Dom.style
maxWidth: '24px'
maxHeight: '24px'
width: 'auto'
verticalAlign: 'middle'
content?()
userId = App.userId()
Page.setCardBackground()
Ui.top !->
Dom.style backgroundColor: '#fff'
ownerId = App.ownerId()
Dom.div !->
Dom.style Box: true
Ui.avatar App.userAvatar(ownerId), onTap: !-> App.showMemberInfo(ownerId)
Dom.h1 !->
Dom.style Flex: 2, display: 'block', marginLeft: '10px'
Dom.text App.title()
Dom.div !->
Dom.style margin: '0 0 0 50px'
Dom.richText shared.get('details') || ''
Dom.div !->
Dom.style
fontSize: '70%'
color: '#aaa'
padding: '6px 0 0'
if ownerId
Dom.text App.userName(ownerId)
Dom.text " • "
Time.deltaText App.created()
# create a mapping from db to optionsO that uses 'day-time' keys
optionsO = Obs.create {}
shared.observeEach 'options', (opt) !->
oDay = 0|opt.key()
if !opt.ref().count().get()
optionsO.set oDay+'', {}
else
opt.observeEach (time) !->
optKey = oDay+'-'+time.key()
optionsO.set optKey, true
Obs.onClean !->
optionsO.remove optKey
Obs.onClean !->
optionsO.remove oDay
users = App.users.get()
expanded = Obs.create(Page.state.peek('exp'))
Ui.list !->
if !optionsO.count().get()
Ui.emptyText tr("No date options configured yet")
else
optionsO.observeEach (option) !->
optionId = option.key()
[day, time] = optionId.split('-')
dayName = Datepicker.dayToString(day, true)
if time
append = ''
if duration = shared.get('duration')
append = '-' + Datepicker.timeToString(+time+duration)
optionName = dayName + ' (' + Datepicker.timeToString(time) + append + ')'
else
optionName = dayName
Ui.item !->
Dom.style Box: 'middle', padding: 0
Dom.style borderBottom: 'none' if expanded.get(optionId)
Dom.div !->
Dom.style Box: 'middle', Flex: 1, padding: '8px'
Dom.div !->
cnt = 0
if answers = shared.get('answers', optionId)
for uid, answer of answers
if users[uid] and answer is 1
cnt++
Dom.style
Box: "middle center"
padding: '5px'
fontSize: '120%'
marginRight: '10px'
backgroundColor: '#ddd'
color: if cnt then 'black' else '#aaa'
borderRadius: '4px'
minWidth: '25px'
Dom.text cnt
Dom.div !->
Dom.style Flex: 1
Dom.div !->
Dom.style fontWeight: 'bold'
Dom.text optionName
Dom.br()
Dom.span !->
notesCnt = shared.ref('notes').count(optionId).get()
Dom.text if notesCnt then tr("%1 note|s", notesCnt) else tr("No notes")
Dom.style fontWeight: 'normal', fontSize: '80%', color: (if notesCnt then 'inherit' else '#aaa')
Dom.div !->
Dom.style color: '#aaa', margin: '0 5px', border: '8px solid transparent'
if expanded.get(optionId)
Dom.style borderBottom: '8px solid #ccc', marginTop: '-8px'
else
Dom.style borderTop: '8px solid #ccc', marginBottom: '-8px'
Dom.onTap !->
expanded.modify optionId, (v) -> if v then null else true
Page.state.set('exp', expanded.get())
if !expanded.get(optionId)
Form.vSep()
renderIcon optionId, userId, true, !->
Dom.onTap !->
state = (getState(optionId)+1)%4
Server.sync 'setState', optionId, state, !->
shared.set 'answers', optionId, userId, state
else
# to prevent a tap-highlight in this area
Dom.div !->
Dom.style width: '50px'
if expanded.get(optionId)
Ui.item !->
Dom.style Box: "right", padding: '0 0 8px 0'
Dom.span !->
Dom.style display: 'block', maxWidth: '20em'
App.users.observeEach (user) !->
isMine = +user.key() is +userId
Dom.span !->
Dom.style Box: "middle", margin: (if isMine then 0 else '4px 0'), textAlign: 'right'
Dom.div !->
Dom.style Flex: 1
if isMine
Dom.style padding: '5px'
else
Dom.style margin: '0 5px'
Dom.span !->
Dom.style fontWeight: 'bold'
Dom.text user.get('name')
note = shared.get('notes', optionId, user.key())
if isMine
Dom.text ': '
Dom.text note if note
Dom.span !->
Dom.style color: App.colors().highlight
Dom.text (if note then ' ' + tr "Edit" else tr "Add a note")
Dom.onTap !->
Form.prompt
title: tr('Note for %1', optionName)
value: note
cb: (note) !->
Server.sync 'setNote', optionId, note||null, !->
shared.set 'notes', optionId, userId, note||null
else if note
Dom.text ': '+note
Ui.avatar App.userAvatar(user.key()),
style: margin: '0 8px'
size: 24
onTap: !-> App.showMemberInfo(user.key())
renderIcon optionId, user.key(), isMine, if isMine then !->
Dom.onTap !->
state = (getState(optionId)+1)%4
Server.sync 'setState', optionId, state, !->
shared.set 'answers', optionId, userId, state
, (user) ->
if +user.key() is +userId
-1000
else
user.get('name')
if App.userIsAdmin() or App.ownerId() is App.userId()
Dom.div !->
Dom.style textAlign: 'right', paddingRight: '8px'
Ui.button tr("Pick date"), !->
Modal.confirm tr("Pick %1?", optionName), tr("Members will no longer be able to change their availability"), !->
Server.sync 'pickDate', optionId
, (option) -> # sort order
option.key()
renderEventSettings = !->
curDate = shared.get('date')||today
curTime = Obs.create(shared.get('time') || -1)
Dom.div !->
Dom.style Box: 'horizontal'
Form.box !->
Dom.style Flex: 1, paddingRight: '12px'
Dom.text tr("Event date")
[handleChange] = Form.makeInput
name: 'date'
value: curDate
content: (value) !->
Dom.div Datepicker.dayToString(value)
Dom.onTap !->
cur = null
Modal.confirm tr("Select date"), !->
cur = Datepicker.date
value: curDate
, !->
handleChange cur.get()
curDate = cur.get()
Form.vSep()
Form.box !->
Dom.style Flex: 1, paddingLeft: '12px'
Dom.text tr("Event time")
[handleChange] = Form.makeInput
name: 'time'
value: curTime.peek()
content: (value) !->
Dom.div Datepicker.timeToString(value)
Dom.onTap !->
val = (if curTime.peek()<0 then null else curTime.peek())
Modal.show tr("Enter time"), !->
Datepicker.time
value: val
onChange: (v) !->
val = v
, (choice) !->
return if choice is 'cancel'
newVal = (if choice is 'clear' then -1 else val)
handleChange newVal
curTime.set newVal
, ['cancel', tr("Cancel"), 'clear', tr("All day"), 'ok', tr("Set")]
renderDurationInput shared.get('duration')||0, curTime
Form.box !->
remind = shared.get('remind')
if !remind? then remind = 86400 # if 0 then it should remain 0
getRemindText = (r) ->
if r is -1
tr("No reminder")
else if r is 0
tr("At time of event")
else if r is 600
tr("10 minutes before")
else if r is 3600
tr("1 hour before")
else if r is 86400
tr("1 day before", r)
else if r is 604800
tr("1 week before", r)
Dom.text tr("Reminder")
[handleChange] = Form.makeInput
name: 'remind'
value: remind
content: (value) !->
Dom.div !->
Dom.text getRemindText(value)
Dom.onTap !->
Modal.show tr("Remind members"), !->
opts = [0, 600, 3600, 86400, 604800, -1]
for rem in opts then do (rem) !->
Ui.item !->
Dom.text getRemindText(rem)
if remind is rem
Dom.style fontWeight: 'bold'
Dom.div !->
Dom.style
Flex: 1
padding: '0 10px'
textAlign: 'right'
fontSize: '150%'
color: App.colors().highlight
Dom.text "✓"
Dom.onTap !->
handleChange rem
remind = rem
Modal.remove()
Obs.observe !->
ask = Obs.create(shared.get('rsvp') || true)
Form.check
name: 'rsvp'
value: shared.func('rsvp') || true
text: tr("Ask people if they're going")
onChange: (v) !->
ask.set(v)
renderPlannerSettings = !->
datesO = null # consists of { dayNr: true } entries, used by Datepicker.date
optionsO = Obs.create {} # consists of { dayNr: time: true } (or dayNr: {}) entries
# construct initial optionsO from db values
curDates = {}
for day, times of shared.get('options')
curDates[day] = true
optionsO.set day, {}
for t, v of times
(o = {})[t] = true
optionsO.merge day, o
Form.addObs 'options', optionsO
Dom.div !->
Dom.style Box: "center", marginTop: '12px', borderBottom: '1px solid #ddd'
datesO = Datepicker.date
mode: 'multi'
value: curDates
# map selected days to optionsO
Obs.observe !->
datesO.observeEach (entry) !->
eDay = entry.key()
optionsO.merge eDay, {}
Obs.onClean !->
optionsO.remove eDay
optionsCnt = Obs.create 0
Obs.observe !->
cnt = 0
for k, times of optionsO.get()
tCnt = 0
for x, y of times
tCnt++
tCnt = Math.max(tCnt, 1)
cnt += tCnt
optionsCnt.set cnt
lastTime = null
dayTimeOptions = (day) !->
addTimeOption = !->
Modal.show tr("Add time option"), !->
Datepicker.time
value: lastTime
onChange: (v) !->
lastTime = v
, (choice) !->
if choice is 'add' and lastTime
optionsO.set day, lastTime, true
showTimeOptions()
, ['cancel', tr("Cancel"), 'add', tr("Add")]
showTimeOptions = !->
Modal.show tr("Time options"), !->
optionsO.observeEach day, (timeOption) !->
Ui.item !->
Dom.div !->
Dom.style Flex: 1, fontSize: '125%', fontWeight: 'bold', paddingLeft: '4px'
Dom.text Datepicker.timeToString(timeOption.key())
Icon.render
data: 'cancelround'
size: 32
onTap: !->
optionsO.remove day, timeOption.key()
Ui.item !->
Dom.style color: App.colors().highlight, paddingLeft: '12px'
Dom.text tr('+ Add option')
Dom.onTap !->
Modal.remove()
addTimeOption()
if optionsO.ref(day).count().get()
# multiple time options
showTimeOptions()
else
# first time option
addTimeOption()
Obs.observe !->
optionsO.observeEach (entry) !->
oDay = entry.key()
Ui.item !->
Dom.style padding: 0
Dom.div !->
Dom.style Flex: 1, padding: '12px'
Dom.text Datepicker.dayToString(oDay)
Dom.div !->
Dom.style fontSize: '75%', color: '#aaa', marginTop: '3px'
ts = (Datepicker.timeToString(t) for t, v of entry.get())
if ts.length
Dom.text ts.join(' / ')
else
Dom.text tr("No time(s) specified")
Dom.onTap !->
dayTimeOptions oDay
Form.vSep()
Icon.render
data: 'cancel'
size: 24
style: padding: '18px'
onTap: !->
datesO.remove oDay # syncs to optionsO
, (entry) -> entry.key()
Form.condition ->
tr("A minimum of two options is required") if optionsCnt.peek()<2
Obs.observe !->
showDuration = false
for date, entry of optionsO.get() when !showDuration
for k, v of entry
showDuration = true # at least one time option defined
break
if !showDuration
return
renderDurationInput shared.get('duration')||0
Dom.div !->
Dom.style Box: 'center middle', textAlign: 'center', color: '#aaa', padding: '8px', fontSize: '85%'
oc = optionsCnt.get()
Dom.text (if !oc then tr("No dates selected yet") else tr("Poll will have %1 option|s", oc))
exports.renderSettings = !->
Form.input
name: '_title'
text: tr("Event name")
value: App.title()
Form.condition (val) ->
tr("An event name is required") if !val._title
Form.text
name: 'details'
text: tr "Details about the event"
autogrow: true
value: shared.func('details')
showPlanner = Obs.create (if shared.get('date') then false else true)
Obs.observe !->
if !Db.shared # only offer choice on install
Form.segmented
name: 'type'
value: 'announce'
segments: ['announce', tr("Fixed date"), 'plan', tr("Date poll")]
onChange: (v) !-> showPlanner.set(v is 'plan')
description: !->
Dom.text (if showPlanner.get() then tr("Asks people to vote for the best date") else tr("Enter date and time below"))
if !showPlanner.get()
# select date
renderEventSettings()
else
renderPlannerSettings()
renderDurationInput = (duration, timeO) !->
Form.box !->
allDay = if timeO? then timeO.get() is -1 else false
Dom.style color: if allDay then '#aaa' else ''
Dom.text tr("Duration")
if allDay
Dom.div tr("No event time specified")
else
[handleChange] = Form.makeInput
name: 'duration'
value: duration
onChange: (v) !->
duration = v
content: (value) !->
Dom.div !->
hours = Math.floor(value/3600)
mins = (value - hours*3600)/60
Dom.text if hours and mins
tr("%1 hour|s and %2 min|s", hours, mins)
else if hours
tr("%1 hour|s", hours)
else if mins
tr("%1 min|s", mins)
else
tr("Not specified")
Dom.onTap !->
Modal.show tr("Duration"), !->
Datepicker.time
value: duration
onChange: (v) !->
handleChange v
duration = v
| 70357 | App = require 'app'
Comments = require 'comments'
Datepicker = require 'datepicker'
Db = require 'db'
Dom = require 'dom'
Event = require 'event'
Form = require 'form'
Icon = require 'icon'
Modal = require 'modal'
Obs = require 'obs'
Page = require 'page'
Server = require 'server'
Time = require 'time'
Ui = require 'ui'
{tr} = require 'i18n'
today = 0|(((new Date()).getTime() - (new Date()).getTimezoneOffset()*6e4) / 864e5)
attendanceTypes =
1: tr "Going"
2: tr "Maybe"
3: tr "Not going"
if Db.shared
shared = Db.shared.ref()
else
shared = Obs.create()
exports.render = !->
if shared.get('date')
renderEvent()
else
renderPlanner()
Comments.enable
messages:
remind: (c) ->
remind = shared.get('remind') || 0
if remind <= 0
tr("This event is happening right now!")
else if remind is 600
tr("This event is happening in 10 minutes")
else if remind is 3600
tr("This event is happening in 1 hour")
else if remind is 86400
tr("This event is happening in 1 day")
else if remind is 604800
tr("This event is happening in 1 week")
picked: (c) ->
whenText = (if (time = Db.shared.get('time'))? and time isnt -1 then Datepicker.timeToString(time)+' ' else '')
whenText += Datepicker.dayToString(Db.shared.get('date'))
"Event date picked: #{whenText} (#{App.title()})"
renderEvent = !->
Ui.top !->
Dom.cls 'top1'
Dom.style margin: 0
Dom.div !->
Dom.span !->
Dom.style fontSize: '160%', fontWeight: 'bold'
Dom.userText App.title()
Dom.div !->
append = ''
if duration = shared.get('duration')
append = ' - ' + Datepicker.timeToString(+shared.get('time')+duration)
Dom.text Datepicker.timeToString(shared.get('time'))+append
Dom.span !->
Dom.style padding: '0 4px'
Dom.text ' • '
Dom.text Datepicker.dayToString(shared.get('date'))
Dom.div !->
Dom.style
display: 'inline-block'
padding: '6px 8px'
fontSize: '75%'
color: '#fff'
marginTop: '8px'
textTransform: 'uppercase'
border: '1px solid #fff'
borderRadius: '2px'
Dom.text tr "Add to calendar"
Dom.onTap !->
if App.agent().android
beginTime = Datepicker.dayToDate(shared.get('date'))
time = Db.shared.get('time')
if time>=0
beginTime.setHours(Math.floor(time/3600))
beginTime.setMinutes(Math.floor((time%3600)/60))
beginTime.setSeconds(Math.floor(time%60))
description = Db.shared.get('details') || ''
intentOpts =
_action: "android.intent.action.INSERT"
_data: "content://com.android.calendar/events"
_activity: 0
allDay: time<0
beginTime: beginTime.getTime()
title: App.title()
description: description
availability: 0 # busy
if duration = Db.shared.get('duration')
intentOpts.endTime = beginTime.getTime() + duration * 1000
ok = App.intent intentOpts
else
App.openUrl App.inboundUrl()
Dom.div !->
Dom.style
fontSize: '75%'
color: '#ddd'
marginTop: '16px'
Dom.text tr("Added by %1", App.userName(shared.get('by')))
Dom.text " • "
Time.deltaText shared.get('created')
# details
if details = shared.get('details')
Form.label !->
Dom.text tr("Details")
Dom.div !->
Dom.userText details
# attendance info..
if shared.get('rsvp')
Form.label tr("Attendance")
Dom.div !->
attendance =
1: []
2: []
3: []
shared.forEach 'attendance', (user) !->
attendance[user.get()].push user.key()
userAtt = shared.get('attendance', App.userId())
for type in [1, 2, 3] then do (type) !->
chosen = userAtt is type
Dom.div !->
Dom.style Box: 'top', margin: '12px 0', fontSize: '85%'
Ui.button !->
Dom.style margin: 0, width: '70px', textAlign: 'center', border: '1px solid '+App.colors().highlight
if chosen
Dom.style backgroundColor: App.colors().highlight, color: '#fff'
else
Dom.style backgroundColor: 'transparent', color: App.colors().highlight
Dom.text attendanceTypes[type]
, !->
Server.sync 'attendance', (if chosen then 0 else type), !->
shared.set 'attendance', App.userId(), (if chosen then null else type)
Dom.div !->
Dom.style fontWeight: 'bold', padding: '6px 8px'
Dom.text ' (' + attendance[type].length + ')'
Dom.div !->
Dom.style Flex: 1, fontWeight: 'bold', padding: '6px 0'
for uid, k in attendance[type] then do (uid) !->
if k
Dom.span !->
Dom.style color: '#999'
Dom.text ', '
Dom.span !->
Dom.style
whiteSpace: 'nowrap'
color: (if App.userId() is +uid then 'inherit' else '#999')
padding: '2px 4px'
margin: '-2px -4px'
Dom.text App.userName(uid)
Dom.onTap (!-> App.showMemberInfo(uid))
renderPlanner = !->
getState = (optionId, userId) -> shared.get('answers', optionId, userId||App.userId()) || 0
renderIcon = (optionId, userId, edit, content) !->
Dom.div !->
Dom.style
Box: 'middle center'
padding: '10px'
minWidth: '29px'
minHeight: '29px'
margin: if edit then 0 else '-9px 0'
opacity: if edit then 1 else 0.3
Dom.img !->
icon = ['unknown', 'yes', 'no', 'maybe'][getState(optionId, userId)]
Dom.prop src: App.resourceUri("#{icon}.png")
Dom.style
maxWidth: '24px'
maxHeight: '24px'
width: 'auto'
verticalAlign: 'middle'
content?()
userId = App.userId()
Page.setCardBackground()
Ui.top !->
Dom.style backgroundColor: '#fff'
ownerId = App.ownerId()
Dom.div !->
Dom.style Box: true
Ui.avatar App.userAvatar(ownerId), onTap: !-> App.showMemberInfo(ownerId)
Dom.h1 !->
Dom.style Flex: 2, display: 'block', marginLeft: '10px'
Dom.text App.title()
Dom.div !->
Dom.style margin: '0 0 0 50px'
Dom.richText shared.get('details') || ''
Dom.div !->
Dom.style
fontSize: '70%'
color: '#aaa'
padding: '6px 0 0'
if ownerId
Dom.text App.userName(ownerId)
Dom.text " • "
Time.deltaText App.created()
# create a mapping from db to optionsO that uses 'day-time' keys
optionsO = Obs.create {}
shared.observeEach 'options', (opt) !->
oDay = 0|opt.key()
if !opt.ref().count().get()
optionsO.set oDay+'', {}
else
opt.observeEach (time) !->
optKey = <KEY>Day+'<KEY>-'+time.key()
optionsO.set optKey, true
Obs.onClean !->
optionsO.remove optKey
Obs.onClean !->
optionsO.remove oDay
users = App.users.get()
expanded = Obs.create(Page.state.peek('exp'))
Ui.list !->
if !optionsO.count().get()
Ui.emptyText tr("No date options configured yet")
else
optionsO.observeEach (option) !->
optionId = option.key()
[day, time] = optionId.split('-')
dayName = Datepicker.dayToString(day, true)
if time
append = ''
if duration = shared.get('duration')
append = '-' + Datepicker.timeToString(+time+duration)
optionName = dayName + ' (' + Datepicker.timeToString(time) + append + ')'
else
optionName = dayName
Ui.item !->
Dom.style Box: 'middle', padding: 0
Dom.style borderBottom: 'none' if expanded.get(optionId)
Dom.div !->
Dom.style Box: 'middle', Flex: 1, padding: '8px'
Dom.div !->
cnt = 0
if answers = shared.get('answers', optionId)
for uid, answer of answers
if users[uid] and answer is 1
cnt++
Dom.style
Box: "middle center"
padding: '5px'
fontSize: '120%'
marginRight: '10px'
backgroundColor: '#ddd'
color: if cnt then 'black' else '#aaa'
borderRadius: '4px'
minWidth: '25px'
Dom.text cnt
Dom.div !->
Dom.style Flex: 1
Dom.div !->
Dom.style fontWeight: 'bold'
Dom.text optionName
Dom.br()
Dom.span !->
notesCnt = shared.ref('notes').count(optionId).get()
Dom.text if notesCnt then tr("%1 note|s", notesCnt) else tr("No notes")
Dom.style fontWeight: 'normal', fontSize: '80%', color: (if notesCnt then 'inherit' else '#aaa')
Dom.div !->
Dom.style color: '#aaa', margin: '0 5px', border: '8px solid transparent'
if expanded.get(optionId)
Dom.style borderBottom: '8px solid #ccc', marginTop: '-8px'
else
Dom.style borderTop: '8px solid #ccc', marginBottom: '-8px'
Dom.onTap !->
expanded.modify optionId, (v) -> if v then null else true
Page.state.set('exp', expanded.get())
if !expanded.get(optionId)
Form.vSep()
renderIcon optionId, userId, true, !->
Dom.onTap !->
state = (getState(optionId)+1)%4
Server.sync 'setState', optionId, state, !->
shared.set 'answers', optionId, userId, state
else
# to prevent a tap-highlight in this area
Dom.div !->
Dom.style width: '50px'
if expanded.get(optionId)
Ui.item !->
Dom.style Box: "right", padding: '0 0 8px 0'
Dom.span !->
Dom.style display: 'block', maxWidth: '20em'
App.users.observeEach (user) !->
isMine = +user.key() is +userId
Dom.span !->
Dom.style Box: "middle", margin: (if isMine then 0 else '4px 0'), textAlign: 'right'
Dom.div !->
Dom.style Flex: 1
if isMine
Dom.style padding: '5px'
else
Dom.style margin: '0 5px'
Dom.span !->
Dom.style fontWeight: 'bold'
Dom.text user.get('name')
note = shared.get('notes', optionId, user.key())
if isMine
Dom.text ': '
Dom.text note if note
Dom.span !->
Dom.style color: App.colors().highlight
Dom.text (if note then ' ' + tr "Edit" else tr "Add a note")
Dom.onTap !->
Form.prompt
title: tr('Note for %1', optionName)
value: note
cb: (note) !->
Server.sync 'setNote', optionId, note||null, !->
shared.set 'notes', optionId, userId, note||null
else if note
Dom.text ': '+note
Ui.avatar App.userAvatar(user.key()),
style: margin: '0 8px'
size: 24
onTap: !-> App.showMemberInfo(user.key())
renderIcon optionId, user.key(), isMine, if isMine then !->
Dom.onTap !->
state = (getState(optionId)+1)%4
Server.sync 'setState', optionId, state, !->
shared.set 'answers', optionId, userId, state
, (user) ->
if +user.key() is +userId
-1000
else
user.get('name')
if App.userIsAdmin() or App.ownerId() is App.userId()
Dom.div !->
Dom.style textAlign: 'right', paddingRight: '8px'
Ui.button tr("Pick date"), !->
Modal.confirm tr("Pick %1?", optionName), tr("Members will no longer be able to change their availability"), !->
Server.sync 'pickDate', optionId
, (option) -> # sort order
option.key()
renderEventSettings = !->
curDate = shared.get('date')||today
curTime = Obs.create(shared.get('time') || -1)
Dom.div !->
Dom.style Box: 'horizontal'
Form.box !->
Dom.style Flex: 1, paddingRight: '12px'
Dom.text tr("Event date")
[handleChange] = Form.makeInput
name: 'date'
value: curDate
content: (value) !->
Dom.div Datepicker.dayToString(value)
Dom.onTap !->
cur = null
Modal.confirm tr("Select date"), !->
cur = Datepicker.date
value: curDate
, !->
handleChange cur.get()
curDate = cur.get()
Form.vSep()
Form.box !->
Dom.style Flex: 1, paddingLeft: '12px'
Dom.text tr("Event time")
[handleChange] = Form.makeInput
name: 'time'
value: curTime.peek()
content: (value) !->
Dom.div Datepicker.timeToString(value)
Dom.onTap !->
val = (if curTime.peek()<0 then null else curTime.peek())
Modal.show tr("Enter time"), !->
Datepicker.time
value: val
onChange: (v) !->
val = v
, (choice) !->
return if choice is 'cancel'
newVal = (if choice is 'clear' then -1 else val)
handleChange newVal
curTime.set newVal
, ['cancel', tr("Cancel"), 'clear', tr("All day"), 'ok', tr("Set")]
renderDurationInput shared.get('duration')||0, curTime
Form.box !->
remind = shared.get('remind')
if !remind? then remind = 86400 # if 0 then it should remain 0
getRemindText = (r) ->
if r is -1
tr("No reminder")
else if r is 0
tr("At time of event")
else if r is 600
tr("10 minutes before")
else if r is 3600
tr("1 hour before")
else if r is 86400
tr("1 day before", r)
else if r is 604800
tr("1 week before", r)
Dom.text tr("Reminder")
[handleChange] = Form.makeInput
name: 'remind'
value: remind
content: (value) !->
Dom.div !->
Dom.text getRemindText(value)
Dom.onTap !->
Modal.show tr("Remind members"), !->
opts = [0, 600, 3600, 86400, 604800, -1]
for rem in opts then do (rem) !->
Ui.item !->
Dom.text getRemindText(rem)
if remind is rem
Dom.style fontWeight: 'bold'
Dom.div !->
Dom.style
Flex: 1
padding: '0 10px'
textAlign: 'right'
fontSize: '150%'
color: App.colors().highlight
Dom.text "✓"
Dom.onTap !->
handleChange rem
remind = rem
Modal.remove()
Obs.observe !->
ask = Obs.create(shared.get('rsvp') || true)
Form.check
name: 'rsvp'
value: shared.func('rsvp') || true
text: tr("Ask people if they're going")
onChange: (v) !->
ask.set(v)
renderPlannerSettings = !->
datesO = null # consists of { dayNr: true } entries, used by Datepicker.date
optionsO = Obs.create {} # consists of { dayNr: time: true } (or dayNr: {}) entries
# construct initial optionsO from db values
curDates = {}
for day, times of shared.get('options')
curDates[day] = true
optionsO.set day, {}
for t, v of times
(o = {})[t] = true
optionsO.merge day, o
Form.addObs 'options', optionsO
Dom.div !->
Dom.style Box: "center", marginTop: '12px', borderBottom: '1px solid #ddd'
datesO = Datepicker.date
mode: 'multi'
value: curDates
# map selected days to optionsO
Obs.observe !->
datesO.observeEach (entry) !->
eDay = entry.key()
optionsO.merge eDay, {}
Obs.onClean !->
optionsO.remove eDay
optionsCnt = Obs.create 0
Obs.observe !->
cnt = 0
for k, times of optionsO.get()
tCnt = 0
for x, y of times
tCnt++
tCnt = Math.max(tCnt, 1)
cnt += tCnt
optionsCnt.set cnt
lastTime = null
dayTimeOptions = (day) !->
addTimeOption = !->
Modal.show tr("Add time option"), !->
Datepicker.time
value: lastTime
onChange: (v) !->
lastTime = v
, (choice) !->
if choice is 'add' and lastTime
optionsO.set day, lastTime, true
showTimeOptions()
, ['cancel', tr("Cancel"), 'add', tr("Add")]
showTimeOptions = !->
Modal.show tr("Time options"), !->
optionsO.observeEach day, (timeOption) !->
Ui.item !->
Dom.div !->
Dom.style Flex: 1, fontSize: '125%', fontWeight: 'bold', paddingLeft: '4px'
Dom.text Datepicker.timeToString(timeOption.key())
Icon.render
data: 'cancelround'
size: 32
onTap: !->
optionsO.remove day, timeOption.key()
Ui.item !->
Dom.style color: App.colors().highlight, paddingLeft: '12px'
Dom.text tr('+ Add option')
Dom.onTap !->
Modal.remove()
addTimeOption()
if optionsO.ref(day).count().get()
# multiple time options
showTimeOptions()
else
# first time option
addTimeOption()
Obs.observe !->
optionsO.observeEach (entry) !->
oDay = entry.key()
Ui.item !->
Dom.style padding: 0
Dom.div !->
Dom.style Flex: 1, padding: '12px'
Dom.text Datepicker.dayToString(oDay)
Dom.div !->
Dom.style fontSize: '75%', color: '#aaa', marginTop: '3px'
ts = (Datepicker.timeToString(t) for t, v of entry.get())
if ts.length
Dom.text ts.join(' / ')
else
Dom.text tr("No time(s) specified")
Dom.onTap !->
dayTimeOptions oDay
Form.vSep()
Icon.render
data: 'cancel'
size: 24
style: padding: '18px'
onTap: !->
datesO.remove oDay # syncs to optionsO
, (entry) -> entry.key()
Form.condition ->
tr("A minimum of two options is required") if optionsCnt.peek()<2
Obs.observe !->
showDuration = false
for date, entry of optionsO.get() when !showDuration
for k, v of entry
showDuration = true # at least one time option defined
break
if !showDuration
return
renderDurationInput shared.get('duration')||0
Dom.div !->
Dom.style Box: 'center middle', textAlign: 'center', color: '#aaa', padding: '8px', fontSize: '85%'
oc = optionsCnt.get()
Dom.text (if !oc then tr("No dates selected yet") else tr("Poll will have %1 option|s", oc))
exports.renderSettings = !->
Form.input
name: '_title'
text: tr("Event name")
value: App.title()
Form.condition (val) ->
tr("An event name is required") if !val._title
Form.text
name: 'details'
text: tr "Details about the event"
autogrow: true
value: shared.func('details')
showPlanner = Obs.create (if shared.get('date') then false else true)
Obs.observe !->
if !Db.shared # only offer choice on install
Form.segmented
name: 'type'
value: 'announce'
segments: ['announce', tr("Fixed date"), 'plan', tr("Date poll")]
onChange: (v) !-> showPlanner.set(v is 'plan')
description: !->
Dom.text (if showPlanner.get() then tr("Asks people to vote for the best date") else tr("Enter date and time below"))
if !showPlanner.get()
# select date
renderEventSettings()
else
renderPlannerSettings()
renderDurationInput = (duration, timeO) !->
Form.box !->
allDay = if timeO? then timeO.get() is -1 else false
Dom.style color: if allDay then '#aaa' else ''
Dom.text tr("Duration")
if allDay
Dom.div tr("No event time specified")
else
[handleChange] = Form.makeInput
name: 'duration'
value: duration
onChange: (v) !->
duration = v
content: (value) !->
Dom.div !->
hours = Math.floor(value/3600)
mins = (value - hours*3600)/60
Dom.text if hours and mins
tr("%1 hour|s and %2 min|s", hours, mins)
else if hours
tr("%1 hour|s", hours)
else if mins
tr("%1 min|s", mins)
else
tr("Not specified")
Dom.onTap !->
Modal.show tr("Duration"), !->
Datepicker.time
value: duration
onChange: (v) !->
handleChange v
duration = v
| true | App = require 'app'
Comments = require 'comments'
Datepicker = require 'datepicker'
Db = require 'db'
Dom = require 'dom'
Event = require 'event'
Form = require 'form'
Icon = require 'icon'
Modal = require 'modal'
Obs = require 'obs'
Page = require 'page'
Server = require 'server'
Time = require 'time'
Ui = require 'ui'
{tr} = require 'i18n'
today = 0|(((new Date()).getTime() - (new Date()).getTimezoneOffset()*6e4) / 864e5)
attendanceTypes =
1: tr "Going"
2: tr "Maybe"
3: tr "Not going"
if Db.shared
shared = Db.shared.ref()
else
shared = Obs.create()
exports.render = !->
if shared.get('date')
renderEvent()
else
renderPlanner()
Comments.enable
messages:
remind: (c) ->
remind = shared.get('remind') || 0
if remind <= 0
tr("This event is happening right now!")
else if remind is 600
tr("This event is happening in 10 minutes")
else if remind is 3600
tr("This event is happening in 1 hour")
else if remind is 86400
tr("This event is happening in 1 day")
else if remind is 604800
tr("This event is happening in 1 week")
picked: (c) ->
whenText = (if (time = Db.shared.get('time'))? and time isnt -1 then Datepicker.timeToString(time)+' ' else '')
whenText += Datepicker.dayToString(Db.shared.get('date'))
"Event date picked: #{whenText} (#{App.title()})"
renderEvent = !->
Ui.top !->
Dom.cls 'top1'
Dom.style margin: 0
Dom.div !->
Dom.span !->
Dom.style fontSize: '160%', fontWeight: 'bold'
Dom.userText App.title()
Dom.div !->
append = ''
if duration = shared.get('duration')
append = ' - ' + Datepicker.timeToString(+shared.get('time')+duration)
Dom.text Datepicker.timeToString(shared.get('time'))+append
Dom.span !->
Dom.style padding: '0 4px'
Dom.text ' • '
Dom.text Datepicker.dayToString(shared.get('date'))
Dom.div !->
Dom.style
display: 'inline-block'
padding: '6px 8px'
fontSize: '75%'
color: '#fff'
marginTop: '8px'
textTransform: 'uppercase'
border: '1px solid #fff'
borderRadius: '2px'
Dom.text tr "Add to calendar"
Dom.onTap !->
if App.agent().android
beginTime = Datepicker.dayToDate(shared.get('date'))
time = Db.shared.get('time')
if time>=0
beginTime.setHours(Math.floor(time/3600))
beginTime.setMinutes(Math.floor((time%3600)/60))
beginTime.setSeconds(Math.floor(time%60))
description = Db.shared.get('details') || ''
intentOpts =
_action: "android.intent.action.INSERT"
_data: "content://com.android.calendar/events"
_activity: 0
allDay: time<0
beginTime: beginTime.getTime()
title: App.title()
description: description
availability: 0 # busy
if duration = Db.shared.get('duration')
intentOpts.endTime = beginTime.getTime() + duration * 1000
ok = App.intent intentOpts
else
App.openUrl App.inboundUrl()
Dom.div !->
Dom.style
fontSize: '75%'
color: '#ddd'
marginTop: '16px'
Dom.text tr("Added by %1", App.userName(shared.get('by')))
Dom.text " • "
Time.deltaText shared.get('created')
# details
if details = shared.get('details')
Form.label !->
Dom.text tr("Details")
Dom.div !->
Dom.userText details
# attendance info..
if shared.get('rsvp')
Form.label tr("Attendance")
Dom.div !->
attendance =
1: []
2: []
3: []
shared.forEach 'attendance', (user) !->
attendance[user.get()].push user.key()
userAtt = shared.get('attendance', App.userId())
for type in [1, 2, 3] then do (type) !->
chosen = userAtt is type
Dom.div !->
Dom.style Box: 'top', margin: '12px 0', fontSize: '85%'
Ui.button !->
Dom.style margin: 0, width: '70px', textAlign: 'center', border: '1px solid '+App.colors().highlight
if chosen
Dom.style backgroundColor: App.colors().highlight, color: '#fff'
else
Dom.style backgroundColor: 'transparent', color: App.colors().highlight
Dom.text attendanceTypes[type]
, !->
Server.sync 'attendance', (if chosen then 0 else type), !->
shared.set 'attendance', App.userId(), (if chosen then null else type)
Dom.div !->
Dom.style fontWeight: 'bold', padding: '6px 8px'
Dom.text ' (' + attendance[type].length + ')'
Dom.div !->
Dom.style Flex: 1, fontWeight: 'bold', padding: '6px 0'
for uid, k in attendance[type] then do (uid) !->
if k
Dom.span !->
Dom.style color: '#999'
Dom.text ', '
Dom.span !->
Dom.style
whiteSpace: 'nowrap'
color: (if App.userId() is +uid then 'inherit' else '#999')
padding: '2px 4px'
margin: '-2px -4px'
Dom.text App.userName(uid)
Dom.onTap (!-> App.showMemberInfo(uid))
renderPlanner = !->
getState = (optionId, userId) -> shared.get('answers', optionId, userId||App.userId()) || 0
renderIcon = (optionId, userId, edit, content) !->
Dom.div !->
Dom.style
Box: 'middle center'
padding: '10px'
minWidth: '29px'
minHeight: '29px'
margin: if edit then 0 else '-9px 0'
opacity: if edit then 1 else 0.3
Dom.img !->
icon = ['unknown', 'yes', 'no', 'maybe'][getState(optionId, userId)]
Dom.prop src: App.resourceUri("#{icon}.png")
Dom.style
maxWidth: '24px'
maxHeight: '24px'
width: 'auto'
verticalAlign: 'middle'
content?()
userId = App.userId()
Page.setCardBackground()
Ui.top !->
Dom.style backgroundColor: '#fff'
ownerId = App.ownerId()
Dom.div !->
Dom.style Box: true
Ui.avatar App.userAvatar(ownerId), onTap: !-> App.showMemberInfo(ownerId)
Dom.h1 !->
Dom.style Flex: 2, display: 'block', marginLeft: '10px'
Dom.text App.title()
Dom.div !->
Dom.style margin: '0 0 0 50px'
Dom.richText shared.get('details') || ''
Dom.div !->
Dom.style
fontSize: '70%'
color: '#aaa'
padding: '6px 0 0'
if ownerId
Dom.text App.userName(ownerId)
Dom.text " • "
Time.deltaText App.created()
# create a mapping from db to optionsO that uses 'day-time' keys
optionsO = Obs.create {}
shared.observeEach 'options', (opt) !->
oDay = 0|opt.key()
if !opt.ref().count().get()
optionsO.set oDay+'', {}
else
opt.observeEach (time) !->
optKey = PI:KEY:<KEY>END_PIDay+'PI:KEY:<KEY>END_PI-'+time.key()
optionsO.set optKey, true
Obs.onClean !->
optionsO.remove optKey
Obs.onClean !->
optionsO.remove oDay
users = App.users.get()
expanded = Obs.create(Page.state.peek('exp'))
Ui.list !->
if !optionsO.count().get()
Ui.emptyText tr("No date options configured yet")
else
optionsO.observeEach (option) !->
optionId = option.key()
[day, time] = optionId.split('-')
dayName = Datepicker.dayToString(day, true)
if time
append = ''
if duration = shared.get('duration')
append = '-' + Datepicker.timeToString(+time+duration)
optionName = dayName + ' (' + Datepicker.timeToString(time) + append + ')'
else
optionName = dayName
Ui.item !->
Dom.style Box: 'middle', padding: 0
Dom.style borderBottom: 'none' if expanded.get(optionId)
Dom.div !->
Dom.style Box: 'middle', Flex: 1, padding: '8px'
Dom.div !->
cnt = 0
if answers = shared.get('answers', optionId)
for uid, answer of answers
if users[uid] and answer is 1
cnt++
Dom.style
Box: "middle center"
padding: '5px'
fontSize: '120%'
marginRight: '10px'
backgroundColor: '#ddd'
color: if cnt then 'black' else '#aaa'
borderRadius: '4px'
minWidth: '25px'
Dom.text cnt
Dom.div !->
Dom.style Flex: 1
Dom.div !->
Dom.style fontWeight: 'bold'
Dom.text optionName
Dom.br()
Dom.span !->
notesCnt = shared.ref('notes').count(optionId).get()
Dom.text if notesCnt then tr("%1 note|s", notesCnt) else tr("No notes")
Dom.style fontWeight: 'normal', fontSize: '80%', color: (if notesCnt then 'inherit' else '#aaa')
Dom.div !->
Dom.style color: '#aaa', margin: '0 5px', border: '8px solid transparent'
if expanded.get(optionId)
Dom.style borderBottom: '8px solid #ccc', marginTop: '-8px'
else
Dom.style borderTop: '8px solid #ccc', marginBottom: '-8px'
Dom.onTap !->
expanded.modify optionId, (v) -> if v then null else true
Page.state.set('exp', expanded.get())
if !expanded.get(optionId)
Form.vSep()
renderIcon optionId, userId, true, !->
Dom.onTap !->
state = (getState(optionId)+1)%4
Server.sync 'setState', optionId, state, !->
shared.set 'answers', optionId, userId, state
else
# to prevent a tap-highlight in this area
Dom.div !->
Dom.style width: '50px'
if expanded.get(optionId)
Ui.item !->
Dom.style Box: "right", padding: '0 0 8px 0'
Dom.span !->
Dom.style display: 'block', maxWidth: '20em'
App.users.observeEach (user) !->
isMine = +user.key() is +userId
Dom.span !->
Dom.style Box: "middle", margin: (if isMine then 0 else '4px 0'), textAlign: 'right'
Dom.div !->
Dom.style Flex: 1
if isMine
Dom.style padding: '5px'
else
Dom.style margin: '0 5px'
Dom.span !->
Dom.style fontWeight: 'bold'
Dom.text user.get('name')
note = shared.get('notes', optionId, user.key())
if isMine
Dom.text ': '
Dom.text note if note
Dom.span !->
Dom.style color: App.colors().highlight
Dom.text (if note then ' ' + tr "Edit" else tr "Add a note")
Dom.onTap !->
Form.prompt
title: tr('Note for %1', optionName)
value: note
cb: (note) !->
Server.sync 'setNote', optionId, note||null, !->
shared.set 'notes', optionId, userId, note||null
else if note
Dom.text ': '+note
Ui.avatar App.userAvatar(user.key()),
style: margin: '0 8px'
size: 24
onTap: !-> App.showMemberInfo(user.key())
renderIcon optionId, user.key(), isMine, if isMine then !->
Dom.onTap !->
state = (getState(optionId)+1)%4
Server.sync 'setState', optionId, state, !->
shared.set 'answers', optionId, userId, state
, (user) ->
if +user.key() is +userId
-1000
else
user.get('name')
if App.userIsAdmin() or App.ownerId() is App.userId()
Dom.div !->
Dom.style textAlign: 'right', paddingRight: '8px'
Ui.button tr("Pick date"), !->
Modal.confirm tr("Pick %1?", optionName), tr("Members will no longer be able to change their availability"), !->
Server.sync 'pickDate', optionId
, (option) -> # sort order
option.key()
renderEventSettings = !->
curDate = shared.get('date')||today
curTime = Obs.create(shared.get('time') || -1)
Dom.div !->
Dom.style Box: 'horizontal'
Form.box !->
Dom.style Flex: 1, paddingRight: '12px'
Dom.text tr("Event date")
[handleChange] = Form.makeInput
name: 'date'
value: curDate
content: (value) !->
Dom.div Datepicker.dayToString(value)
Dom.onTap !->
cur = null
Modal.confirm tr("Select date"), !->
cur = Datepicker.date
value: curDate
, !->
handleChange cur.get()
curDate = cur.get()
Form.vSep()
Form.box !->
Dom.style Flex: 1, paddingLeft: '12px'
Dom.text tr("Event time")
[handleChange] = Form.makeInput
name: 'time'
value: curTime.peek()
content: (value) !->
Dom.div Datepicker.timeToString(value)
Dom.onTap !->
val = (if curTime.peek()<0 then null else curTime.peek())
Modal.show tr("Enter time"), !->
Datepicker.time
value: val
onChange: (v) !->
val = v
, (choice) !->
return if choice is 'cancel'
newVal = (if choice is 'clear' then -1 else val)
handleChange newVal
curTime.set newVal
, ['cancel', tr("Cancel"), 'clear', tr("All day"), 'ok', tr("Set")]
renderDurationInput shared.get('duration')||0, curTime
Form.box !->
remind = shared.get('remind')
if !remind? then remind = 86400 # if 0 then it should remain 0
getRemindText = (r) ->
if r is -1
tr("No reminder")
else if r is 0
tr("At time of event")
else if r is 600
tr("10 minutes before")
else if r is 3600
tr("1 hour before")
else if r is 86400
tr("1 day before", r)
else if r is 604800
tr("1 week before", r)
Dom.text tr("Reminder")
[handleChange] = Form.makeInput
name: 'remind'
value: remind
content: (value) !->
Dom.div !->
Dom.text getRemindText(value)
Dom.onTap !->
Modal.show tr("Remind members"), !->
opts = [0, 600, 3600, 86400, 604800, -1]
for rem in opts then do (rem) !->
Ui.item !->
Dom.text getRemindText(rem)
if remind is rem
Dom.style fontWeight: 'bold'
Dom.div !->
Dom.style
Flex: 1
padding: '0 10px'
textAlign: 'right'
fontSize: '150%'
color: App.colors().highlight
Dom.text "✓"
Dom.onTap !->
handleChange rem
remind = rem
Modal.remove()
Obs.observe !->
ask = Obs.create(shared.get('rsvp') || true)
Form.check
name: 'rsvp'
value: shared.func('rsvp') || true
text: tr("Ask people if they're going")
onChange: (v) !->
ask.set(v)
renderPlannerSettings = !->
datesO = null # consists of { dayNr: true } entries, used by Datepicker.date
optionsO = Obs.create {} # consists of { dayNr: time: true } (or dayNr: {}) entries
# construct initial optionsO from db values
curDates = {}
for day, times of shared.get('options')
curDates[day] = true
optionsO.set day, {}
for t, v of times
(o = {})[t] = true
optionsO.merge day, o
Form.addObs 'options', optionsO
Dom.div !->
Dom.style Box: "center", marginTop: '12px', borderBottom: '1px solid #ddd'
datesO = Datepicker.date
mode: 'multi'
value: curDates
# map selected days to optionsO
Obs.observe !->
datesO.observeEach (entry) !->
eDay = entry.key()
optionsO.merge eDay, {}
Obs.onClean !->
optionsO.remove eDay
optionsCnt = Obs.create 0
Obs.observe !->
cnt = 0
for k, times of optionsO.get()
tCnt = 0
for x, y of times
tCnt++
tCnt = Math.max(tCnt, 1)
cnt += tCnt
optionsCnt.set cnt
lastTime = null
dayTimeOptions = (day) !->
addTimeOption = !->
Modal.show tr("Add time option"), !->
Datepicker.time
value: lastTime
onChange: (v) !->
lastTime = v
, (choice) !->
if choice is 'add' and lastTime
optionsO.set day, lastTime, true
showTimeOptions()
, ['cancel', tr("Cancel"), 'add', tr("Add")]
showTimeOptions = !->
Modal.show tr("Time options"), !->
optionsO.observeEach day, (timeOption) !->
Ui.item !->
Dom.div !->
Dom.style Flex: 1, fontSize: '125%', fontWeight: 'bold', paddingLeft: '4px'
Dom.text Datepicker.timeToString(timeOption.key())
Icon.render
data: 'cancelround'
size: 32
onTap: !->
optionsO.remove day, timeOption.key()
Ui.item !->
Dom.style color: App.colors().highlight, paddingLeft: '12px'
Dom.text tr('+ Add option')
Dom.onTap !->
Modal.remove()
addTimeOption()
if optionsO.ref(day).count().get()
# multiple time options
showTimeOptions()
else
# first time option
addTimeOption()
Obs.observe !->
optionsO.observeEach (entry) !->
oDay = entry.key()
Ui.item !->
Dom.style padding: 0
Dom.div !->
Dom.style Flex: 1, padding: '12px'
Dom.text Datepicker.dayToString(oDay)
Dom.div !->
Dom.style fontSize: '75%', color: '#aaa', marginTop: '3px'
ts = (Datepicker.timeToString(t) for t, v of entry.get())
if ts.length
Dom.text ts.join(' / ')
else
Dom.text tr("No time(s) specified")
Dom.onTap !->
dayTimeOptions oDay
Form.vSep()
Icon.render
data: 'cancel'
size: 24
style: padding: '18px'
onTap: !->
datesO.remove oDay # syncs to optionsO
, (entry) -> entry.key()
Form.condition ->
tr("A minimum of two options is required") if optionsCnt.peek()<2
Obs.observe !->
showDuration = false
for date, entry of optionsO.get() when !showDuration
for k, v of entry
showDuration = true # at least one time option defined
break
if !showDuration
return
renderDurationInput shared.get('duration')||0
Dom.div !->
Dom.style Box: 'center middle', textAlign: 'center', color: '#aaa', padding: '8px', fontSize: '85%'
oc = optionsCnt.get()
Dom.text (if !oc then tr("No dates selected yet") else tr("Poll will have %1 option|s", oc))
exports.renderSettings = !->
Form.input
name: '_title'
text: tr("Event name")
value: App.title()
Form.condition (val) ->
tr("An event name is required") if !val._title
Form.text
name: 'details'
text: tr "Details about the event"
autogrow: true
value: shared.func('details')
showPlanner = Obs.create (if shared.get('date') then false else true)
Obs.observe !->
if !Db.shared # only offer choice on install
Form.segmented
name: 'type'
value: 'announce'
segments: ['announce', tr("Fixed date"), 'plan', tr("Date poll")]
onChange: (v) !-> showPlanner.set(v is 'plan')
description: !->
Dom.text (if showPlanner.get() then tr("Asks people to vote for the best date") else tr("Enter date and time below"))
if !showPlanner.get()
# select date
renderEventSettings()
else
renderPlannerSettings()
renderDurationInput = (duration, timeO) !->
Form.box !->
allDay = if timeO? then timeO.get() is -1 else false
Dom.style color: if allDay then '#aaa' else ''
Dom.text tr("Duration")
if allDay
Dom.div tr("No event time specified")
else
[handleChange] = Form.makeInput
name: 'duration'
value: duration
onChange: (v) !->
duration = v
content: (value) !->
Dom.div !->
hours = Math.floor(value/3600)
mins = (value - hours*3600)/60
Dom.text if hours and mins
tr("%1 hour|s and %2 min|s", hours, mins)
else if hours
tr("%1 hour|s", hours)
else if mins
tr("%1 min|s", mins)
else
tr("Not specified")
Dom.onTap !->
Modal.show tr("Duration"), !->
Datepicker.time
value: duration
onChange: (v) !->
handleChange v
duration = v
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.