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": " 'verification:meshblu-protocol'\n username: 'bobby'\n password: 'drop tables'\n port: 0xd00d",
"end": 519,
"score": 0.9995836019515991,
"start": 514,
"tag": "USERNAME",
"value": "bobby"
},
{
"context": "rotocol'\n username: 'bobby'\n password: ... | test/integration/store-verification-spec.coffee | octoblu/meshblu-verifier-pingdom | 0 | {afterEach, beforeEach, describe, it} = global
{expect} = require 'chai'
sinon = require 'sinon'
_ = require 'lodash'
moment = require 'moment'
request = require 'request'
Server = require '../../src/server.coffee'
describe 'Store Verification', ->
beforeEach (done) ->
@elasticsearch = create: sinon.stub()
@logFn = sinon.spy()
@sut = new Server {
@elasticsearch
@logFn,
disableLogging: true
elasticsearchIndex: 'verification:meshblu-protocol'
username: 'bobby'
password: 'drop tables'
port: 0xd00d
}
@sut.run done
afterEach (done) ->
@sut.destroy done
describe 'POST /verifications/foo/', ->
describe 'when called', ->
beforeEach (done) ->
@elasticsearch.create.yields null
@expiration = moment().add(2, 'minutes').utc().format()
options =
baseUrl: "http://localhost:#{@sut.address().port}"
auth: {username: 'bobby', password: 'drop tables'}
json:
success: true
expires: @expiration
error:
message: 'uh oh'
step: 'register'
stats:
operation: 'doin-somethin'
startTime: '2016-01-12T01:00:00.000Z'
endTime: '2016-01-12T02:00:00.000Z'
duration: 12345
request.post '/verifications/foo', options, (error, @response) => done error
it 'should respond with a 201', ->
expect(@response.statusCode).to.equal 201
it 'should store the verification in elasticsearch', ->
dateStr = moment().format "YYYY-MM-DD"
expect(@elasticsearch.create).to.have.been.called
arg = _.first @elasticsearch.create.firstCall.args
now = moment().valueOf()
expect(arg).to.containSubset {
index: "verification:meshblu-protocol-#{dateStr}"
type: 'foo'
body: {
index: "verification:meshblu-protocol-#{dateStr}"
type: 'foo'
metadata:
name: 'foo'
success: true
expires: @expiration
data:
error:
message: 'uh oh'
step: 'register'
}
}
expect(arg.body.date).to.be.closeTo now, 100
describe 'when called with a non-integer', ->
beforeEach (done) ->
@elasticsearch.create.yields null
@expiration = moment().add(2, 'minutes').utc().format()
options =
baseUrl: "http://localhost:#{@sut.address().port}"
auth: {username: 'bobby', password: 'drop tables'}
json:
success: true
expires: @expiration
error:
message: 'uh oh'
step: 'register'
code: 'ETIMEOUT'
request.post '/verifications/foo', options, (error, @response) => done error
it 'should respond with a 201', ->
expect(@response.statusCode).to.equal 201
it 'should store the verification in elasticsearch', ->
expect(@elasticsearch.create).to.have.been.called
arg = _.first @elasticsearch.create.firstCall.args
expect(arg.body.data.error).not.to.have.property 'code'
| 132688 | {afterEach, beforeEach, describe, it} = global
{expect} = require 'chai'
sinon = require 'sinon'
_ = require 'lodash'
moment = require 'moment'
request = require 'request'
Server = require '../../src/server.coffee'
describe 'Store Verification', ->
beforeEach (done) ->
@elasticsearch = create: sinon.stub()
@logFn = sinon.spy()
@sut = new Server {
@elasticsearch
@logFn,
disableLogging: true
elasticsearchIndex: 'verification:meshblu-protocol'
username: 'bobby'
password: '<PASSWORD>'
port: 0xd00d
}
@sut.run done
afterEach (done) ->
@sut.destroy done
describe 'POST /verifications/foo/', ->
describe 'when called', ->
beforeEach (done) ->
@elasticsearch.create.yields null
@expiration = moment().add(2, 'minutes').utc().format()
options =
baseUrl: "http://localhost:#{@sut.address().port}"
auth: {username: 'bobby', password: '<PASSWORD>'}
json:
success: true
expires: @expiration
error:
message: 'uh oh'
step: 'register'
stats:
operation: 'doin-somethin'
startTime: '2016-01-12T01:00:00.000Z'
endTime: '2016-01-12T02:00:00.000Z'
duration: 12345
request.post '/verifications/foo', options, (error, @response) => done error
it 'should respond with a 201', ->
expect(@response.statusCode).to.equal 201
it 'should store the verification in elasticsearch', ->
dateStr = moment().format "YYYY-MM-DD"
expect(@elasticsearch.create).to.have.been.called
arg = _.first @elasticsearch.create.firstCall.args
now = moment().valueOf()
expect(arg).to.containSubset {
index: "verification:meshblu-protocol-#{dateStr}"
type: 'foo'
body: {
index: "verification:meshblu-protocol-#{dateStr}"
type: 'foo'
metadata:
name: 'foo'
success: true
expires: @expiration
data:
error:
message: 'uh oh'
step: 'register'
}
}
expect(arg.body.date).to.be.closeTo now, 100
describe 'when called with a non-integer', ->
beforeEach (done) ->
@elasticsearch.create.yields null
@expiration = moment().add(2, 'minutes').utc().format()
options =
baseUrl: "http://localhost:#{@sut.address().port}"
auth: {username: 'bobby', password: '<PASSWORD>'}
json:
success: true
expires: @expiration
error:
message: 'uh oh'
step: 'register'
code: 'ETIMEOUT'
request.post '/verifications/foo', options, (error, @response) => done error
it 'should respond with a 201', ->
expect(@response.statusCode).to.equal 201
it 'should store the verification in elasticsearch', ->
expect(@elasticsearch.create).to.have.been.called
arg = _.first @elasticsearch.create.firstCall.args
expect(arg.body.data.error).not.to.have.property 'code'
| true | {afterEach, beforeEach, describe, it} = global
{expect} = require 'chai'
sinon = require 'sinon'
_ = require 'lodash'
moment = require 'moment'
request = require 'request'
Server = require '../../src/server.coffee'
describe 'Store Verification', ->
beforeEach (done) ->
@elasticsearch = create: sinon.stub()
@logFn = sinon.spy()
@sut = new Server {
@elasticsearch
@logFn,
disableLogging: true
elasticsearchIndex: 'verification:meshblu-protocol'
username: 'bobby'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
port: 0xd00d
}
@sut.run done
afterEach (done) ->
@sut.destroy done
describe 'POST /verifications/foo/', ->
describe 'when called', ->
beforeEach (done) ->
@elasticsearch.create.yields null
@expiration = moment().add(2, 'minutes').utc().format()
options =
baseUrl: "http://localhost:#{@sut.address().port}"
auth: {username: 'bobby', password: 'PI:PASSWORD:<PASSWORD>END_PI'}
json:
success: true
expires: @expiration
error:
message: 'uh oh'
step: 'register'
stats:
operation: 'doin-somethin'
startTime: '2016-01-12T01:00:00.000Z'
endTime: '2016-01-12T02:00:00.000Z'
duration: 12345
request.post '/verifications/foo', options, (error, @response) => done error
it 'should respond with a 201', ->
expect(@response.statusCode).to.equal 201
it 'should store the verification in elasticsearch', ->
dateStr = moment().format "YYYY-MM-DD"
expect(@elasticsearch.create).to.have.been.called
arg = _.first @elasticsearch.create.firstCall.args
now = moment().valueOf()
expect(arg).to.containSubset {
index: "verification:meshblu-protocol-#{dateStr}"
type: 'foo'
body: {
index: "verification:meshblu-protocol-#{dateStr}"
type: 'foo'
metadata:
name: 'foo'
success: true
expires: @expiration
data:
error:
message: 'uh oh'
step: 'register'
}
}
expect(arg.body.date).to.be.closeTo now, 100
describe 'when called with a non-integer', ->
beforeEach (done) ->
@elasticsearch.create.yields null
@expiration = moment().add(2, 'minutes').utc().format()
options =
baseUrl: "http://localhost:#{@sut.address().port}"
auth: {username: 'bobby', password: 'PI:PASSWORD:<PASSWORD>END_PI'}
json:
success: true
expires: @expiration
error:
message: 'uh oh'
step: 'register'
code: 'ETIMEOUT'
request.post '/verifications/foo', options, (error, @response) => done error
it 'should respond with a 201', ->
expect(@response.statusCode).to.equal 201
it 'should store the verification in elasticsearch', ->
expect(@elasticsearch.create).to.have.been.called
arg = _.first @elasticsearch.create.firstCall.args
expect(arg.body.data.error).not.to.have.property 'code'
|
[
{
"context": " \n# Copyright 2011 - 2013 Mark Masse (OSS project WRML.org) \n# ",
"end": 824,
"score": 0.9997959733009338,
"start": 814,
"tag": "NAME",
"value": "Mark Masse"
}
] | wrmldoc/js/app/components/form/FormController.coffee | wrml/wrml | 47 | #
# WRML - Web Resource Modeling Language
# __ __ ______ __ __ __
# /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \
# \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____
# \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\
# \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/
#
# http://www.wrml.org
#
# Copyright 2011 - 2013 Mark Masse (OSS project WRML.org)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# CoffeeScript
@Wrmldoc.module "Components.Form", (Form, App, Backbone, Marionette, $, _) ->
class Form.Controller extends App.Controllers.Base
initialize: (options = {}) ->
@contentView = dataModel.view
@formLayout = @getFormLayout dataModel.config
@listenTo @formLayout, "show", @formContentRegion
@listenTo @formLayout, "form:submit", @formSubmit
@listenTo @formLayout, "form:cancel", @formCancel
formCancel: ->
@contentView.triggerMethod "form:cancel"
formSubmit: ->
data = Backbone.Syphon.serialize @formLayout
if @contentView.triggerMethod("form:submit", data) isnt false
model = @contentView.model
collection = @contentView.collection
@processFormSubmit data, model, collection
processFormSubmit: (data, model, collection) ->
model.save data,
collection: collection
onClose: ->
console.log "onClose", @
formContentRegion: ->
@region = @formLayout.formContentRegion
@show @contentView
getFormLayout: (options = {}) ->
config = @getDefaultConfig _.result(@contentView, "form")
_.extend config, options
buttons = @getButtons config.buttons
new Form.FormWrapper
config: config
model: @contentView.model
buttons: buttons
getDefaultConfig: (config = {}) ->
_.defaults config,
footer: true
focusFirstInput: true
errors: true
syncing: true
getButtons: (buttons = {}) ->
App.request("form:button:entities", buttons, @contentView.model) unless buttons is false
App.reqres.setHandler "form:wrapper", (contentView, options = {}) ->
throw new Error "No model found inside of form's contentView" unless contentView.model
formController = new Form.Controller
view: contentView
config: options
formController.formLayout | 194354 | #
# WRML - Web Resource Modeling Language
# __ __ ______ __ __ __
# /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \
# \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____
# \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\
# \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/
#
# http://www.wrml.org
#
# Copyright 2011 - 2013 <NAME> (OSS project WRML.org)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# CoffeeScript
@Wrmldoc.module "Components.Form", (Form, App, Backbone, Marionette, $, _) ->
class Form.Controller extends App.Controllers.Base
initialize: (options = {}) ->
@contentView = dataModel.view
@formLayout = @getFormLayout dataModel.config
@listenTo @formLayout, "show", @formContentRegion
@listenTo @formLayout, "form:submit", @formSubmit
@listenTo @formLayout, "form:cancel", @formCancel
formCancel: ->
@contentView.triggerMethod "form:cancel"
formSubmit: ->
data = Backbone.Syphon.serialize @formLayout
if @contentView.triggerMethod("form:submit", data) isnt false
model = @contentView.model
collection = @contentView.collection
@processFormSubmit data, model, collection
processFormSubmit: (data, model, collection) ->
model.save data,
collection: collection
onClose: ->
console.log "onClose", @
formContentRegion: ->
@region = @formLayout.formContentRegion
@show @contentView
getFormLayout: (options = {}) ->
config = @getDefaultConfig _.result(@contentView, "form")
_.extend config, options
buttons = @getButtons config.buttons
new Form.FormWrapper
config: config
model: @contentView.model
buttons: buttons
getDefaultConfig: (config = {}) ->
_.defaults config,
footer: true
focusFirstInput: true
errors: true
syncing: true
getButtons: (buttons = {}) ->
App.request("form:button:entities", buttons, @contentView.model) unless buttons is false
App.reqres.setHandler "form:wrapper", (contentView, options = {}) ->
throw new Error "No model found inside of form's contentView" unless contentView.model
formController = new Form.Controller
view: contentView
config: options
formController.formLayout | true | #
# WRML - Web Resource Modeling Language
# __ __ ______ __ __ __
# /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \
# \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____
# \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\
# \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/
#
# http://www.wrml.org
#
# Copyright 2011 - 2013 PI:NAME:<NAME>END_PI (OSS project WRML.org)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# CoffeeScript
@Wrmldoc.module "Components.Form", (Form, App, Backbone, Marionette, $, _) ->
class Form.Controller extends App.Controllers.Base
initialize: (options = {}) ->
@contentView = dataModel.view
@formLayout = @getFormLayout dataModel.config
@listenTo @formLayout, "show", @formContentRegion
@listenTo @formLayout, "form:submit", @formSubmit
@listenTo @formLayout, "form:cancel", @formCancel
formCancel: ->
@contentView.triggerMethod "form:cancel"
formSubmit: ->
data = Backbone.Syphon.serialize @formLayout
if @contentView.triggerMethod("form:submit", data) isnt false
model = @contentView.model
collection = @contentView.collection
@processFormSubmit data, model, collection
processFormSubmit: (data, model, collection) ->
model.save data,
collection: collection
onClose: ->
console.log "onClose", @
formContentRegion: ->
@region = @formLayout.formContentRegion
@show @contentView
getFormLayout: (options = {}) ->
config = @getDefaultConfig _.result(@contentView, "form")
_.extend config, options
buttons = @getButtons config.buttons
new Form.FormWrapper
config: config
model: @contentView.model
buttons: buttons
getDefaultConfig: (config = {}) ->
_.defaults config,
footer: true
focusFirstInput: true
errors: true
syncing: true
getButtons: (buttons = {}) ->
App.request("form:button:entities", buttons, @contentView.model) unless buttons is false
App.reqres.setHandler "form:wrapper", (contentView, options = {}) ->
throw new Error "No model found inside of form's contentView" unless contentView.model
formController = new Form.Controller
view: contentView
config: options
formController.formLayout |
[
{
"context": "dArguments: [\n pgUser: user\n pgPassword: pass\n ]\n userCallback: (err, result) ->\n if",
"end": 132,
"score": 0.9953998923301697,
"start": 128,
"tag": "PASSWORD",
"value": "pass"
}
] | accounts-pg_client.coffee | Raynes/meteor-accounts-pg | 1 | Meteor.loginWithPg = (user, pass, cb) ->
Accounts.callLoginMethod
methodArguments: [
pgUser: user
pgPassword: pass
]
userCallback: (err, result) ->
if err
cb? and cb(err)
else
cb and cb()
| 100846 | Meteor.loginWithPg = (user, pass, cb) ->
Accounts.callLoginMethod
methodArguments: [
pgUser: user
pgPassword: <PASSWORD>
]
userCallback: (err, result) ->
if err
cb? and cb(err)
else
cb and cb()
| true | Meteor.loginWithPg = (user, pass, cb) ->
Accounts.callLoginMethod
methodArguments: [
pgUser: user
pgPassword: PI:PASSWORD:<PASSWORD>END_PI
]
userCallback: (err, result) ->
if err
cb? and cb(err)
else
cb and cb()
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9983174800872803,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-http-client-race.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
http = require("http")
url = require("url")
body1_s = "1111111111111111"
body2_s = "22222"
server = http.createServer((req, res) ->
body = (if url.parse(req.url).pathname is "/1" then body1_s else body2_s)
res.writeHead 200,
"Content-Type": "text/plain"
"Content-Length": body.length
res.end body
return
)
server.listen common.PORT
body1 = ""
body2 = ""
server.on "listening", ->
req1 = http.request(
port: common.PORT
path: "/1"
)
req1.end()
req1.on "response", (res1) ->
res1.setEncoding "utf8"
res1.on "data", (chunk) ->
body1 += chunk
return
res1.on "end", ->
req2 = http.request(
port: common.PORT
path: "/2"
)
req2.end()
req2.on "response", (res2) ->
res2.setEncoding "utf8"
res2.on "data", (chunk) ->
body2 += chunk
return
res2.on "end", ->
server.close()
return
return
return
return
return
process.on "exit", ->
assert.equal body1_s, body1
assert.equal body2_s, body2
return
| 106248 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
http = require("http")
url = require("url")
body1_s = "1111111111111111"
body2_s = "22222"
server = http.createServer((req, res) ->
body = (if url.parse(req.url).pathname is "/1" then body1_s else body2_s)
res.writeHead 200,
"Content-Type": "text/plain"
"Content-Length": body.length
res.end body
return
)
server.listen common.PORT
body1 = ""
body2 = ""
server.on "listening", ->
req1 = http.request(
port: common.PORT
path: "/1"
)
req1.end()
req1.on "response", (res1) ->
res1.setEncoding "utf8"
res1.on "data", (chunk) ->
body1 += chunk
return
res1.on "end", ->
req2 = http.request(
port: common.PORT
path: "/2"
)
req2.end()
req2.on "response", (res2) ->
res2.setEncoding "utf8"
res2.on "data", (chunk) ->
body2 += chunk
return
res2.on "end", ->
server.close()
return
return
return
return
return
process.on "exit", ->
assert.equal body1_s, body1
assert.equal body2_s, body2
return
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
http = require("http")
url = require("url")
body1_s = "1111111111111111"
body2_s = "22222"
server = http.createServer((req, res) ->
body = (if url.parse(req.url).pathname is "/1" then body1_s else body2_s)
res.writeHead 200,
"Content-Type": "text/plain"
"Content-Length": body.length
res.end body
return
)
server.listen common.PORT
body1 = ""
body2 = ""
server.on "listening", ->
req1 = http.request(
port: common.PORT
path: "/1"
)
req1.end()
req1.on "response", (res1) ->
res1.setEncoding "utf8"
res1.on "data", (chunk) ->
body1 += chunk
return
res1.on "end", ->
req2 = http.request(
port: common.PORT
path: "/2"
)
req2.end()
req2.on "response", (res2) ->
res2.setEncoding "utf8"
res2.on "data", (chunk) ->
body2 += chunk
return
res2.on "end", ->
server.close()
return
return
return
return
return
process.on "exit", ->
assert.equal body1_s, body1
assert.equal body2_s, body2
return
|
[
{
"context": ".inDir DEST\n .withOptions\n realname: 'Octoblu, Inc'\n githubUrl: 'https://github.com/octoblu'\n",
"end": 419,
"score": 0.8886147737503052,
"start": 407,
"tag": "NAME",
"value": "Octoblu, Inc"
},
{
"context": "oblu, Inc'\n githubUrl: 'https://... | test/app.spec.coffee | octoblu/generator-meshblu-core-task-check-whitelist | 0 | path = require 'path'
fs = require 'fs-extra'
helpers = require 'yeoman-test'
assert = require 'yeoman-assert'
TASKNAME = 'do-something'
DEST = path.join __dirname, '..', 'tmp', "meshblu-core-task-#{TASKNAME}"
describe 'do-something', ->
before (done) ->
fs.mkdirsSync DEST
helpers
.run path.join __dirname, '..', 'app'
.inDir DEST
.withOptions
realname: 'Octoblu, Inc'
githubUrl: 'https://github.com/octoblu'
.withPrompts
githubUser: 'octoblu'
taskName: TASKNAME
.on 'end', done
it 'creates expected files', ->
assert.file [
'src/do-something.coffee'
'test/mocha.opts'
'test/do-something-spec.coffee'
'test/test_helper.coffee'
'index.js'
'.gitignore'
'.travis.yml'
'LICENSE'
'README.md'
'package.json'
]
| 78451 | path = require 'path'
fs = require 'fs-extra'
helpers = require 'yeoman-test'
assert = require 'yeoman-assert'
TASKNAME = 'do-something'
DEST = path.join __dirname, '..', 'tmp', "meshblu-core-task-#{TASKNAME}"
describe 'do-something', ->
before (done) ->
fs.mkdirsSync DEST
helpers
.run path.join __dirname, '..', 'app'
.inDir DEST
.withOptions
realname: '<NAME>'
githubUrl: 'https://github.com/octoblu'
.withPrompts
githubUser: 'octoblu'
taskName: TASKNAME
.on 'end', done
it 'creates expected files', ->
assert.file [
'src/do-something.coffee'
'test/mocha.opts'
'test/do-something-spec.coffee'
'test/test_helper.coffee'
'index.js'
'.gitignore'
'.travis.yml'
'LICENSE'
'README.md'
'package.json'
]
| true | path = require 'path'
fs = require 'fs-extra'
helpers = require 'yeoman-test'
assert = require 'yeoman-assert'
TASKNAME = 'do-something'
DEST = path.join __dirname, '..', 'tmp', "meshblu-core-task-#{TASKNAME}"
describe 'do-something', ->
before (done) ->
fs.mkdirsSync DEST
helpers
.run path.join __dirname, '..', 'app'
.inDir DEST
.withOptions
realname: 'PI:NAME:<NAME>END_PI'
githubUrl: 'https://github.com/octoblu'
.withPrompts
githubUser: 'octoblu'
taskName: TASKNAME
.on 'end', done
it 'creates expected files', ->
assert.file [
'src/do-something.coffee'
'test/mocha.opts'
'test/do-something-spec.coffee'
'test/test_helper.coffee'
'index.js'
'.gitignore'
'.travis.yml'
'LICENSE'
'README.md'
'package.json'
]
|
[
{
"context": "##############################################\n#\n# Markus 16/12/2017\n#\n####################################",
"end": 90,
"score": 0.9991677403450012,
"start": 84,
"tag": "NAME",
"value": "Markus"
}
] | client/3_database/modify.coffee | MooqitaSFH/worklearn | 0 | ###############################################################################
#
# Markus 16/12/2017
#
###############################################################################
###############################################################################
@set_field = (collection, document, field, value, verbose=true, callback=null) ->
if typeof collection != "string"
collection = get_collection_name collection
if typeof document != "string"
document = document._id
trace = stack_trace()
if not callback
callback = (err, res) ->
if err
err_msg = "Error saving " + field + ": "
err_msg += err
err_msg += "A stack trace was written to the console."
sAlert.error(err_msg, {timeout: 60000})
console.log "Client method set_field caused server error: "
console.log err
console.log "Client stack trace: "
console.log trace
if res & verbose
silent = false
profile = get_profile()
if profile
silent = profile.silent
if not silent
sAlert.success(field + " saved.")
Meteor.call "set_field", collection, document, field, value, callback
| 13275 | ###############################################################################
#
# <NAME> 16/12/2017
#
###############################################################################
###############################################################################
@set_field = (collection, document, field, value, verbose=true, callback=null) ->
if typeof collection != "string"
collection = get_collection_name collection
if typeof document != "string"
document = document._id
trace = stack_trace()
if not callback
callback = (err, res) ->
if err
err_msg = "Error saving " + field + ": "
err_msg += err
err_msg += "A stack trace was written to the console."
sAlert.error(err_msg, {timeout: 60000})
console.log "Client method set_field caused server error: "
console.log err
console.log "Client stack trace: "
console.log trace
if res & verbose
silent = false
profile = get_profile()
if profile
silent = profile.silent
if not silent
sAlert.success(field + " saved.")
Meteor.call "set_field", collection, document, field, value, callback
| true | ###############################################################################
#
# PI:NAME:<NAME>END_PI 16/12/2017
#
###############################################################################
###############################################################################
@set_field = (collection, document, field, value, verbose=true, callback=null) ->
if typeof collection != "string"
collection = get_collection_name collection
if typeof document != "string"
document = document._id
trace = stack_trace()
if not callback
callback = (err, res) ->
if err
err_msg = "Error saving " + field + ": "
err_msg += err
err_msg += "A stack trace was written to the console."
sAlert.error(err_msg, {timeout: 60000})
console.log "Client method set_field caused server error: "
console.log err
console.log "Client stack trace: "
console.log trace
if res & verbose
silent = false
profile = get_profile()
if profile
silent = profile.silent
if not silent
sAlert.success(field + " saved.")
Meteor.call "set_field", collection, document, field, value, callback
|
[
{
"context": "iguration:\n# None\n#\n# Commands:\n# hubot insult @username - Shows a tastefully insult\n#\n# Author:\n# PiXeL",
"end": 145,
"score": 0.8286787271499634,
"start": 136,
"tag": "USERNAME",
"value": "@username"
},
{
"context": "ername - Shows a tastefully insult\n#\... | src/insult.coffee | PiXeL16/hubot-insults | 2 | # Description:
# Insult your colleages tastefully
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot insult @username - Shows a tastefully insult
#
# Author:
# PiXeL16 <cjimenez16@gmail.com> Chris Jimenez
insults = [
"May the chocolate chips in your cookies always turn out to be raisins.",
"May every sock you wear be slightly rotated, just enough for it to be uncomfortable.",
"May your mother come to talk to you, and then leave your door slightly ajar, so that you have to get up and close it.",
"May your article load that extra little bit as you're about to click a link so you click an ad instead.",
"May both sides of your pillow be warm.",
"May you forever feel your cellphone vibrating in the pocket it's not even in.",
"May you always get up from your computer with your headphones still attached.",
"May your chair produce a sound similar to a fart, but only once, such that you cannot reproduce it to prove that it was just the chair.",
"I don’t believe in plastic surgery, But in your case, Go ahead.",
"People like you are the reason we have middle fingers.",
"Why Don’t You Slip Into Something More Comfortable. Like A Coma?",
"When your mom dropped you off at the school, she got a ticket for littering.",
"Tell me… Is being stupid a profession or are you just gifted?",
"Me pretending to listen should be enough for you.",
"What’s the point of putting on makeup, a monkey is gonna stay a monkey.",
"My mom says pigs don’t eat biscuits… So I better take that one out of your hand.",
"No need for insults, your face says it all.",
"You’re so ugly that when you cry, the tears roll down the back of your head…just to avoid your face.",
"Wow! You have a huge pimple in between your shoulders! Oh wait that’s your face.",
"It’s not that you are weird…it’s just that everyone else is normal.",
"Zombies eat brains. You’re safe.",
"Scientists are trying to figure out how long human can live without a brain. You can tell them your age.",
"Roses are red, violets are blue, I have 5 fingers, the 3rd ones for you.",
"Is your ass jealous of the amount of shit that just came out of your mouth?",
"Your birth certificate is an apology letter from the condom factory.",
"I’m jealous of all the people that haven't met you!",
"I wasn't born with enough middle fingers to let you know how I feel about you.",
"You must have been born on a highway because that's where most accidents happen.",
"If you are going to be two faced, at least make one of them pretty.",
"Yo're so ugly, when your mom dropped you off at school she got a fine for littering.",
"I bet your brain feels as good as new, seeing that you never use it.",
"You bring everyone a lot of joy, when you leave the room.",
"Two wrongs don't make a right, take your parents as an example.",
"I'd like to see things from your point of view but I can't seem to get my head that far up my ass.",
"I could eat a bowl of alphabet soup and shit out a smarter statement than that.",
"If I wanted to kill myself I'd climb your ego and jump to your IQ.",
"If laughter is the best medicine, your face must be curing the world.",
"If you're gonna be a smartass, first you have to be smart. Otherwise you're just an ass.",
"You're so ugly, when you popped out the doctor said Aww what a treasure and your mom said Yeah, lets bury it.",
"I don't exactly hate you, but if you were on fire and I had water, I'd drink it.",
"It's better to let someone think you are an Idiot than to open your mouth and prove it.",
"Shut up, you'll never be the man your mother is.",
"You shouldn't play hide and seek, no one would look for you.",
"The last time I saw a face like yours I fed it a banana.",
"Maybe if you ate some of that makeup you could be pretty on the inside.",
"Hey, you have somthing on your chin... no, the 3rd one down",
"http://i.imgur.com/9IZACjN.jpg",
"http://i.imgur.com/ftc2h0p.jpg",
"http://i.imgur.com/QEb2GaS.jpg",
"http://i.imgur.com/LHQ5FXf.jpg",
"http://i.imgur.com/rNW9J0D.jpg",
"http://i.imgur.com/D6SpawO.jpg",
"I'd slap you, but shit stains.",
"If I were to slap you, it would be considered animal abuse!",
"Why don't you slip into something more comfortable -- like a coma.",
"I have neither the time nor the crayons to explain this to you.",
"You look like something I'd draw with my left hand.",
"If you really want to know about mistakes, you should ask your parents.",
"What are you doing here? Did someone leave your cage open?",
"You're not funny, but your life, now that's a joke.",
"You're as useless as a knitted condom.",
"Oh my God, look at you. Was anyone else hurt in the accident?",
"You're so fat, you could sell shade.",
"You're as bright as a black hole, and twice as dense.",
"You're so ugly, when you got robbed, the robbers made you wear their masks.",
"You are proof that evolution CAN go in reverse.",
"Do you still love nature, despite what it did to you?",
"You're so ugly, the only dates you get are on a calendar.",
"Shock me, say something intelligent.",
"Learn from your parents' mistakes - use birth control!",
"http://i.imgur.com/slGGjh9.png",
"http://i.imgur.com/ijuqlp7.png",
"http://i.imgur.com/riHJxSx.png",
"http://i.imgur.com/21vNjxl.png",
"http://i.imgur.com/XlMRGDE.png",
"http://i.imgur.com/y9iuoKk.png",
"http://i.imgur.com/zmU7RBF.png",
"http://i.imgur.com/nrLtb7S.png",
"http://i.imgur.com/m0U288v.gif",
"http://i.imgur.com/W5LGPj7.gif",
"http://i.imgur.com/GZfjPDH.gif",
"http://i.imgur.com/TM0qYRi.gif",
"http://i.imgur.com/dUb0C1V.gif",
"http://i.imgur.com/WFdLzo9.gif",
"http://i.imgur.com/doE0ChC.gif",
"http://i.imgur.com/Jal12NU.gif",
"http://i.imgur.com/SOEQQ6m.gif",
"http://i.imgur.com/OJkjPnP.gif",
"http://i.imgur.com/CjTPuvh.gif",
"http://i.imgur.com/5cpGsja.gif",
"http://i.imgur.com/23J4RqC.gif",
"http://i.imgur.com/m7qUTLq.gif",
"http://i.imgur.com/qwk5kKT.gif",
"http://i.imgur.com/6b9OqaI.gif",
"http://i.imgur.com/mcL83zN.gif",
"http://i.imgur.com/bwzg7nr.gif",
"http://i.imgur.com/H92PB5P.gif",
"http://i.imgur.com/8sqhwOg.gif",
"http://i.imgur.com/WPGwXHq.gif",
"http://i.imgur.com/cOVQQq6.gif",
"http://cdn.emgn.com/wp-content/uploads/2015/01/Rude-Animal-Facts-EMGN1.png",
"http://cdn.emgn.com/wp-content/uploads/2015/01/Rude-Animal-Facts-EMGN2.png",
"http://cdn.emgn.com/wp-content/uploads/2015/01/Rude-Animal-Facts-EMGN4.png",
"http://cdn.emgn.com/wp-content/uploads/2015/01/Rude-Animal-Facts-EMGN5.png",
"http://cdn.emgn.com/wp-content/uploads/2015/01/Rude-Animal-Facts-EMGN6.jpg",
"http://i.imgur.com/dMDdQOI.gif",
"http://i.imgur.com/4PhyZKv.gif",
"http://i.imgur.com/6OGiTqc.gif",
"http://i.imgur.com/WtDpHiL.gif",
"http://i.imgur.com/7PIIlI7.gif",
"http://replygif.net/i/186.gif",
"http://i.imgur.com/TLDBTeV.gif",
"http://i.imgur.com/HegZkkc.gif",
"http://i.imgur.com/clcdkfP.gif",
"http://i.imgur.com/c5yeWVx.gif",
"http://i.imgur.com/IG4Evs9.gif",
"http://i.imgur.com/VJCWcnK.gif",
"http://i.imgur.com/QFrk1X5.gif",
"http://i.imgur.com/kXGUKwD.gif",
"http://i.imgur.com/Jnit9mq.gif",
"http://i.imgur.com/iQjNakW.gif",
"http://i.imgur.com/5Zfltup.gif",
"http://i.imgur.com/OdYTqoB.gif",
"http://i.imgur.com/LCy4zVv.gif",
"http://i.imgur.com/DZ64Fu7.gif",
"http://i.imgur.com/DAzfQh6.gif",
"http://i.imgur.com/R8Ou2cj.gif",
]
module.exports = (robot) ->
robot.hear /insult/i, (msg) ->
msg.send msg.random insults
| 16195 | # Description:
# Insult your colleages tastefully
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot insult @username - Shows a tastefully insult
#
# Author:
# PiXeL16 <<EMAIL>> <NAME>
insults = [
"May the chocolate chips in your cookies always turn out to be raisins.",
"May every sock you wear be slightly rotated, just enough for it to be uncomfortable.",
"May your mother come to talk to you, and then leave your door slightly ajar, so that you have to get up and close it.",
"May your article load that extra little bit as you're about to click a link so you click an ad instead.",
"May both sides of your pillow be warm.",
"May you forever feel your cellphone vibrating in the pocket it's not even in.",
"May you always get up from your computer with your headphones still attached.",
"May your chair produce a sound similar to a fart, but only once, such that you cannot reproduce it to prove that it was just the chair.",
"I don’t believe in plastic surgery, But in your case, Go ahead.",
"People like you are the reason we have middle fingers.",
"Why Don’t You Slip Into Something More Comfortable. Like A Coma?",
"When your mom dropped you off at the school, she got a ticket for littering.",
"Tell me… Is being stupid a profession or are you just gifted?",
"Me pretending to listen should be enough for you.",
"What’s the point of putting on makeup, a monkey is gonna stay a monkey.",
"My mom says pigs don’t eat biscuits… So I better take that one out of your hand.",
"No need for insults, your face says it all.",
"You’re so ugly that when you cry, the tears roll down the back of your head…just to avoid your face.",
"Wow! You have a huge pimple in between your shoulders! Oh wait that’s your face.",
"It’s not that you are weird…it’s just that everyone else is normal.",
"Zombies eat brains. You’re safe.",
"Scientists are trying to figure out how long human can live without a brain. You can tell them your age.",
"Roses are red, violets are blue, I have 5 fingers, the 3rd ones for you.",
"Is your ass jealous of the amount of shit that just came out of your mouth?",
"Your birth certificate is an apology letter from the condom factory.",
"I’m jealous of all the people that haven't met you!",
"I wasn't born with enough middle fingers to let you know how I feel about you.",
"You must have been born on a highway because that's where most accidents happen.",
"If you are going to be two faced, at least make one of them pretty.",
"Yo're so ugly, when your mom dropped you off at school she got a fine for littering.",
"I bet your brain feels as good as new, seeing that you never use it.",
"You bring everyone a lot of joy, when you leave the room.",
"Two wrongs don't make a right, take your parents as an example.",
"I'd like to see things from your point of view but I can't seem to get my head that far up my ass.",
"I could eat a bowl of alphabet soup and shit out a smarter statement than that.",
"If I wanted to kill myself I'd climb your ego and jump to your IQ.",
"If laughter is the best medicine, your face must be curing the world.",
"If you're gonna be a smartass, first you have to be smart. Otherwise you're just an ass.",
"You're so ugly, when you popped out the doctor said Aww what a treasure and your mom said Yeah, lets bury it.",
"I don't exactly hate you, but if you were on fire and I had water, I'd drink it.",
"It's better to let someone think you are an Idiot than to open your mouth and prove it.",
"Shut up, you'll never be the man your mother is.",
"You shouldn't play hide and seek, no one would look for you.",
"The last time I saw a face like yours I fed it a banana.",
"Maybe if you ate some of that makeup you could be pretty on the inside.",
"Hey, you have somthing on your chin... no, the 3rd one down",
"http://i.imgur.com/9IZACjN.jpg",
"http://i.imgur.com/ftc2h0p.jpg",
"http://i.imgur.com/QEb2GaS.jpg",
"http://i.imgur.com/LHQ5FXf.jpg",
"http://i.imgur.com/rNW9J0D.jpg",
"http://i.imgur.com/D6SpawO.jpg",
"I'd slap you, but shit stains.",
"If I were to slap you, it would be considered animal abuse!",
"Why don't you slip into something more comfortable -- like a coma.",
"I have neither the time nor the crayons to explain this to you.",
"You look like something I'd draw with my left hand.",
"If you really want to know about mistakes, you should ask your parents.",
"What are you doing here? Did someone leave your cage open?",
"You're not funny, but your life, now that's a joke.",
"You're as useless as a knitted condom.",
"Oh my God, look at you. Was anyone else hurt in the accident?",
"You're so fat, you could sell shade.",
"You're as bright as a black hole, and twice as dense.",
"You're so ugly, when you got robbed, the robbers made you wear their masks.",
"You are proof that evolution CAN go in reverse.",
"Do you still love nature, despite what it did to you?",
"You're so ugly, the only dates you get are on a calendar.",
"Shock me, say something intelligent.",
"Learn from your parents' mistakes - use birth control!",
"http://i.imgur.com/slGGjh9.png",
"http://i.imgur.com/ijuqlp7.png",
"http://i.imgur.com/riHJxSx.png",
"http://i.imgur.com/21vNjxl.png",
"http://i.imgur.com/XlMRGDE.png",
"http://i.imgur.com/y9iuoKk.png",
"http://i.imgur.com/zmU7RBF.png",
"http://i.imgur.com/nrLtb7S.png",
"http://i.imgur.com/m0U288v.gif",
"http://i.imgur.com/W5LGPj7.gif",
"http://i.imgur.com/GZfjPDH.gif",
"http://i.imgur.com/TM0qYRi.gif",
"http://i.imgur.com/dUb0C1V.gif",
"http://i.imgur.com/WFdLzo9.gif",
"http://i.imgur.com/doE0ChC.gif",
"http://i.imgur.com/Jal12NU.gif",
"http://i.imgur.com/SOEQQ6m.gif",
"http://i.imgur.com/OJkjPnP.gif",
"http://i.imgur.com/CjTPuvh.gif",
"http://i.imgur.com/5cpGsja.gif",
"http://i.imgur.com/23J4RqC.gif",
"http://i.imgur.com/m7qUTLq.gif",
"http://i.imgur.com/qwk5kKT.gif",
"http://i.imgur.com/6b9OqaI.gif",
"http://i.imgur.com/mcL83zN.gif",
"http://i.imgur.com/bwzg7nr.gif",
"http://i.imgur.com/H92PB5P.gif",
"http://i.imgur.com/8sqhwOg.gif",
"http://i.imgur.com/WPGwXHq.gif",
"http://i.imgur.com/cOVQQq6.gif",
"http://cdn.emgn.com/wp-content/uploads/2015/01/Rude-Animal-Facts-EMGN1.png",
"http://cdn.emgn.com/wp-content/uploads/2015/01/Rude-Animal-Facts-EMGN2.png",
"http://cdn.emgn.com/wp-content/uploads/2015/01/Rude-Animal-Facts-EMGN4.png",
"http://cdn.emgn.com/wp-content/uploads/2015/01/Rude-Animal-Facts-EMGN5.png",
"http://cdn.emgn.com/wp-content/uploads/2015/01/Rude-Animal-Facts-EMGN6.jpg",
"http://i.imgur.com/dMDdQOI.gif",
"http://i.imgur.com/4PhyZKv.gif",
"http://i.imgur.com/6OGiTqc.gif",
"http://i.imgur.com/WtDpHiL.gif",
"http://i.imgur.com/7PIIlI7.gif",
"http://replygif.net/i/186.gif",
"http://i.imgur.com/TLDBTeV.gif",
"http://i.imgur.com/HegZkkc.gif",
"http://i.imgur.com/clcdkfP.gif",
"http://i.imgur.com/c5yeWVx.gif",
"http://i.imgur.com/IG4Evs9.gif",
"http://i.imgur.com/VJCWcnK.gif",
"http://i.imgur.com/QFrk1X5.gif",
"http://i.imgur.com/kXGUKwD.gif",
"http://i.imgur.com/Jnit9mq.gif",
"http://i.imgur.com/iQjNakW.gif",
"http://i.imgur.com/5Zfltup.gif",
"http://i.imgur.com/OdYTqoB.gif",
"http://i.imgur.com/LCy4zVv.gif",
"http://i.imgur.com/DZ64Fu7.gif",
"http://i.imgur.com/DAzfQh6.gif",
"http://i.imgur.com/R8Ou2cj.gif",
]
module.exports = (robot) ->
robot.hear /insult/i, (msg) ->
msg.send msg.random insults
| true | # Description:
# Insult your colleages tastefully
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot insult @username - Shows a tastefully insult
#
# Author:
# PiXeL16 <PI:EMAIL:<EMAIL>END_PI> PI:NAME:<NAME>END_PI
insults = [
"May the chocolate chips in your cookies always turn out to be raisins.",
"May every sock you wear be slightly rotated, just enough for it to be uncomfortable.",
"May your mother come to talk to you, and then leave your door slightly ajar, so that you have to get up and close it.",
"May your article load that extra little bit as you're about to click a link so you click an ad instead.",
"May both sides of your pillow be warm.",
"May you forever feel your cellphone vibrating in the pocket it's not even in.",
"May you always get up from your computer with your headphones still attached.",
"May your chair produce a sound similar to a fart, but only once, such that you cannot reproduce it to prove that it was just the chair.",
"I don’t believe in plastic surgery, But in your case, Go ahead.",
"People like you are the reason we have middle fingers.",
"Why Don’t You Slip Into Something More Comfortable. Like A Coma?",
"When your mom dropped you off at the school, she got a ticket for littering.",
"Tell me… Is being stupid a profession or are you just gifted?",
"Me pretending to listen should be enough for you.",
"What’s the point of putting on makeup, a monkey is gonna stay a monkey.",
"My mom says pigs don’t eat biscuits… So I better take that one out of your hand.",
"No need for insults, your face says it all.",
"You’re so ugly that when you cry, the tears roll down the back of your head…just to avoid your face.",
"Wow! You have a huge pimple in between your shoulders! Oh wait that’s your face.",
"It’s not that you are weird…it’s just that everyone else is normal.",
"Zombies eat brains. You’re safe.",
"Scientists are trying to figure out how long human can live without a brain. You can tell them your age.",
"Roses are red, violets are blue, I have 5 fingers, the 3rd ones for you.",
"Is your ass jealous of the amount of shit that just came out of your mouth?",
"Your birth certificate is an apology letter from the condom factory.",
"I’m jealous of all the people that haven't met you!",
"I wasn't born with enough middle fingers to let you know how I feel about you.",
"You must have been born on a highway because that's where most accidents happen.",
"If you are going to be two faced, at least make one of them pretty.",
"Yo're so ugly, when your mom dropped you off at school she got a fine for littering.",
"I bet your brain feels as good as new, seeing that you never use it.",
"You bring everyone a lot of joy, when you leave the room.",
"Two wrongs don't make a right, take your parents as an example.",
"I'd like to see things from your point of view but I can't seem to get my head that far up my ass.",
"I could eat a bowl of alphabet soup and shit out a smarter statement than that.",
"If I wanted to kill myself I'd climb your ego and jump to your IQ.",
"If laughter is the best medicine, your face must be curing the world.",
"If you're gonna be a smartass, first you have to be smart. Otherwise you're just an ass.",
"You're so ugly, when you popped out the doctor said Aww what a treasure and your mom said Yeah, lets bury it.",
"I don't exactly hate you, but if you were on fire and I had water, I'd drink it.",
"It's better to let someone think you are an Idiot than to open your mouth and prove it.",
"Shut up, you'll never be the man your mother is.",
"You shouldn't play hide and seek, no one would look for you.",
"The last time I saw a face like yours I fed it a banana.",
"Maybe if you ate some of that makeup you could be pretty on the inside.",
"Hey, you have somthing on your chin... no, the 3rd one down",
"http://i.imgur.com/9IZACjN.jpg",
"http://i.imgur.com/ftc2h0p.jpg",
"http://i.imgur.com/QEb2GaS.jpg",
"http://i.imgur.com/LHQ5FXf.jpg",
"http://i.imgur.com/rNW9J0D.jpg",
"http://i.imgur.com/D6SpawO.jpg",
"I'd slap you, but shit stains.",
"If I were to slap you, it would be considered animal abuse!",
"Why don't you slip into something more comfortable -- like a coma.",
"I have neither the time nor the crayons to explain this to you.",
"You look like something I'd draw with my left hand.",
"If you really want to know about mistakes, you should ask your parents.",
"What are you doing here? Did someone leave your cage open?",
"You're not funny, but your life, now that's a joke.",
"You're as useless as a knitted condom.",
"Oh my God, look at you. Was anyone else hurt in the accident?",
"You're so fat, you could sell shade.",
"You're as bright as a black hole, and twice as dense.",
"You're so ugly, when you got robbed, the robbers made you wear their masks.",
"You are proof that evolution CAN go in reverse.",
"Do you still love nature, despite what it did to you?",
"You're so ugly, the only dates you get are on a calendar.",
"Shock me, say something intelligent.",
"Learn from your parents' mistakes - use birth control!",
"http://i.imgur.com/slGGjh9.png",
"http://i.imgur.com/ijuqlp7.png",
"http://i.imgur.com/riHJxSx.png",
"http://i.imgur.com/21vNjxl.png",
"http://i.imgur.com/XlMRGDE.png",
"http://i.imgur.com/y9iuoKk.png",
"http://i.imgur.com/zmU7RBF.png",
"http://i.imgur.com/nrLtb7S.png",
"http://i.imgur.com/m0U288v.gif",
"http://i.imgur.com/W5LGPj7.gif",
"http://i.imgur.com/GZfjPDH.gif",
"http://i.imgur.com/TM0qYRi.gif",
"http://i.imgur.com/dUb0C1V.gif",
"http://i.imgur.com/WFdLzo9.gif",
"http://i.imgur.com/doE0ChC.gif",
"http://i.imgur.com/Jal12NU.gif",
"http://i.imgur.com/SOEQQ6m.gif",
"http://i.imgur.com/OJkjPnP.gif",
"http://i.imgur.com/CjTPuvh.gif",
"http://i.imgur.com/5cpGsja.gif",
"http://i.imgur.com/23J4RqC.gif",
"http://i.imgur.com/m7qUTLq.gif",
"http://i.imgur.com/qwk5kKT.gif",
"http://i.imgur.com/6b9OqaI.gif",
"http://i.imgur.com/mcL83zN.gif",
"http://i.imgur.com/bwzg7nr.gif",
"http://i.imgur.com/H92PB5P.gif",
"http://i.imgur.com/8sqhwOg.gif",
"http://i.imgur.com/WPGwXHq.gif",
"http://i.imgur.com/cOVQQq6.gif",
"http://cdn.emgn.com/wp-content/uploads/2015/01/Rude-Animal-Facts-EMGN1.png",
"http://cdn.emgn.com/wp-content/uploads/2015/01/Rude-Animal-Facts-EMGN2.png",
"http://cdn.emgn.com/wp-content/uploads/2015/01/Rude-Animal-Facts-EMGN4.png",
"http://cdn.emgn.com/wp-content/uploads/2015/01/Rude-Animal-Facts-EMGN5.png",
"http://cdn.emgn.com/wp-content/uploads/2015/01/Rude-Animal-Facts-EMGN6.jpg",
"http://i.imgur.com/dMDdQOI.gif",
"http://i.imgur.com/4PhyZKv.gif",
"http://i.imgur.com/6OGiTqc.gif",
"http://i.imgur.com/WtDpHiL.gif",
"http://i.imgur.com/7PIIlI7.gif",
"http://replygif.net/i/186.gif",
"http://i.imgur.com/TLDBTeV.gif",
"http://i.imgur.com/HegZkkc.gif",
"http://i.imgur.com/clcdkfP.gif",
"http://i.imgur.com/c5yeWVx.gif",
"http://i.imgur.com/IG4Evs9.gif",
"http://i.imgur.com/VJCWcnK.gif",
"http://i.imgur.com/QFrk1X5.gif",
"http://i.imgur.com/kXGUKwD.gif",
"http://i.imgur.com/Jnit9mq.gif",
"http://i.imgur.com/iQjNakW.gif",
"http://i.imgur.com/5Zfltup.gif",
"http://i.imgur.com/OdYTqoB.gif",
"http://i.imgur.com/LCy4zVv.gif",
"http://i.imgur.com/DZ64Fu7.gif",
"http://i.imgur.com/DAzfQh6.gif",
"http://i.imgur.com/R8Ou2cj.gif",
]
module.exports = (robot) ->
robot.hear /insult/i, (msg) ->
msg.send msg.random insults
|
[
{
"context": "or = (out, color) ->\n rgb = color.rgb\n key = rgb.join \"_\"\n if out[key]\n out[key].count++\n else\n ",
"end": 363,
"score": 0.975904643535614,
"start": 351,
"tag": "KEY",
"value": "rgb.join \"_\""
}
] | src/public/lib/editor/cssstats.coffee | tonistiigi/styler | 18 | define (require, exports, module) ->
hex2rgba = (hex) ->
hex = hex.substr 1
if hex.length == 3
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]
[ parseInt (hex.substr 0, 2), 16
parseInt (hex.substr 2, 2), 16
parseInt (hex.substr 4, 2), 16
1 ]
addColor = (out, color) ->
rgb = color.rgb
key = rgb.join "_"
if out[key]
out[key].count++
else
out[key] = count:1, rgb:color.rgb, hex:color.hex
exports.getStats = (data) ->
out = colors:{}, fonts:{}
hexcolors = data.match /(#[0-9a-f]{3}|#[0-9a-f]{6})\b/ig
if hexcolors
for hex in hexcolors
addColor out.colors, hex:hex.toLowerCase(), rgb:hex2rgba hex
rgbcolors = data.match /rgba?\s*\([0-9\.,\s%]{5,}\)/ig
if rgbcolors
for rgbcolor in rgbcolors
components = rgbcolor.match /[0-9\.\s]+%?/
if components.length==3 or components.length==4
color = []
for component,i in components
value = parseFloat component.match /[0-9\.]+/
ispercentage = -1 != component.indexOf "%"
value *= 2.55 if ispercentage
color.push if i < 3 then Math.round(value) else value
if color.length < 4
color.push 1
addColor out.colors, rgb:color
colors = []
for key, color of out.colors
colors.push color
out.colors = colors
fontregexp = /font-family\s*:\s*.*?(;|\n)/ig
fontregexp2 = /font-family\s*:\s*(.*?)(;|\n)/i
fontfamilys = data.match fontregexp
if fontfamilys
for fontfamily in fontfamilys
value = (fontfamily.match fontregexp2)[1]
continue unless value
parts = value.split ","
for part,i in parts
part = part.trim()
if part[0] in "'\"" and part[-1..][0] in "'\""
part = part.substr 1, part.length - 2
part = part.replace /['"]/g, ""
continue if part in ["monospace", "serif", "sans-serif", "cursive", "fantasy"] #better not to count generic-family (i think?)
if out.fonts[part]
out.fonts[part]++
else
out.fonts[part] = 1
fonts = []
for name, count of out.fonts
fonts.push name:name, count:count
out.fonts = fonts
out
| 146124 | define (require, exports, module) ->
hex2rgba = (hex) ->
hex = hex.substr 1
if hex.length == 3
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]
[ parseInt (hex.substr 0, 2), 16
parseInt (hex.substr 2, 2), 16
parseInt (hex.substr 4, 2), 16
1 ]
addColor = (out, color) ->
rgb = color.rgb
key = <KEY>
if out[key]
out[key].count++
else
out[key] = count:1, rgb:color.rgb, hex:color.hex
exports.getStats = (data) ->
out = colors:{}, fonts:{}
hexcolors = data.match /(#[0-9a-f]{3}|#[0-9a-f]{6})\b/ig
if hexcolors
for hex in hexcolors
addColor out.colors, hex:hex.toLowerCase(), rgb:hex2rgba hex
rgbcolors = data.match /rgba?\s*\([0-9\.,\s%]{5,}\)/ig
if rgbcolors
for rgbcolor in rgbcolors
components = rgbcolor.match /[0-9\.\s]+%?/
if components.length==3 or components.length==4
color = []
for component,i in components
value = parseFloat component.match /[0-9\.]+/
ispercentage = -1 != component.indexOf "%"
value *= 2.55 if ispercentage
color.push if i < 3 then Math.round(value) else value
if color.length < 4
color.push 1
addColor out.colors, rgb:color
colors = []
for key, color of out.colors
colors.push color
out.colors = colors
fontregexp = /font-family\s*:\s*.*?(;|\n)/ig
fontregexp2 = /font-family\s*:\s*(.*?)(;|\n)/i
fontfamilys = data.match fontregexp
if fontfamilys
for fontfamily in fontfamilys
value = (fontfamily.match fontregexp2)[1]
continue unless value
parts = value.split ","
for part,i in parts
part = part.trim()
if part[0] in "'\"" and part[-1..][0] in "'\""
part = part.substr 1, part.length - 2
part = part.replace /['"]/g, ""
continue if part in ["monospace", "serif", "sans-serif", "cursive", "fantasy"] #better not to count generic-family (i think?)
if out.fonts[part]
out.fonts[part]++
else
out.fonts[part] = 1
fonts = []
for name, count of out.fonts
fonts.push name:name, count:count
out.fonts = fonts
out
| true | define (require, exports, module) ->
hex2rgba = (hex) ->
hex = hex.substr 1
if hex.length == 3
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]
[ parseInt (hex.substr 0, 2), 16
parseInt (hex.substr 2, 2), 16
parseInt (hex.substr 4, 2), 16
1 ]
addColor = (out, color) ->
rgb = color.rgb
key = PI:KEY:<KEY>END_PI
if out[key]
out[key].count++
else
out[key] = count:1, rgb:color.rgb, hex:color.hex
exports.getStats = (data) ->
out = colors:{}, fonts:{}
hexcolors = data.match /(#[0-9a-f]{3}|#[0-9a-f]{6})\b/ig
if hexcolors
for hex in hexcolors
addColor out.colors, hex:hex.toLowerCase(), rgb:hex2rgba hex
rgbcolors = data.match /rgba?\s*\([0-9\.,\s%]{5,}\)/ig
if rgbcolors
for rgbcolor in rgbcolors
components = rgbcolor.match /[0-9\.\s]+%?/
if components.length==3 or components.length==4
color = []
for component,i in components
value = parseFloat component.match /[0-9\.]+/
ispercentage = -1 != component.indexOf "%"
value *= 2.55 if ispercentage
color.push if i < 3 then Math.round(value) else value
if color.length < 4
color.push 1
addColor out.colors, rgb:color
colors = []
for key, color of out.colors
colors.push color
out.colors = colors
fontregexp = /font-family\s*:\s*.*?(;|\n)/ig
fontregexp2 = /font-family\s*:\s*(.*?)(;|\n)/i
fontfamilys = data.match fontregexp
if fontfamilys
for fontfamily in fontfamilys
value = (fontfamily.match fontregexp2)[1]
continue unless value
parts = value.split ","
for part,i in parts
part = part.trim()
if part[0] in "'\"" and part[-1..][0] in "'\""
part = part.substr 1, part.length - 2
part = part.replace /['"]/g, ""
continue if part in ["monospace", "serif", "sans-serif", "cursive", "fantasy"] #better not to count generic-family (i think?)
if out.fonts[part]
out.fonts[part]++
else
out.fonts[part] = 1
fonts = []
for name, count of out.fonts
fonts.push name:name, count:count
out.fonts = fonts
out
|
[
{
"context": "eoverview Tests for no-self-assign rule.\n# @author Toru Nagashima\n###\n\n'use strict'\n\n#-----------------------------",
"end": 76,
"score": 0.9998593926429749,
"start": 62,
"tag": "NAME",
"value": "Toru Nagashima"
}
] | src/tests/rules/no-self-assign.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for no-self-assign rule.
# @author Toru Nagashima
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-self-assign'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-self-assign', rule,
valid: [
'a = a'
'a = b'
'a += a'
'a = +a'
'a = [a]'
'[a] = a'
'[a = 1] = [a]'
'[a, b] = [b, a]'
'[a,, b] = [, b, a]'
'[x, a] = [...x, a]'
'[a, b] = {a, b}'
'({a} = a)'
'({a = 1} = {a})'
'({a: b} = {a})'
'({a} = {a: b})'
'({a} = {a: ->})'
'({a} = {[a]: a})'
'({a, ...b} = {a, ...b})'
,
code: 'a.b = a.c', options: [props: yes]
,
code: 'a.b = c.b', options: [props: yes]
,
code: 'a.b = a[b]', options: [props: yes]
,
code: 'a[b] = a.b', options: [props: yes]
,
code: 'a.b().c = a.b().c', options: [props: yes]
,
code: 'b().c = b().c', options: [props: yes]
,
code: 'a[b + 1] = a[b + 1]', options: [props: yes] # it ignores non-simple computed properties.
,
code: 'a.b = a.b'
options: [props: no]
,
code: 'a.b.c = a.b.c'
options: [props: no]
,
code: 'a[b] = a[b]'
options: [props: no]
,
code: "a['b'] = a['b']"
options: [props: no]
]
invalid: [
code: '''
a = null
a = a
'''
errors: ["'a' is assigned to itself."]
,
code: '[a] = [a]'
errors: ["'a' is assigned to itself."]
,
code: '[a, b] = [a, b]'
errors: ["'a' is assigned to itself.", "'b' is assigned to itself."]
,
code: '[a, b] = [a, c]'
errors: ["'a' is assigned to itself."]
,
code: '[a, b] = [, b]'
errors: ["'b' is assigned to itself."]
,
code: '[a, ...b] = [a, ...b]'
errors: ["'a' is assigned to itself.", "'b' is assigned to itself."]
,
code: '[[a], {b}] = [[a], {b}]'
errors: ["'a' is assigned to itself.", "'b' is assigned to itself."]
,
code: '({a} = {a})'
errors: ["'a' is assigned to itself."]
,
code: '({a: b} = {a: b})'
errors: ["'b' is assigned to itself."]
,
code: '({a, b} = {a, b})'
errors: ["'a' is assigned to itself.", "'b' is assigned to itself."]
,
code: '({a, b} = {b, a})'
errors: ["'b' is assigned to itself.", "'a' is assigned to itself."]
,
code: '({a, b} = {c, a})'
errors: ["'a' is assigned to itself."]
,
code: '({a: {b}, c: [d]} = {a: {b}, c: [d]})'
errors: ["'b' is assigned to itself.", "'d' is assigned to itself."]
,
code: '({a, b} = {a, ...x, b})'
errors: ["'b' is assigned to itself."]
,
code: 'a.b = a.b'
errors: ["'a.b' is assigned to itself."]
,
code: 'a.b.c = a.b.c'
errors: ["'a.b.c' is assigned to itself."]
,
code: 'a[b] = a[b]'
errors: ["'a[b]' is assigned to itself."]
,
code: "a['b'] = a['b']"
errors: ["'a['b']' is assigned to itself."]
,
code: 'a.b = a.b'
options: [props: yes]
errors: ["'a.b' is assigned to itself."]
,
code: 'a.b.c = a.b.c'
options: [props: yes]
errors: ["'a.b.c' is assigned to itself."]
,
code: 'a[b] = a[b]'
options: [props: yes]
errors: ["'a[b]' is assigned to itself."]
,
code: "a['b'] = a['b']"
options: [props: yes]
errors: ["'a['b']' is assigned to itself."]
]
| 68745 | ###*
# @fileoverview Tests for no-self-assign rule.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-self-assign'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-self-assign', rule,
valid: [
'a = a'
'a = b'
'a += a'
'a = +a'
'a = [a]'
'[a] = a'
'[a = 1] = [a]'
'[a, b] = [b, a]'
'[a,, b] = [, b, a]'
'[x, a] = [...x, a]'
'[a, b] = {a, b}'
'({a} = a)'
'({a = 1} = {a})'
'({a: b} = {a})'
'({a} = {a: b})'
'({a} = {a: ->})'
'({a} = {[a]: a})'
'({a, ...b} = {a, ...b})'
,
code: 'a.b = a.c', options: [props: yes]
,
code: 'a.b = c.b', options: [props: yes]
,
code: 'a.b = a[b]', options: [props: yes]
,
code: 'a[b] = a.b', options: [props: yes]
,
code: 'a.b().c = a.b().c', options: [props: yes]
,
code: 'b().c = b().c', options: [props: yes]
,
code: 'a[b + 1] = a[b + 1]', options: [props: yes] # it ignores non-simple computed properties.
,
code: 'a.b = a.b'
options: [props: no]
,
code: 'a.b.c = a.b.c'
options: [props: no]
,
code: 'a[b] = a[b]'
options: [props: no]
,
code: "a['b'] = a['b']"
options: [props: no]
]
invalid: [
code: '''
a = null
a = a
'''
errors: ["'a' is assigned to itself."]
,
code: '[a] = [a]'
errors: ["'a' is assigned to itself."]
,
code: '[a, b] = [a, b]'
errors: ["'a' is assigned to itself.", "'b' is assigned to itself."]
,
code: '[a, b] = [a, c]'
errors: ["'a' is assigned to itself."]
,
code: '[a, b] = [, b]'
errors: ["'b' is assigned to itself."]
,
code: '[a, ...b] = [a, ...b]'
errors: ["'a' is assigned to itself.", "'b' is assigned to itself."]
,
code: '[[a], {b}] = [[a], {b}]'
errors: ["'a' is assigned to itself.", "'b' is assigned to itself."]
,
code: '({a} = {a})'
errors: ["'a' is assigned to itself."]
,
code: '({a: b} = {a: b})'
errors: ["'b' is assigned to itself."]
,
code: '({a, b} = {a, b})'
errors: ["'a' is assigned to itself.", "'b' is assigned to itself."]
,
code: '({a, b} = {b, a})'
errors: ["'b' is assigned to itself.", "'a' is assigned to itself."]
,
code: '({a, b} = {c, a})'
errors: ["'a' is assigned to itself."]
,
code: '({a: {b}, c: [d]} = {a: {b}, c: [d]})'
errors: ["'b' is assigned to itself.", "'d' is assigned to itself."]
,
code: '({a, b} = {a, ...x, b})'
errors: ["'b' is assigned to itself."]
,
code: 'a.b = a.b'
errors: ["'a.b' is assigned to itself."]
,
code: 'a.b.c = a.b.c'
errors: ["'a.b.c' is assigned to itself."]
,
code: 'a[b] = a[b]'
errors: ["'a[b]' is assigned to itself."]
,
code: "a['b'] = a['b']"
errors: ["'a['b']' is assigned to itself."]
,
code: 'a.b = a.b'
options: [props: yes]
errors: ["'a.b' is assigned to itself."]
,
code: 'a.b.c = a.b.c'
options: [props: yes]
errors: ["'a.b.c' is assigned to itself."]
,
code: 'a[b] = a[b]'
options: [props: yes]
errors: ["'a[b]' is assigned to itself."]
,
code: "a['b'] = a['b']"
options: [props: yes]
errors: ["'a['b']' is assigned to itself."]
]
| true | ###*
# @fileoverview Tests for no-self-assign rule.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-self-assign'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-self-assign', rule,
valid: [
'a = a'
'a = b'
'a += a'
'a = +a'
'a = [a]'
'[a] = a'
'[a = 1] = [a]'
'[a, b] = [b, a]'
'[a,, b] = [, b, a]'
'[x, a] = [...x, a]'
'[a, b] = {a, b}'
'({a} = a)'
'({a = 1} = {a})'
'({a: b} = {a})'
'({a} = {a: b})'
'({a} = {a: ->})'
'({a} = {[a]: a})'
'({a, ...b} = {a, ...b})'
,
code: 'a.b = a.c', options: [props: yes]
,
code: 'a.b = c.b', options: [props: yes]
,
code: 'a.b = a[b]', options: [props: yes]
,
code: 'a[b] = a.b', options: [props: yes]
,
code: 'a.b().c = a.b().c', options: [props: yes]
,
code: 'b().c = b().c', options: [props: yes]
,
code: 'a[b + 1] = a[b + 1]', options: [props: yes] # it ignores non-simple computed properties.
,
code: 'a.b = a.b'
options: [props: no]
,
code: 'a.b.c = a.b.c'
options: [props: no]
,
code: 'a[b] = a[b]'
options: [props: no]
,
code: "a['b'] = a['b']"
options: [props: no]
]
invalid: [
code: '''
a = null
a = a
'''
errors: ["'a' is assigned to itself."]
,
code: '[a] = [a]'
errors: ["'a' is assigned to itself."]
,
code: '[a, b] = [a, b]'
errors: ["'a' is assigned to itself.", "'b' is assigned to itself."]
,
code: '[a, b] = [a, c]'
errors: ["'a' is assigned to itself."]
,
code: '[a, b] = [, b]'
errors: ["'b' is assigned to itself."]
,
code: '[a, ...b] = [a, ...b]'
errors: ["'a' is assigned to itself.", "'b' is assigned to itself."]
,
code: '[[a], {b}] = [[a], {b}]'
errors: ["'a' is assigned to itself.", "'b' is assigned to itself."]
,
code: '({a} = {a})'
errors: ["'a' is assigned to itself."]
,
code: '({a: b} = {a: b})'
errors: ["'b' is assigned to itself."]
,
code: '({a, b} = {a, b})'
errors: ["'a' is assigned to itself.", "'b' is assigned to itself."]
,
code: '({a, b} = {b, a})'
errors: ["'b' is assigned to itself.", "'a' is assigned to itself."]
,
code: '({a, b} = {c, a})'
errors: ["'a' is assigned to itself."]
,
code: '({a: {b}, c: [d]} = {a: {b}, c: [d]})'
errors: ["'b' is assigned to itself.", "'d' is assigned to itself."]
,
code: '({a, b} = {a, ...x, b})'
errors: ["'b' is assigned to itself."]
,
code: 'a.b = a.b'
errors: ["'a.b' is assigned to itself."]
,
code: 'a.b.c = a.b.c'
errors: ["'a.b.c' is assigned to itself."]
,
code: 'a[b] = a[b]'
errors: ["'a[b]' is assigned to itself."]
,
code: "a['b'] = a['b']"
errors: ["'a['b']' is assigned to itself."]
,
code: 'a.b = a.b'
options: [props: yes]
errors: ["'a.b' is assigned to itself."]
,
code: 'a.b.c = a.b.c'
options: [props: yes]
errors: ["'a.b.c' is assigned to itself."]
,
code: 'a[b] = a[b]'
options: [props: yes]
errors: ["'a[b]' is assigned to itself."]
,
code: "a['b'] = a['b']"
options: [props: yes]
errors: ["'a['b']' is assigned to itself."]
]
|
[
{
"context": "3 Flarebyte.com Ltd. All rights reserved.\nCreator: Olivier Huin\nContributors:\n###\n\n'use strict'\n# Services\nflamin",
"end": 151,
"score": 0.9998688697814941,
"start": 139,
"tag": "NAME",
"value": "Olivier Huin"
}
] | nodejs/flarebyte.net/0.8/node/flaming/browser/js/services22.coffee | flarebyte/wonderful-bazar | 0 | ###
GENERATED - DO NOT EDIT - Tue Jan 14 2014 22:25:31 GMT+0000 (GMT)
Copyright (c) 2013 Flarebyte.com Ltd. All rights reserved.
Creator: Olivier Huin
Contributors:
###
'use strict'
# Services
flamingAppServices = angular.module('flamingApp.services', ['ngResource'])
flamingAppServices.value "version", "0.1"
# List all profiles for the current user
flamingAppServices.factory "ListAllProfileService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/profile", {}, actions
]
# List all login options for the current user
flamingAppServices.factory "ListAllLoginOptionsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/login", {}, actions
]
# List all compose templates for the current user
flamingAppServices.factory "ListAllComposeTemplatesService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/compose", {}, actions
]
# List all messages to read for the current user
flamingAppServices.factory "ListAllMessagesToReadService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/to-read", {}, actions
]
# List all tasks to do for the current user
flamingAppServices.factory "ListAllTasksToDoService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/to-do", {}, actions
]
# List all important messages for the current user
flamingAppServices.factory "ListAllImportantMessagesService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/important", {}, actions
]
# List all recent messages for the current user
flamingAppServices.factory "ListAllRecentMessagesService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/recent", {}, actions
]
# List all shared messages for the current user
flamingAppServices.factory "ListAllSharedMessagesService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/shared", {}, actions
]
# List all messages for the current user
flamingAppServices.factory "ListAllMessagesService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/all", {}, actions
]
# List all news for the current user
flamingAppServices.factory "ListAllNewsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/news", {}, actions
]
# List all trash for the current user
flamingAppServices.factory "ListAllTrashService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/trash", {}, actions
]
# List all dashboards of the current user
flamingAppServices.factory "ListAllDashboardsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/dashboard", {}, actions
]
# List a selection of contacts of the current user
flamingAppServices.factory "ListASelectionOfContactsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/contacts", {}, actions
]
# List all contacts of the current user
flamingAppServices.factory "ListAllContactsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/contacts", {}, actions
]
# List all settings of the current user
flamingAppServices.factory "ListAllSettingsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/settings", {}, actions
]
# List all help items of the current user
flamingAppServices.factory "ListAllHelpItemsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/help", {}, actions
]
# List all faq items of the current user
flamingAppServices.factory "ListAllFaqItemsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/faq", {}, actions
]
# List all privacy items of the current user
flamingAppServices.factory "ListAllPrivacyItemsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/privacy", {}, actions
]
# List all terms for the current user
flamingAppServices.factory "ListAllTermsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/terms", {}, actions
]
| 32455 | ###
GENERATED - DO NOT EDIT - Tue Jan 14 2014 22:25:31 GMT+0000 (GMT)
Copyright (c) 2013 Flarebyte.com Ltd. All rights reserved.
Creator: <NAME>
Contributors:
###
'use strict'
# Services
flamingAppServices = angular.module('flamingApp.services', ['ngResource'])
flamingAppServices.value "version", "0.1"
# List all profiles for the current user
flamingAppServices.factory "ListAllProfileService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/profile", {}, actions
]
# List all login options for the current user
flamingAppServices.factory "ListAllLoginOptionsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/login", {}, actions
]
# List all compose templates for the current user
flamingAppServices.factory "ListAllComposeTemplatesService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/compose", {}, actions
]
# List all messages to read for the current user
flamingAppServices.factory "ListAllMessagesToReadService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/to-read", {}, actions
]
# List all tasks to do for the current user
flamingAppServices.factory "ListAllTasksToDoService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/to-do", {}, actions
]
# List all important messages for the current user
flamingAppServices.factory "ListAllImportantMessagesService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/important", {}, actions
]
# List all recent messages for the current user
flamingAppServices.factory "ListAllRecentMessagesService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/recent", {}, actions
]
# List all shared messages for the current user
flamingAppServices.factory "ListAllSharedMessagesService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/shared", {}, actions
]
# List all messages for the current user
flamingAppServices.factory "ListAllMessagesService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/all", {}, actions
]
# List all news for the current user
flamingAppServices.factory "ListAllNewsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/news", {}, actions
]
# List all trash for the current user
flamingAppServices.factory "ListAllTrashService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/trash", {}, actions
]
# List all dashboards of the current user
flamingAppServices.factory "ListAllDashboardsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/dashboard", {}, actions
]
# List a selection of contacts of the current user
flamingAppServices.factory "ListASelectionOfContactsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/contacts", {}, actions
]
# List all contacts of the current user
flamingAppServices.factory "ListAllContactsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/contacts", {}, actions
]
# List all settings of the current user
flamingAppServices.factory "ListAllSettingsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/settings", {}, actions
]
# List all help items of the current user
flamingAppServices.factory "ListAllHelpItemsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/help", {}, actions
]
# List all faq items of the current user
flamingAppServices.factory "ListAllFaqItemsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/faq", {}, actions
]
# List all privacy items of the current user
flamingAppServices.factory "ListAllPrivacyItemsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/privacy", {}, actions
]
# List all terms for the current user
flamingAppServices.factory "ListAllTermsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/terms", {}, actions
]
| true | ###
GENERATED - DO NOT EDIT - Tue Jan 14 2014 22:25:31 GMT+0000 (GMT)
Copyright (c) 2013 Flarebyte.com Ltd. All rights reserved.
Creator: PI:NAME:<NAME>END_PI
Contributors:
###
'use strict'
# Services
flamingAppServices = angular.module('flamingApp.services', ['ngResource'])
flamingAppServices.value "version", "0.1"
# List all profiles for the current user
flamingAppServices.factory "ListAllProfileService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/profile", {}, actions
]
# List all login options for the current user
flamingAppServices.factory "ListAllLoginOptionsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/login", {}, actions
]
# List all compose templates for the current user
flamingAppServices.factory "ListAllComposeTemplatesService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/compose", {}, actions
]
# List all messages to read for the current user
flamingAppServices.factory "ListAllMessagesToReadService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/to-read", {}, actions
]
# List all tasks to do for the current user
flamingAppServices.factory "ListAllTasksToDoService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/to-do", {}, actions
]
# List all important messages for the current user
flamingAppServices.factory "ListAllImportantMessagesService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/important", {}, actions
]
# List all recent messages for the current user
flamingAppServices.factory "ListAllRecentMessagesService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/recent", {}, actions
]
# List all shared messages for the current user
flamingAppServices.factory "ListAllSharedMessagesService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/shared", {}, actions
]
# List all messages for the current user
flamingAppServices.factory "ListAllMessagesService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/all", {}, actions
]
# List all news for the current user
flamingAppServices.factory "ListAllNewsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/news", {}, actions
]
# List all trash for the current user
flamingAppServices.factory "ListAllTrashService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/trash", {}, actions
]
# List all dashboards of the current user
flamingAppServices.factory "ListAllDashboardsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/dashboard", {}, actions
]
# List a selection of contacts of the current user
flamingAppServices.factory "ListASelectionOfContactsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/contacts", {}, actions
]
# List all contacts of the current user
flamingAppServices.factory "ListAllContactsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/contacts", {}, actions
]
# List all settings of the current user
flamingAppServices.factory "ListAllSettingsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/settings", {}, actions
]
# List all help items of the current user
flamingAppServices.factory "ListAllHelpItemsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/help", {}, actions
]
# List all faq items of the current user
flamingAppServices.factory "ListAllFaqItemsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/faq", {}, actions
]
# List all privacy items of the current user
flamingAppServices.factory "ListAllPrivacyItemsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/privacy", {}, actions
]
# List all terms for the current user
flamingAppServices.factory "ListAllTermsService",
["$resource", ($resource) ->
actions=
query:
method: "GET"
$resource "/api/terms", {}, actions
]
|
[
{
"context": " book: {title: \"Brighton Rock\", author: \"Graham Greene\"}\n clientId: \"12345\",\n callback",
"end": 2417,
"score": 0.9998900294303894,
"start": 2404,
"tag": "NAME",
"value": "Graham Greene"
}
] | src/readmill.coffee | aron/annotator.readmill.js | 0 | # Base class for the Readmill plugin. This will be called via the jQuery
# annotator interface.
#
# The "book", "clientId" and "callbackUrl" arguments are required. The
# book should be an object literal for a book on Readmill ideally with an
# "id" but if only a "title", "author" are provided the plugin will
# create the book for you.
#
# Examples
#
# jQuery("#content").annotator()
# .annotator("addPlugin", "Readmill", {
# book: {id: 52},
# clientId: "123456",
# callbackUrl: "http://example.com/callback.html"
# });
#
# Returns a new instance of Readmill.
Annotator.Readmill = class Readmill extends Annotator.Plugin
# Privately export jQuery variable local only to this class.
jQuery = Annotator.$
# DOM and custom event to callback map.
events:
"annotationCreated": "_onAnnotationCreated"
"annotationUpdated": "_onAnnotationUpdated"
"annotationDeleted": "_onAnnotationDeleted"
# Default options for the class.
options:
# Gets a unique identifier for this page. This allows a book to be spread
# over multiple html pages but retain a single resource on Readmill. By
# default this is the page URI up to the query string.
#
# Returns a unique id for the page.
getPage: -> window.location.href.split('?').shift()
# Initialises the plugin instance and sets up properties.
#
# element - The root Annotator element.
# options - An object literal of options.
# book - An object of book metadata.
# clientId - The client id string for the service.
# callbackUrl - A full url pointing to the callback.html file.
# accessToken - A pre activated accessToken (optional).
# getPage - A function that returns a page id (optional).
#
# Returns nothing.
# Raises an Error if any of the required arguments are missing.
constructor: (element, options) ->
super
# Ensure required options are provided.
errors = (key for own key in ["book", "clientId", "callbackUrl"] when not options[key])
if errors.length
throw new Error """
options "#{errors.join('", ')}" are required by the Readmill plugin. eg:
jQuery("#content").annotator()
.annotator("addPlugin", "Readmill", {
book: {id: "52"}, /* Or use a title & author. */
book: {title: "Brighton Rock", author: "Graham Greene"}
clientId: "12345",
callbackUrl: "http://example.com/callback.html"
});
"""
@user = null
@book = @options.book
@view = new Readmill.View
@auth = new Readmill.Auth @options
@store = new Readmill.Store
@client = new Readmill.Client @options
# Rather than use CoffeeScript's scope binding for all the event handlers
# in this class (which generates a line of JavaScript per binding) we use a
# utilty function to manually bind all functions beginning with "_on" to
# the current scope.
Readmill.utils.proxyHandlers this
# Decorate all error handlers with a callback to check for unauthorised
# responses.
for own key, value of this when key.indexOf("Error") > -1
this[key] = @_createUnauthorizedHandler(value)
token = options.accessToken or @store.get("access-token")
@connected(token, silent: true) if token
@unsaved = []
# Internal: Called by the Annotator after the intance has been created and
# @annotator property has been attached. Sets up initial plugin state.
#
# Returns nothing.
pluginInit: ->
@view.on "reading", @lookupReading
@view.on "finish", @endReading
@view.on "privacy", @updatePrivacy
@view.on "connect", @connect
@view.on "disconnect", @disconnect
jQuery("body").append @view.render()
if @client.isAuthorized()
# Look up reading and update the view. Pass silent to prevent
# triggering "reading" event.
@lookupReading().done => @view.reading(silent: true)
else
@lookupBook()
# Public: Fetches the book resource from the Readmill API and updates the
# view when complete. This method is usually called as part of the plugin
# setup.
#
# The method also attaches a "promise" property to @book which can be used
# to determine if the book is loaded.
#
# Examples
#
# readmill.lookupBook()
#
# Returns a jQuery.Deferred() promise.
lookupBook: ->
return @book.promise if @book.promise
@book.promise = if @book.id
@client.getBook @book.id
else
@client.matchBook @book
@book.promise.then(@_onBookSuccess, @_onBookError).done =>
@view.updateBook @book
# Public: Queries/Creates a reading for the current book.
#
# Examples
#
# request = readmill.lookupReading()
# request.done -> console.log request.reading.id
#
# Returns a jQuery.Deferred() promise.
lookupReading: =>
@lookupBook().done =>
request = @client.createReadingForBook @book.id,
state: Readmill.Client.READING_STATE_OPEN
private: @view.isPrivate()
request.then(@_onCreateReadingSuccess, @_onCreateReadingError)
# Public: Ends the current reading session if one exists by marking
# the book as finished.
#
# Examples
#
# readmill.endReading()
#
# Returns a jQuery.Deferred() promise.
endReading: =>
if @book.reading
@client.updateReading @book.reading.uri,
state: Readmill.Client.READING_STATE_FINISHED
@removeAnnotations()
delete @book.reading
# Public: Updates the privacy of the reading depending on the status
# of the view.
#
# Returns jQuery.Deferred promise.
updatePrivacy: =>
isPrivate = @view.isPrivate()
if @book.reading and @book.reading.private isnt isPrivate
@book.reading.private = isPrivate
request = @client.updateReading(@book.reading.uri, private: isPrivate)
request.fail(@_onUpdatePrivacyError)
# Public: Begins the Readmill authentication flow.
#
# Examples
#
# auth = readmill.connect()
# auth.done -> readmill.client.me() # Load the user data.
#
# Returns a jQuery.Deferred() promise.
connect: =>
@auth.connect().then @_onConnectSuccess, @_onConnectError
# Public: Setup method that should be called once the user is authenticated
# with Readmill. Will display a notification unless options.silent argument
# is provided.
#
# accessToken - Access token for the client/current user.
# options - An object of method options (default: {}).
# silent: If true will not display the notification.
#
# Examples
#
# readmill.connected("abcdefgh")
# readmill.connected("abcdefgh", silent: true)
#
# Returns nothing.
connected: (accessToken, options={}) ->
@client.authorize accessToken
@client.me().then(@_onMeSuccess, @_onMeError).done =>
@view.login @user
@store.set "access-token", accessToken, options.expires
unless options?.silent is true
Annotator.showNotification "Successfully connected to Readmill"
# Public: Displays an unauthorized notification. Should be called when
# a user is required to reconnect with Readmill.
#
# Examples
#
# readmill.unauthorized()
#
# Returns nothing.
unauthorized: ->
msg = "Not connected to Readmill, click here to connect"
Annotator.showNotification(msg)
@disconnect(removeAnnotations: false)
# Watch for the users clicks on the notifiaction banner.
notification = jQuery(".annotator-notice").one "click.readmill-auth", =>
@connect()
# Unbind the event listener manually after five seconds.
unbind = => notification.unbind(".readmill-auth")
setTimeout(unbind, 5000)
# Public: Removes all traces of the user from the plugin.
#
# 1. Deauthorises the client instance.
# 2. Removes related local storage entries.
# 3. Removes annotations from the document.
#
# Examples
#
# jQuery("#logout").click -> readmill.disconnect()
#
# Returns nothing.
disconnect: (options={}) =>
@client.deauthorize()
@store.remove("access-token")
@removeAnnotations() unless options.removeAnnotations is false
# Internal: Helper method for displaying error notifications.
#
# message - Message to display to the user.
#
# Examples
#
# readmill.error("Unable to find this book")
#
# Returns nothing.
error: (message) ->
Annotator.showNotification message, Annotator.Notification.ERROR
# Internal: Removes all annotations from the current page.
#
# Examples
#
# readmill.removeAnnotations()
#
# Returns nothing.
removeAnnotations: ->
@element.find(".annotator-hl").each ->
jQuery(this).replaceWith this.childNodes
# Decorator method for error callbacks for client requests. Returns a wrapped
# function which handles 401 Unauthorized responses and requests the user to
# reconnect with Readmill.
#
# wrapped - The error handler to wrap.
#
# Examples
#
# handler = readmill._createUnauthorizedHandler (jqXHR) ->
# console.log "An error has occured."
# readmill.me().error(handler)
#
# Returns a new callback function.
_createUnauthorizedHandler: (handler) ->
(jqXHR) =>
isUnauthorized = jqXHR and (jqXHR.status is 401 or jqXHR.status is 0)
if isUnauthorized then @unauthorized() else handler.apply(this, arguments)
_onConnectSuccess: (params) ->
@connected params.access_token, params
_onConnectError: (error) ->
@error error
_onMeSuccess: (data) ->
@user = data
_onMeError: () ->
@error "Unable to fetch user info from Readmill"
_onBookSuccess: (book) ->
jQuery.extend @book, book
_onBookError: ->
@error "Unable to fetch book info from Readmill"
_onCreateReadingSuccess: (body, status, jqXHR) ->
{location} = body
if location
request = @client.request(url: location)
request.then @_onGetReadingSuccess, @_onGetReadingError
else
@_onGetReadingError()
_onCreateReadingError: (jqXHR) ->
if jqXHR.status == 409
body = JSON.parse jqXHR.responseText
@_onCreateReadingSuccess(body, "success", jqXHR)
else
@error "Unable to create a reading for this book"
# Public: Callback handler for failiure to update the privacy value.
#
# jqXHR - The jqXHR object for the failed request.
#
# Returns nothing.
_onUpdatePrivacyError: (jqXHR) ->
@error "Unable to update the privacy state for this book"
_onGetReadingSuccess: (reading) ->
@book.reading = reading
@view.updateBook(@book)
request = @client.getHighlights(reading.highlights)
request.then @_onGetHighlightsSuccess, @_onGetHighlightsError
_onGetReadingError: () ->
@error "Unable to create a reading for this book"
_onGetHighlightsSuccess: (highlights) ->
promises = jQuery.map highlights, (highlight) =>
Readmill.utils.annotationFromHighlight(highlight, @client)
# Filter out unparsable annotations.
promises = jQuery.grep promises, (prom) -> prom.state() isnt "rejected"
jQuery.when.apply(jQuery, promises).done =>
annotations = jQuery.makeArray(arguments)
@annotator.loadAnnotations annotations
_onGetHighlightsError: ->
@error "Unable to fetch highlights for reading"
_onCreateHighlight: (annotation, data) ->
# Now fetch the highlight resource in order to get the required
# urls for the highlight, comments and comment resources.
@client.request(url: data.location).done (highlight) =>
# Need to store this rather than data.location in order to be able to
# delete the highlight at a later date.
annotation.id = highlight.id
annotation.highlightUrl = highlight.uri
annotation.commentsUrl = highlight.comments
# Now create the comment for the highlight. We can do this using the
# @_onAnnotationUpdated() method which does this anyway. This should
# probably be moved out the callback methods in a later refactor.
@_onAnnotationUpdated(annotation) if annotation.text
_onBeforeAnnotationCreated: (annotation) ->
annotation.page = @options.getPage()
_onAnnotationCreated: (annotation) ->
if @client.isAuthorized() and @book.id and @book.reading?.highlights
url = @book.reading.highlights
highlight = Readmill.utils.highlightFromAnnotation annotation
# We don't create the comment here as we can't easily access the url
# permalink. The comment is instead created in the success callback.
request = @client.createHighlight url, highlight
request.done jQuery.proxy(this, "_onCreateHighlight", annotation)
request.fail @_onAnnotationCreatedError
else
@unsaved.push annotation
@unauthorized() unless @client.isAuthorized()
unless @book.id
@lookupBook().done => @_onAnnotationCreated(annotation)
_onAnnotationCreatedError: ->
@error "Unable to save annotation to Readmill"
_onAnnotationUpdated: (annotation) ->
data = Readmill.utils.commentFromAnnotation annotation
if annotation.commentUrl
request = @client.updateComment annotation.commentUrl, data
else if annotation.commentsUrl
request = @client.createComment annotation.commentsUrl, data
request.done (data) =>
annotation.commentUrl = data.location
request.fail @_onAnnotationUpdatedError if request
_onAnnotationUpdatedError: ->
@error "Unable to update annotation in Readmill"
_onAnnotationDeleted: (annotation) ->
if annotation.highlightUrl
request = @client.deleteHighlight(annotation.highlightUrl)
request.fail @_onAnnotationDeletedError
_onAnnotationDeletedError: ->
@error "Unable to delete annotation on Readmill"
# Grab the Delegator class here as it's useful for other Classes.
Annotator.Class = Annotator.__super__.constructor
Annotator.Plugin.Readmill = Annotator.Readmill
| 191603 | # Base class for the Readmill plugin. This will be called via the jQuery
# annotator interface.
#
# The "book", "clientId" and "callbackUrl" arguments are required. The
# book should be an object literal for a book on Readmill ideally with an
# "id" but if only a "title", "author" are provided the plugin will
# create the book for you.
#
# Examples
#
# jQuery("#content").annotator()
# .annotator("addPlugin", "Readmill", {
# book: {id: 52},
# clientId: "123456",
# callbackUrl: "http://example.com/callback.html"
# });
#
# Returns a new instance of Readmill.
Annotator.Readmill = class Readmill extends Annotator.Plugin
# Privately export jQuery variable local only to this class.
jQuery = Annotator.$
# DOM and custom event to callback map.
events:
"annotationCreated": "_onAnnotationCreated"
"annotationUpdated": "_onAnnotationUpdated"
"annotationDeleted": "_onAnnotationDeleted"
# Default options for the class.
options:
# Gets a unique identifier for this page. This allows a book to be spread
# over multiple html pages but retain a single resource on Readmill. By
# default this is the page URI up to the query string.
#
# Returns a unique id for the page.
getPage: -> window.location.href.split('?').shift()
# Initialises the plugin instance and sets up properties.
#
# element - The root Annotator element.
# options - An object literal of options.
# book - An object of book metadata.
# clientId - The client id string for the service.
# callbackUrl - A full url pointing to the callback.html file.
# accessToken - A pre activated accessToken (optional).
# getPage - A function that returns a page id (optional).
#
# Returns nothing.
# Raises an Error if any of the required arguments are missing.
constructor: (element, options) ->
super
# Ensure required options are provided.
errors = (key for own key in ["book", "clientId", "callbackUrl"] when not options[key])
if errors.length
throw new Error """
options "#{errors.join('", ')}" are required by the Readmill plugin. eg:
jQuery("#content").annotator()
.annotator("addPlugin", "Readmill", {
book: {id: "52"}, /* Or use a title & author. */
book: {title: "Brighton Rock", author: "<NAME>"}
clientId: "12345",
callbackUrl: "http://example.com/callback.html"
});
"""
@user = null
@book = @options.book
@view = new Readmill.View
@auth = new Readmill.Auth @options
@store = new Readmill.Store
@client = new Readmill.Client @options
# Rather than use CoffeeScript's scope binding for all the event handlers
# in this class (which generates a line of JavaScript per binding) we use a
# utilty function to manually bind all functions beginning with "_on" to
# the current scope.
Readmill.utils.proxyHandlers this
# Decorate all error handlers with a callback to check for unauthorised
# responses.
for own key, value of this when key.indexOf("Error") > -1
this[key] = @_createUnauthorizedHandler(value)
token = options.accessToken or @store.get("access-token")
@connected(token, silent: true) if token
@unsaved = []
# Internal: Called by the Annotator after the intance has been created and
# @annotator property has been attached. Sets up initial plugin state.
#
# Returns nothing.
pluginInit: ->
@view.on "reading", @lookupReading
@view.on "finish", @endReading
@view.on "privacy", @updatePrivacy
@view.on "connect", @connect
@view.on "disconnect", @disconnect
jQuery("body").append @view.render()
if @client.isAuthorized()
# Look up reading and update the view. Pass silent to prevent
# triggering "reading" event.
@lookupReading().done => @view.reading(silent: true)
else
@lookupBook()
# Public: Fetches the book resource from the Readmill API and updates the
# view when complete. This method is usually called as part of the plugin
# setup.
#
# The method also attaches a "promise" property to @book which can be used
# to determine if the book is loaded.
#
# Examples
#
# readmill.lookupBook()
#
# Returns a jQuery.Deferred() promise.
lookupBook: ->
return @book.promise if @book.promise
@book.promise = if @book.id
@client.getBook @book.id
else
@client.matchBook @book
@book.promise.then(@_onBookSuccess, @_onBookError).done =>
@view.updateBook @book
# Public: Queries/Creates a reading for the current book.
#
# Examples
#
# request = readmill.lookupReading()
# request.done -> console.log request.reading.id
#
# Returns a jQuery.Deferred() promise.
lookupReading: =>
@lookupBook().done =>
request = @client.createReadingForBook @book.id,
state: Readmill.Client.READING_STATE_OPEN
private: @view.isPrivate()
request.then(@_onCreateReadingSuccess, @_onCreateReadingError)
# Public: Ends the current reading session if one exists by marking
# the book as finished.
#
# Examples
#
# readmill.endReading()
#
# Returns a jQuery.Deferred() promise.
endReading: =>
if @book.reading
@client.updateReading @book.reading.uri,
state: Readmill.Client.READING_STATE_FINISHED
@removeAnnotations()
delete @book.reading
# Public: Updates the privacy of the reading depending on the status
# of the view.
#
# Returns jQuery.Deferred promise.
updatePrivacy: =>
isPrivate = @view.isPrivate()
if @book.reading and @book.reading.private isnt isPrivate
@book.reading.private = isPrivate
request = @client.updateReading(@book.reading.uri, private: isPrivate)
request.fail(@_onUpdatePrivacyError)
# Public: Begins the Readmill authentication flow.
#
# Examples
#
# auth = readmill.connect()
# auth.done -> readmill.client.me() # Load the user data.
#
# Returns a jQuery.Deferred() promise.
connect: =>
@auth.connect().then @_onConnectSuccess, @_onConnectError
# Public: Setup method that should be called once the user is authenticated
# with Readmill. Will display a notification unless options.silent argument
# is provided.
#
# accessToken - Access token for the client/current user.
# options - An object of method options (default: {}).
# silent: If true will not display the notification.
#
# Examples
#
# readmill.connected("abcdefgh")
# readmill.connected("abcdefgh", silent: true)
#
# Returns nothing.
connected: (accessToken, options={}) ->
@client.authorize accessToken
@client.me().then(@_onMeSuccess, @_onMeError).done =>
@view.login @user
@store.set "access-token", accessToken, options.expires
unless options?.silent is true
Annotator.showNotification "Successfully connected to Readmill"
# Public: Displays an unauthorized notification. Should be called when
# a user is required to reconnect with Readmill.
#
# Examples
#
# readmill.unauthorized()
#
# Returns nothing.
unauthorized: ->
msg = "Not connected to Readmill, click here to connect"
Annotator.showNotification(msg)
@disconnect(removeAnnotations: false)
# Watch for the users clicks on the notifiaction banner.
notification = jQuery(".annotator-notice").one "click.readmill-auth", =>
@connect()
# Unbind the event listener manually after five seconds.
unbind = => notification.unbind(".readmill-auth")
setTimeout(unbind, 5000)
# Public: Removes all traces of the user from the plugin.
#
# 1. Deauthorises the client instance.
# 2. Removes related local storage entries.
# 3. Removes annotations from the document.
#
# Examples
#
# jQuery("#logout").click -> readmill.disconnect()
#
# Returns nothing.
disconnect: (options={}) =>
@client.deauthorize()
@store.remove("access-token")
@removeAnnotations() unless options.removeAnnotations is false
# Internal: Helper method for displaying error notifications.
#
# message - Message to display to the user.
#
# Examples
#
# readmill.error("Unable to find this book")
#
# Returns nothing.
error: (message) ->
Annotator.showNotification message, Annotator.Notification.ERROR
# Internal: Removes all annotations from the current page.
#
# Examples
#
# readmill.removeAnnotations()
#
# Returns nothing.
removeAnnotations: ->
@element.find(".annotator-hl").each ->
jQuery(this).replaceWith this.childNodes
# Decorator method for error callbacks for client requests. Returns a wrapped
# function which handles 401 Unauthorized responses and requests the user to
# reconnect with Readmill.
#
# wrapped - The error handler to wrap.
#
# Examples
#
# handler = readmill._createUnauthorizedHandler (jqXHR) ->
# console.log "An error has occured."
# readmill.me().error(handler)
#
# Returns a new callback function.
_createUnauthorizedHandler: (handler) ->
(jqXHR) =>
isUnauthorized = jqXHR and (jqXHR.status is 401 or jqXHR.status is 0)
if isUnauthorized then @unauthorized() else handler.apply(this, arguments)
_onConnectSuccess: (params) ->
@connected params.access_token, params
_onConnectError: (error) ->
@error error
_onMeSuccess: (data) ->
@user = data
_onMeError: () ->
@error "Unable to fetch user info from Readmill"
_onBookSuccess: (book) ->
jQuery.extend @book, book
_onBookError: ->
@error "Unable to fetch book info from Readmill"
_onCreateReadingSuccess: (body, status, jqXHR) ->
{location} = body
if location
request = @client.request(url: location)
request.then @_onGetReadingSuccess, @_onGetReadingError
else
@_onGetReadingError()
_onCreateReadingError: (jqXHR) ->
if jqXHR.status == 409
body = JSON.parse jqXHR.responseText
@_onCreateReadingSuccess(body, "success", jqXHR)
else
@error "Unable to create a reading for this book"
# Public: Callback handler for failiure to update the privacy value.
#
# jqXHR - The jqXHR object for the failed request.
#
# Returns nothing.
_onUpdatePrivacyError: (jqXHR) ->
@error "Unable to update the privacy state for this book"
_onGetReadingSuccess: (reading) ->
@book.reading = reading
@view.updateBook(@book)
request = @client.getHighlights(reading.highlights)
request.then @_onGetHighlightsSuccess, @_onGetHighlightsError
_onGetReadingError: () ->
@error "Unable to create a reading for this book"
_onGetHighlightsSuccess: (highlights) ->
promises = jQuery.map highlights, (highlight) =>
Readmill.utils.annotationFromHighlight(highlight, @client)
# Filter out unparsable annotations.
promises = jQuery.grep promises, (prom) -> prom.state() isnt "rejected"
jQuery.when.apply(jQuery, promises).done =>
annotations = jQuery.makeArray(arguments)
@annotator.loadAnnotations annotations
_onGetHighlightsError: ->
@error "Unable to fetch highlights for reading"
_onCreateHighlight: (annotation, data) ->
# Now fetch the highlight resource in order to get the required
# urls for the highlight, comments and comment resources.
@client.request(url: data.location).done (highlight) =>
# Need to store this rather than data.location in order to be able to
# delete the highlight at a later date.
annotation.id = highlight.id
annotation.highlightUrl = highlight.uri
annotation.commentsUrl = highlight.comments
# Now create the comment for the highlight. We can do this using the
# @_onAnnotationUpdated() method which does this anyway. This should
# probably be moved out the callback methods in a later refactor.
@_onAnnotationUpdated(annotation) if annotation.text
_onBeforeAnnotationCreated: (annotation) ->
annotation.page = @options.getPage()
_onAnnotationCreated: (annotation) ->
if @client.isAuthorized() and @book.id and @book.reading?.highlights
url = @book.reading.highlights
highlight = Readmill.utils.highlightFromAnnotation annotation
# We don't create the comment here as we can't easily access the url
# permalink. The comment is instead created in the success callback.
request = @client.createHighlight url, highlight
request.done jQuery.proxy(this, "_onCreateHighlight", annotation)
request.fail @_onAnnotationCreatedError
else
@unsaved.push annotation
@unauthorized() unless @client.isAuthorized()
unless @book.id
@lookupBook().done => @_onAnnotationCreated(annotation)
_onAnnotationCreatedError: ->
@error "Unable to save annotation to Readmill"
_onAnnotationUpdated: (annotation) ->
data = Readmill.utils.commentFromAnnotation annotation
if annotation.commentUrl
request = @client.updateComment annotation.commentUrl, data
else if annotation.commentsUrl
request = @client.createComment annotation.commentsUrl, data
request.done (data) =>
annotation.commentUrl = data.location
request.fail @_onAnnotationUpdatedError if request
_onAnnotationUpdatedError: ->
@error "Unable to update annotation in Readmill"
_onAnnotationDeleted: (annotation) ->
if annotation.highlightUrl
request = @client.deleteHighlight(annotation.highlightUrl)
request.fail @_onAnnotationDeletedError
_onAnnotationDeletedError: ->
@error "Unable to delete annotation on Readmill"
# Grab the Delegator class here as it's useful for other Classes.
Annotator.Class = Annotator.__super__.constructor
Annotator.Plugin.Readmill = Annotator.Readmill
| true | # Base class for the Readmill plugin. This will be called via the jQuery
# annotator interface.
#
# The "book", "clientId" and "callbackUrl" arguments are required. The
# book should be an object literal for a book on Readmill ideally with an
# "id" but if only a "title", "author" are provided the plugin will
# create the book for you.
#
# Examples
#
# jQuery("#content").annotator()
# .annotator("addPlugin", "Readmill", {
# book: {id: 52},
# clientId: "123456",
# callbackUrl: "http://example.com/callback.html"
# });
#
# Returns a new instance of Readmill.
Annotator.Readmill = class Readmill extends Annotator.Plugin
# Privately export jQuery variable local only to this class.
jQuery = Annotator.$
# DOM and custom event to callback map.
events:
"annotationCreated": "_onAnnotationCreated"
"annotationUpdated": "_onAnnotationUpdated"
"annotationDeleted": "_onAnnotationDeleted"
# Default options for the class.
options:
# Gets a unique identifier for this page. This allows a book to be spread
# over multiple html pages but retain a single resource on Readmill. By
# default this is the page URI up to the query string.
#
# Returns a unique id for the page.
getPage: -> window.location.href.split('?').shift()
# Initialises the plugin instance and sets up properties.
#
# element - The root Annotator element.
# options - An object literal of options.
# book - An object of book metadata.
# clientId - The client id string for the service.
# callbackUrl - A full url pointing to the callback.html file.
# accessToken - A pre activated accessToken (optional).
# getPage - A function that returns a page id (optional).
#
# Returns nothing.
# Raises an Error if any of the required arguments are missing.
constructor: (element, options) ->
super
# Ensure required options are provided.
errors = (key for own key in ["book", "clientId", "callbackUrl"] when not options[key])
if errors.length
throw new Error """
options "#{errors.join('", ')}" are required by the Readmill plugin. eg:
jQuery("#content").annotator()
.annotator("addPlugin", "Readmill", {
book: {id: "52"}, /* Or use a title & author. */
book: {title: "Brighton Rock", author: "PI:NAME:<NAME>END_PI"}
clientId: "12345",
callbackUrl: "http://example.com/callback.html"
});
"""
@user = null
@book = @options.book
@view = new Readmill.View
@auth = new Readmill.Auth @options
@store = new Readmill.Store
@client = new Readmill.Client @options
# Rather than use CoffeeScript's scope binding for all the event handlers
# in this class (which generates a line of JavaScript per binding) we use a
# utilty function to manually bind all functions beginning with "_on" to
# the current scope.
Readmill.utils.proxyHandlers this
# Decorate all error handlers with a callback to check for unauthorised
# responses.
for own key, value of this when key.indexOf("Error") > -1
this[key] = @_createUnauthorizedHandler(value)
token = options.accessToken or @store.get("access-token")
@connected(token, silent: true) if token
@unsaved = []
# Internal: Called by the Annotator after the intance has been created and
# @annotator property has been attached. Sets up initial plugin state.
#
# Returns nothing.
pluginInit: ->
@view.on "reading", @lookupReading
@view.on "finish", @endReading
@view.on "privacy", @updatePrivacy
@view.on "connect", @connect
@view.on "disconnect", @disconnect
jQuery("body").append @view.render()
if @client.isAuthorized()
# Look up reading and update the view. Pass silent to prevent
# triggering "reading" event.
@lookupReading().done => @view.reading(silent: true)
else
@lookupBook()
# Public: Fetches the book resource from the Readmill API and updates the
# view when complete. This method is usually called as part of the plugin
# setup.
#
# The method also attaches a "promise" property to @book which can be used
# to determine if the book is loaded.
#
# Examples
#
# readmill.lookupBook()
#
# Returns a jQuery.Deferred() promise.
lookupBook: ->
return @book.promise if @book.promise
@book.promise = if @book.id
@client.getBook @book.id
else
@client.matchBook @book
@book.promise.then(@_onBookSuccess, @_onBookError).done =>
@view.updateBook @book
# Public: Queries/Creates a reading for the current book.
#
# Examples
#
# request = readmill.lookupReading()
# request.done -> console.log request.reading.id
#
# Returns a jQuery.Deferred() promise.
lookupReading: =>
@lookupBook().done =>
request = @client.createReadingForBook @book.id,
state: Readmill.Client.READING_STATE_OPEN
private: @view.isPrivate()
request.then(@_onCreateReadingSuccess, @_onCreateReadingError)
# Public: Ends the current reading session if one exists by marking
# the book as finished.
#
# Examples
#
# readmill.endReading()
#
# Returns a jQuery.Deferred() promise.
endReading: =>
if @book.reading
@client.updateReading @book.reading.uri,
state: Readmill.Client.READING_STATE_FINISHED
@removeAnnotations()
delete @book.reading
# Public: Updates the privacy of the reading depending on the status
# of the view.
#
# Returns jQuery.Deferred promise.
updatePrivacy: =>
isPrivate = @view.isPrivate()
if @book.reading and @book.reading.private isnt isPrivate
@book.reading.private = isPrivate
request = @client.updateReading(@book.reading.uri, private: isPrivate)
request.fail(@_onUpdatePrivacyError)
# Public: Begins the Readmill authentication flow.
#
# Examples
#
# auth = readmill.connect()
# auth.done -> readmill.client.me() # Load the user data.
#
# Returns a jQuery.Deferred() promise.
connect: =>
@auth.connect().then @_onConnectSuccess, @_onConnectError
# Public: Setup method that should be called once the user is authenticated
# with Readmill. Will display a notification unless options.silent argument
# is provided.
#
# accessToken - Access token for the client/current user.
# options - An object of method options (default: {}).
# silent: If true will not display the notification.
#
# Examples
#
# readmill.connected("abcdefgh")
# readmill.connected("abcdefgh", silent: true)
#
# Returns nothing.
connected: (accessToken, options={}) ->
@client.authorize accessToken
@client.me().then(@_onMeSuccess, @_onMeError).done =>
@view.login @user
@store.set "access-token", accessToken, options.expires
unless options?.silent is true
Annotator.showNotification "Successfully connected to Readmill"
# Public: Displays an unauthorized notification. Should be called when
# a user is required to reconnect with Readmill.
#
# Examples
#
# readmill.unauthorized()
#
# Returns nothing.
unauthorized: ->
msg = "Not connected to Readmill, click here to connect"
Annotator.showNotification(msg)
@disconnect(removeAnnotations: false)
# Watch for the users clicks on the notifiaction banner.
notification = jQuery(".annotator-notice").one "click.readmill-auth", =>
@connect()
# Unbind the event listener manually after five seconds.
unbind = => notification.unbind(".readmill-auth")
setTimeout(unbind, 5000)
# Public: Removes all traces of the user from the plugin.
#
# 1. Deauthorises the client instance.
# 2. Removes related local storage entries.
# 3. Removes annotations from the document.
#
# Examples
#
# jQuery("#logout").click -> readmill.disconnect()
#
# Returns nothing.
disconnect: (options={}) =>
@client.deauthorize()
@store.remove("access-token")
@removeAnnotations() unless options.removeAnnotations is false
# Internal: Helper method for displaying error notifications.
#
# message - Message to display to the user.
#
# Examples
#
# readmill.error("Unable to find this book")
#
# Returns nothing.
error: (message) ->
Annotator.showNotification message, Annotator.Notification.ERROR
# Internal: Removes all annotations from the current page.
#
# Examples
#
# readmill.removeAnnotations()
#
# Returns nothing.
removeAnnotations: ->
@element.find(".annotator-hl").each ->
jQuery(this).replaceWith this.childNodes
# Decorator method for error callbacks for client requests. Returns a wrapped
# function which handles 401 Unauthorized responses and requests the user to
# reconnect with Readmill.
#
# wrapped - The error handler to wrap.
#
# Examples
#
# handler = readmill._createUnauthorizedHandler (jqXHR) ->
# console.log "An error has occured."
# readmill.me().error(handler)
#
# Returns a new callback function.
_createUnauthorizedHandler: (handler) ->
(jqXHR) =>
isUnauthorized = jqXHR and (jqXHR.status is 401 or jqXHR.status is 0)
if isUnauthorized then @unauthorized() else handler.apply(this, arguments)
_onConnectSuccess: (params) ->
@connected params.access_token, params
_onConnectError: (error) ->
@error error
_onMeSuccess: (data) ->
@user = data
_onMeError: () ->
@error "Unable to fetch user info from Readmill"
_onBookSuccess: (book) ->
jQuery.extend @book, book
_onBookError: ->
@error "Unable to fetch book info from Readmill"
_onCreateReadingSuccess: (body, status, jqXHR) ->
{location} = body
if location
request = @client.request(url: location)
request.then @_onGetReadingSuccess, @_onGetReadingError
else
@_onGetReadingError()
_onCreateReadingError: (jqXHR) ->
if jqXHR.status == 409
body = JSON.parse jqXHR.responseText
@_onCreateReadingSuccess(body, "success", jqXHR)
else
@error "Unable to create a reading for this book"
# Public: Callback handler for failiure to update the privacy value.
#
# jqXHR - The jqXHR object for the failed request.
#
# Returns nothing.
_onUpdatePrivacyError: (jqXHR) ->
@error "Unable to update the privacy state for this book"
_onGetReadingSuccess: (reading) ->
@book.reading = reading
@view.updateBook(@book)
request = @client.getHighlights(reading.highlights)
request.then @_onGetHighlightsSuccess, @_onGetHighlightsError
_onGetReadingError: () ->
@error "Unable to create a reading for this book"
_onGetHighlightsSuccess: (highlights) ->
promises = jQuery.map highlights, (highlight) =>
Readmill.utils.annotationFromHighlight(highlight, @client)
# Filter out unparsable annotations.
promises = jQuery.grep promises, (prom) -> prom.state() isnt "rejected"
jQuery.when.apply(jQuery, promises).done =>
annotations = jQuery.makeArray(arguments)
@annotator.loadAnnotations annotations
_onGetHighlightsError: ->
@error "Unable to fetch highlights for reading"
_onCreateHighlight: (annotation, data) ->
# Now fetch the highlight resource in order to get the required
# urls for the highlight, comments and comment resources.
@client.request(url: data.location).done (highlight) =>
# Need to store this rather than data.location in order to be able to
# delete the highlight at a later date.
annotation.id = highlight.id
annotation.highlightUrl = highlight.uri
annotation.commentsUrl = highlight.comments
# Now create the comment for the highlight. We can do this using the
# @_onAnnotationUpdated() method which does this anyway. This should
# probably be moved out the callback methods in a later refactor.
@_onAnnotationUpdated(annotation) if annotation.text
_onBeforeAnnotationCreated: (annotation) ->
annotation.page = @options.getPage()
_onAnnotationCreated: (annotation) ->
if @client.isAuthorized() and @book.id and @book.reading?.highlights
url = @book.reading.highlights
highlight = Readmill.utils.highlightFromAnnotation annotation
# We don't create the comment here as we can't easily access the url
# permalink. The comment is instead created in the success callback.
request = @client.createHighlight url, highlight
request.done jQuery.proxy(this, "_onCreateHighlight", annotation)
request.fail @_onAnnotationCreatedError
else
@unsaved.push annotation
@unauthorized() unless @client.isAuthorized()
unless @book.id
@lookupBook().done => @_onAnnotationCreated(annotation)
_onAnnotationCreatedError: ->
@error "Unable to save annotation to Readmill"
_onAnnotationUpdated: (annotation) ->
data = Readmill.utils.commentFromAnnotation annotation
if annotation.commentUrl
request = @client.updateComment annotation.commentUrl, data
else if annotation.commentsUrl
request = @client.createComment annotation.commentsUrl, data
request.done (data) =>
annotation.commentUrl = data.location
request.fail @_onAnnotationUpdatedError if request
_onAnnotationUpdatedError: ->
@error "Unable to update annotation in Readmill"
_onAnnotationDeleted: (annotation) ->
if annotation.highlightUrl
request = @client.deleteHighlight(annotation.highlightUrl)
request.fail @_onAnnotationDeletedError
_onAnnotationDeletedError: ->
@error "Unable to delete annotation on Readmill"
# Grab the Delegator class here as it's useful for other Classes.
Annotator.Class = Annotator.__super__.constructor
Annotator.Plugin.Readmill = Annotator.Readmill
|
[
{
"context": "\" : [ 25.289606400000025, 54.6646826 ], \"path\" : \"ssslIokjyCjA`YNtJ@tDC`Do@lFYhB[pBUr@a@dB_@xBYhC_@tCUhAQ`@m@z@gCfBNvBFfAn@`IqEpASHa@XuFfGaA|@gAl@[LiFbA{Cz@sBx@eATyLpCaDx@cFxAcFnA{Ct@yD`AoBlAWRsCbBkCxA}@^cBZo@VyAPaADkETM?GEOMo@eAmIuLSQWOgGuAsA_@]Q_Ao@u@k@{B{AcCwAmAw@qByAqAfCgCtF{ApCq@vAQrAm@bF... | src/packages/carpool-api/carpool-api.coffee | ArnoldasSid/vilnius-carpool | 11 | Router.route('/api/user/:userId/location', where: 'server').get(->
try
headers =
'Content-type': 'application/json; charset=utf-8'
if not apiSecurity.authorize(@params.userId, @params.query.access_token)
@response.writeHead(404, headers);
@response.end(JSON.stringify({error: "Forbiden: token or user is wrong"}), "utf-8");
return
result = Locations.findOne {userId: @params.userId}, {sort:{tsi:-1}, limit:1}
result = {error: "No location saved"} unless result
da ["carpool-api"], "Read location for #{@params.userId}", result
@response.writeHead(200, headers);
@response.end(JSON.stringify(result), "utf-8");
catch e
console.error(e)
@response.writeHead(503, headers);
@response.end("error:"+JSON.stringify(e), "utf-8");
).post(->
location = @request.body
location.tsi = new Date();
location.userId = @params.userId;
da ["carpool-api"], "Create location", location
Locations.insert(location);
headers =
'Content-type': 'application/json; charset=utf-8'
@response.writeHead(200, headers);
result =
status: "ok"
@response.end(JSON.stringify(result), "utf-8");
).put ->
# PUT /webhooks/stripe
return
Router.route('/api/trip/location', where: 'server').get(->
result = { "_id" : "rpfb3p3JBfWYdR3c7", "fromAddress" : "Dzūkų 54, Vilnius", "role" : "driver", "toAddress" : "Šeškinės g. 10, Vilnius", "time" : new Date("2016-03-08T03:29:42.465Z"), "toLoc" : [ 25.25145359999999, 54.71326200000001 ], "fromLoc" : [ 25.289606400000025, 54.6646826 ], "path" : "ssslIokjyCjA`YNtJ@tDC`Do@lFYhB[pBUr@a@dB_@xBYhC_@tCUhAQ`@m@z@gCfBNvBFfAn@`IqEpASHa@XuFfGaA|@gAl@[LiFbA{Cz@sBx@eATyLpCaDx@cFxAcFnA{Ct@yD`AoBlAWRsCbBkCxA}@^cBZo@VyAPaADkETM?GEOMo@eAmIuLSQWOgGuAsA_@]Q_Ao@u@k@{B{AcCwAmAw@qByAqAfCgCtF{ApCq@vAQrAm@bF]zCGVObAGROXMTe@CyBCuAF}DJs@D{Kh@cD\\aALqHyB]Q_AAaARu@^u@x@WV}@dBk@hBMn@q@jIKzAWpDW~BIr@Uz@eAtDW\\yDfDyDpD_DxC}CjD}CfDi@b@aEdCsAjAcDnC]@a@Rg@?uDy@gB_@qAe@", "stops" : [ ], "owner" : "HX8jY2bnYWGoHB7Em", "requests" : [ ], "status" : "scheduled" }
headers =
'Content-type': 'application/json; charset=utf-8'
@response.writeHead(200, headers);
@response.end(JSON.stringify(result), "utf-8");
)
| 50538 | Router.route('/api/user/:userId/location', where: 'server').get(->
try
headers =
'Content-type': 'application/json; charset=utf-8'
if not apiSecurity.authorize(@params.userId, @params.query.access_token)
@response.writeHead(404, headers);
@response.end(JSON.stringify({error: "Forbiden: token or user is wrong"}), "utf-8");
return
result = Locations.findOne {userId: @params.userId}, {sort:{tsi:-1}, limit:1}
result = {error: "No location saved"} unless result
da ["carpool-api"], "Read location for #{@params.userId}", result
@response.writeHead(200, headers);
@response.end(JSON.stringify(result), "utf-8");
catch e
console.error(e)
@response.writeHead(503, headers);
@response.end("error:"+JSON.stringify(e), "utf-8");
).post(->
location = @request.body
location.tsi = new Date();
location.userId = @params.userId;
da ["carpool-api"], "Create location", location
Locations.insert(location);
headers =
'Content-type': 'application/json; charset=utf-8'
@response.writeHead(200, headers);
result =
status: "ok"
@response.end(JSON.stringify(result), "utf-8");
).put ->
# PUT /webhooks/stripe
return
Router.route('/api/trip/location', where: 'server').get(->
result = { "_id" : "rpfb3p3JBfWYdR3c7", "fromAddress" : "Dzūkų 54, Vilnius", "role" : "driver", "toAddress" : "Šeškinės g. 10, Vilnius", "time" : new Date("2016-03-08T03:29:42.465Z"), "toLoc" : [ 25.25145359999999, 54.71326200000001 ], "fromLoc" : [ 25.289606400000025, 54.6646826 ], "path" : "<KEY>", "stops" : [ ], "owner" : "HX8jY2bnYWGoHB7Em", "requests" : [ ], "status" : "scheduled" }
headers =
'Content-type': 'application/json; charset=utf-8'
@response.writeHead(200, headers);
@response.end(JSON.stringify(result), "utf-8");
)
| true | Router.route('/api/user/:userId/location', where: 'server').get(->
try
headers =
'Content-type': 'application/json; charset=utf-8'
if not apiSecurity.authorize(@params.userId, @params.query.access_token)
@response.writeHead(404, headers);
@response.end(JSON.stringify({error: "Forbiden: token or user is wrong"}), "utf-8");
return
result = Locations.findOne {userId: @params.userId}, {sort:{tsi:-1}, limit:1}
result = {error: "No location saved"} unless result
da ["carpool-api"], "Read location for #{@params.userId}", result
@response.writeHead(200, headers);
@response.end(JSON.stringify(result), "utf-8");
catch e
console.error(e)
@response.writeHead(503, headers);
@response.end("error:"+JSON.stringify(e), "utf-8");
).post(->
location = @request.body
location.tsi = new Date();
location.userId = @params.userId;
da ["carpool-api"], "Create location", location
Locations.insert(location);
headers =
'Content-type': 'application/json; charset=utf-8'
@response.writeHead(200, headers);
result =
status: "ok"
@response.end(JSON.stringify(result), "utf-8");
).put ->
# PUT /webhooks/stripe
return
Router.route('/api/trip/location', where: 'server').get(->
result = { "_id" : "rpfb3p3JBfWYdR3c7", "fromAddress" : "Dzūkų 54, Vilnius", "role" : "driver", "toAddress" : "Šeškinės g. 10, Vilnius", "time" : new Date("2016-03-08T03:29:42.465Z"), "toLoc" : [ 25.25145359999999, 54.71326200000001 ], "fromLoc" : [ 25.289606400000025, 54.6646826 ], "path" : "PI:KEY:<KEY>END_PI", "stops" : [ ], "owner" : "HX8jY2bnYWGoHB7Em", "requests" : [ ], "status" : "scheduled" }
headers =
'Content-type': 'application/json; charset=utf-8'
@response.writeHead(200, headers);
@response.end(JSON.stringify(result), "utf-8");
)
|
[
{
"context": "ers: { Name:{}, State:{} }\n params = { Name:'abc', State: 'Enabled' }\n xml = \"\"\"\n <Data ",
"end": 583,
"score": 0.8625643849372864,
"start": 580,
"tag": "NAME",
"value": "abc"
},
{
"context": " Xyz: 'xyz'\n Abc: 'abc'\n Name: 'john... | test/xml/builder.spec.coffee | daguej/aws-sdk-js | 28 | helpers = require('../helpers')
AWS = helpers.AWS
matchXML = helpers.matchXML
describe 'AWS.XML.Builder', ->
xmlns = 'http://mockservice.com/xmlns'
api = null
beforeEach ->
api = new AWS.Model.Api metadata: xmlNamespace: xmlns
toXML = (rules, params) ->
rules.type = 'structure'
shape = AWS.Model.Shape.create(rules, api: api)
builder = new AWS.XML.Builder()
builder.toXML(params, shape, 'Data')
describe 'toXML', ->
it 'wraps simple structures with location of body', ->
rules = members: { Name:{}, State:{} }
params = { Name:'abc', State: 'Enabled' }
xml = """
<Data xmlns="#{xmlns}">
<Name>abc</Name>
<State>Enabled</State>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'ignores null input', ->
rules = members: { Name:{}, State:{} }
params = { Name:null, State:undefined }
xml = ''
matchXML(toXML(rules, params), xml)
it 'ignores nested null input', ->
rules = members: {Struct:{type: 'structure', members: {State:{}}}}
params = { Struct: { State: null } }
xml = """
<Data xmlns="#{xmlns}">
<Struct/>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'orders xml members by the order they appear in the rules', ->
rules = xmlOrder: ['Count', 'State'], members: {Count:{type:'integer'},State:{}}
params = { State: 'Disabled', Count: 123 }
xml = """
<Data xmlns="#{xmlns}">
<Count>123</Count>
<State>Disabled</State>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'can serializes structures into XML', ->
rules = members:
Name: {}
Details:
type: 'structure'
members:
Abc: {}
Xyz: {}
params =
Details:
Xyz: 'xyz'
Abc: 'abc'
Name: 'john'
xml = """
<Data xmlns="#{xmlns}">
<Name>john</Name>
<Details>
<Abc>abc</Abc>
<Xyz>xyz</Xyz>
</Details>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'serializes empty structures as empty element', ->
rules = {members:{Config:{type:'structure',members:{Foo:{},Bar:{}}}}}
params = { Config: {} }
xml = """
<Data xmlns="#{xmlns}">
<Config/>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'does not serialize missing members', ->
rules = {members:{Config:{type:'structure',members:{Foo:{},Bar:{}}}}}
params = { Config: { Foo: 'abc' } }
xml = """
<Data xmlns="#{xmlns}">
<Config>
<Foo>abc</Foo>
</Config>
</Data>
"""
matchXML(toXML(rules, params), xml)
describe 'lists', ->
it 'serializes lists (default member names)', ->
rules = {members:{Aliases:{type:'list',member:{}}}}
params = {Aliases:['abc','mno','xyz']}
xml = """
<Data xmlns="#{xmlns}">
<Aliases>
<member>abc</member>
<member>mno</member>
<member>xyz</member>
</Aliases>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'serializes lists (custom member names)', ->
rules = {members:{Aliases:{type:'list',member:{locationName:'Alias'}}}}
params = {Aliases:['abc','mno','xyz']}
xml = """
<Data xmlns="#{xmlns}">
<Aliases>
<Alias>abc</Alias>
<Alias>mno</Alias>
<Alias>xyz</Alias>
</Aliases>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'includes lists elements even if they have no members', ->
rules = {members:{Aliases:{type:'list',member:{locationName:'Alias'}}}}
params = {Aliases:[]}
xml = """
<Data xmlns="#{xmlns}">
<Aliases/>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'serializes lists of structures', ->
rules = members:
Points:
type: 'list'
member:
type: 'structure'
locationName: 'Point'
members:
X: {type:'float'}
Y: {type:'float'}
params = {Points:[{X:1.2,Y:2.1},{X:3.4,Y:4.3}]}
xml = """
<Data xmlns="#{xmlns}">
<Points>
<Point>
<X>1.2</X>
<Y>2.1</Y>
</Point>
<Point>
<X>3.4</X>
<Y>4.3</Y>
</Point>
</Points>
</Data>
"""
matchXML(toXML(rules, params), xml)
describe 'flattened lists', ->
it 'serializes lists without a base wrapper', ->
rules = {members:{Aliases:{type:'list',flattened:true,member:{}}}}
params = {Aliases:['abc','mno','xyz']}
xml = """
<Data xmlns="#{xmlns}">
<Aliases>abc</Aliases>
<Aliases>mno</Aliases>
<Aliases>xyz</Aliases>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'serializes lists (custom member names)', ->
rules = members: {Aliases:{type:'list',flattened:true,member:{locationName:'Alias'}}}
params = {Aliases:['abc','mno','xyz']}
xml = """
<Data xmlns="#{xmlns}">
<Alias>abc</Alias>
<Alias>mno</Alias>
<Alias>xyz</Alias>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'omits lists elements when no members are given', ->
rules = {members:{Aliases:{type:'list',flattened:true,member:{locationName:'Alias'}}}}
params = {Aliases:[]}
xml = ''
matchXML(toXML(rules, params), xml)
it 'serializes lists of structures', ->
rules = members:
Points:
type: 'list'
flattened: true
name: 'Point'
member:
type: 'structure'
locationName: 'Point'
members:
X: {type:'float'}
Y: {type:'float'}
params = {Points:[{X:1.2,Y:2.1},{X:3.4,Y:4.3}]}
xml = """
<Data xmlns="#{xmlns}">
<Point>
<X>1.2</X>
<Y>2.1</Y>
</Point>
<Point>
<X>3.4</X>
<Y>4.3</Y>
</Point>
</Data>
"""
matchXML(toXML(rules, params), xml)
describe 'maps', ->
rules =
type: 'structure'
members:
Items:
type: 'map'
key: type: 'string'
value: type: 'string'
it 'translates maps', ->
params = { Items: { A: 'a', B: 'b' } }
xml = """
<Data xmlns="#{xmlns}">
<Items>
<entry>
<key>A</key>
<value>a</value>
</entry>
<entry>
<key>B</key>
<value>b</value>
</entry>
</Items>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'allows renamed map keys and values', ->
params = { Items: { A: 'a', B: 'b' } }
otherRules =
type: 'structure'
members:
Items:
type: 'map'
key: type: 'string', locationName: 'MKEY'
value: type: 'string', locationName: 'MVALUE'
xml = """
<Data xmlns="#{xmlns}">
<Items>
<entry>
<MKEY>A</MKEY>
<MVALUE>a</MVALUE>
</entry>
<entry>
<MKEY>B</MKEY>
<MVALUE>b</MVALUE>
</entry>
</Items>
</Data>
"""
matchXML(toXML(otherRules, params), xml)
it 'ignores null', ->
expect(toXML(rules, Items: null)).to.equal('')
it 'ignores undefined', ->
expect(toXML(rules, Items: undefined)).to.equal('')
describe 'flattened maps', ->
rules =
type: 'structure'
members:
Items:
type: 'map'
locationName: 'Item'
flattened: true
key: type: 'string'
value: type: 'string'
it 'translates flattened maps', ->
params = { Items: { A: 'a', B: 'b' } }
xml = """
<Data xmlns="#{xmlns}">
<Item>
<key>A</key>
<value>a</value>
</Item>
<Item>
<key>B</key>
<value>b</value>
</Item>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'allows renamed map keys and values', ->
params = { Items: { A: 'a', B: 'b' } }
otherRules =
type: 'structure'
members:
Items:
locationName: 'Item'
flattened: true
type: 'map'
key: type: 'string', locationName: 'MKEY'
value: type: 'string', locationName: 'MVALUE'
xml = """
<Data xmlns="#{xmlns}">
<Item>
<MKEY>A</MKEY>
<MVALUE>a</MVALUE>
</Item>
<Item>
<MKEY>B</MKEY>
<MVALUE>b</MVALUE>
</Item>
</Data>
"""
matchXML(toXML(otherRules, params), xml)
it 'ignores null', ->
expect(toXML(rules, Items: null)).to.equal('')
it 'ignores undefined', ->
expect(toXML(rules, Items: undefined)).to.equal('')
describe 'numbers', ->
it 'integers', ->
rules = members: {Count:{type:'integer'}}
params = { Count: 123.0 }
xml = """
<Data xmlns="#{xmlns}">
<Count>123</Count>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'floats', ->
rules = members: {Count:{type:'float'}}
params = { Count: 123.123 }
xml = """
<Data xmlns="#{xmlns}">
<Count>123.123</Count>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'ints and floats formatted as numbers', ->
rules = members: {CountI:{type:'integer'},CountF:{type:'float'}}
params = { CountI: '123', CountF: '1.23' }
xml = """
<Data xmlns="#{xmlns}">
<CountI>123</CountI>
<CountF>1.23</CountF>
</Data>
"""
matchXML(toXML(rules, params), xml)
describe 'booleans', ->
it 'true', ->
rules = members: {Enabled:{type:'boolean'}}
params = { Enabled: true }
xml = """
<Data xmlns="#{xmlns}">
<Enabled>true</Enabled>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'false', ->
rules = members: {Enabled:{type:'boolean'}}
params = { Enabled: false }
xml = """
<Data xmlns="#{xmlns}">
<Enabled>false</Enabled>
</Data>
"""
matchXML(toXML(rules, params), xml)
describe 'timestamps', ->
time = new Date()
time.setMilliseconds(0)
it 'iso8601', ->
api.timestampFormat = 'iso8601'
rules = members: {Expires:{type:'timestamp'}}
params = { Expires: time }
xml = """
<Data xmlns="#{xmlns}">
<Expires>#{AWS.util.date.iso8601(time)}</Expires>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'rfc822', ->
api.timestampFormat = 'rfc822'
rules = members: {Expires:{type:'timestamp'}}
params = { Expires: time }
xml = """
<Data xmlns="#{xmlns}">
<Expires>#{AWS.util.date.rfc822(time)}</Expires>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'unix timestamp', ->
api.timestampFormat = 'unixTimestamp'
rules = members: {Expires:{type:'timestamp'}}
params = { Expires: time }
xml = """
<Data xmlns="#{xmlns}">
<Expires>#{AWS.util.date.unixTimestamp(time)}</Expires>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'follows the forat given on the shape', ->
api.timestampFormat = 'unixTimestamp'
rules = members: {Expires:{type:'timestamp',timestampFormat:'rfc822'}}
params = { Expires: time }
# despite the api configuration will specify unixTimesmap, we expect
# an rfc822 formatted date based on the format attribute
xml = """
<Data xmlns="#{xmlns}">
<Expires>#{AWS.util.date.rfc822(time)}</Expires>
</Data>
"""
matchXML(toXML(rules, params), xml)
describe 'xml attributes', ->
it 'can serialize xml attributes', ->
rules = members:
Config:
type: 'structure'
members:
Foo:
type: 'string'
Attr:
type: 'string'
xmlAttribute: true
locationName: 'attr:name'
params = { Config: { Foo: 'bar', Attr: 'abc' } }
xml = """
<Data xmlns="#{xmlns}">
<Config attr:name="abc"><Foo>bar</Foo></Config>
</Data>
"""
matchXML(toXML(rules, params), xml)
describe 'xml namespaces', ->
it 'can apply xml namespaces on structures', ->
rules = members:
Config:
type: 'structure'
xmlNamespace:
uri: 'URI'
members:
Foo:
type: 'string'
params = { Config: { Foo: 'bar' } }
xml = """
<Data xmlns="#{xmlns}">
<Config xmlns="URI"><Foo>bar</Foo></Config>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'applies namespace prefixes to the xmlns attribute', ->
rules = members:
Config:
type: 'structure'
xmlNamespace:
prefix: 'xsi'
uri: 'URI'
members:
Foo:
type: 'string'
params = { Config: { Foo: 'bar' } }
xml = """
<Data xmlns="#{xmlns}">
<Config xmlns:xsi="URI"><Foo>bar</Foo></Config>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'can apply namespaces to elements that have other attributes', ->
rules = members:
Config:
type: 'structure'
xmlNamespace:
prefix: 'xsi'
uri: 'URI'
members:
Foo:
type: 'string'
Bar:
type: 'string'
xmlAttribute: true
locationName: 'xsi:label'
params = { Config: { Foo: 'abc', Bar: 'xyz' } }
xml = """
<Data xmlns="#{xmlns}">
<Config xmlns:xsi="URI" xsi:label="xyz"><Foo>abc</Foo></Config>
</Data>
"""
matchXML(toXML(rules, params), xml)
| 58355 | helpers = require('../helpers')
AWS = helpers.AWS
matchXML = helpers.matchXML
describe 'AWS.XML.Builder', ->
xmlns = 'http://mockservice.com/xmlns'
api = null
beforeEach ->
api = new AWS.Model.Api metadata: xmlNamespace: xmlns
toXML = (rules, params) ->
rules.type = 'structure'
shape = AWS.Model.Shape.create(rules, api: api)
builder = new AWS.XML.Builder()
builder.toXML(params, shape, 'Data')
describe 'toXML', ->
it 'wraps simple structures with location of body', ->
rules = members: { Name:{}, State:{} }
params = { Name:'<NAME>', State: 'Enabled' }
xml = """
<Data xmlns="#{xmlns}">
<Name>abc</Name>
<State>Enabled</State>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'ignores null input', ->
rules = members: { Name:{}, State:{} }
params = { Name:null, State:undefined }
xml = ''
matchXML(toXML(rules, params), xml)
it 'ignores nested null input', ->
rules = members: {Struct:{type: 'structure', members: {State:{}}}}
params = { Struct: { State: null } }
xml = """
<Data xmlns="#{xmlns}">
<Struct/>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'orders xml members by the order they appear in the rules', ->
rules = xmlOrder: ['Count', 'State'], members: {Count:{type:'integer'},State:{}}
params = { State: 'Disabled', Count: 123 }
xml = """
<Data xmlns="#{xmlns}">
<Count>123</Count>
<State>Disabled</State>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'can serializes structures into XML', ->
rules = members:
Name: {}
Details:
type: 'structure'
members:
Abc: {}
Xyz: {}
params =
Details:
Xyz: 'xyz'
Abc: 'abc'
Name: '<NAME>'
xml = """
<Data xmlns="#{xmlns}">
<Name><NAME></Name>
<Details>
<Abc>abc</Abc>
<Xyz>xyz</Xyz>
</Details>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'serializes empty structures as empty element', ->
rules = {members:{Config:{type:'structure',members:{Foo:{},Bar:{}}}}}
params = { Config: {} }
xml = """
<Data xmlns="#{xmlns}">
<Config/>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'does not serialize missing members', ->
rules = {members:{Config:{type:'structure',members:{Foo:{},Bar:{}}}}}
params = { Config: { Foo: 'abc' } }
xml = """
<Data xmlns="#{xmlns}">
<Config>
<Foo>abc</Foo>
</Config>
</Data>
"""
matchXML(toXML(rules, params), xml)
describe 'lists', ->
it 'serializes lists (default member names)', ->
rules = {members:{Aliases:{type:'list',member:{}}}}
params = {Aliases:['abc','mno','xyz']}
xml = """
<Data xmlns="#{xmlns}">
<Aliases>
<member>abc</member>
<member>mno</member>
<member>xyz</member>
</Aliases>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'serializes lists (custom member names)', ->
rules = {members:{Aliases:{type:'list',member:{locationName:'Alias'}}}}
params = {Aliases:['abc','mno','xyz']}
xml = """
<Data xmlns="#{xmlns}">
<Aliases>
<Alias>abc</Alias>
<Alias>mno</Alias>
<Alias>xyz</Alias>
</Aliases>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'includes lists elements even if they have no members', ->
rules = {members:{Aliases:{type:'list',member:{locationName:'Alias'}}}}
params = {Aliases:[]}
xml = """
<Data xmlns="#{xmlns}">
<Aliases/>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'serializes lists of structures', ->
rules = members:
Points:
type: 'list'
member:
type: 'structure'
locationName: 'Point'
members:
X: {type:'float'}
Y: {type:'float'}
params = {Points:[{X:1.2,Y:2.1},{X:3.4,Y:4.3}]}
xml = """
<Data xmlns="#{xmlns}">
<Points>
<Point>
<X>1.2</X>
<Y>2.1</Y>
</Point>
<Point>
<X>3.4</X>
<Y>4.3</Y>
</Point>
</Points>
</Data>
"""
matchXML(toXML(rules, params), xml)
describe 'flattened lists', ->
it 'serializes lists without a base wrapper', ->
rules = {members:{Aliases:{type:'list',flattened:true,member:{}}}}
params = {Aliases:['abc','mno','xyz']}
xml = """
<Data xmlns="#{xmlns}">
<Aliases>abc</Aliases>
<Aliases>mno</Aliases>
<Aliases>xyz</Aliases>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'serializes lists (custom member names)', ->
rules = members: {Aliases:{type:'list',flattened:true,member:{locationName:'Alias'}}}
params = {Aliases:['abc','mno','xyz']}
xml = """
<Data xmlns="#{xmlns}">
<Alias>abc</Alias>
<Alias>mno</Alias>
<Alias>xyz</Alias>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'omits lists elements when no members are given', ->
rules = {members:{Aliases:{type:'list',flattened:true,member:{locationName:'Alias'}}}}
params = {Aliases:[]}
xml = ''
matchXML(toXML(rules, params), xml)
it 'serializes lists of structures', ->
rules = members:
Points:
type: 'list'
flattened: true
name: '<NAME>'
member:
type: 'structure'
locationName: 'Point'
members:
X: {type:'float'}
Y: {type:'float'}
params = {Points:[{X:1.2,Y:2.1},{X:3.4,Y:4.3}]}
xml = """
<Data xmlns="#{xmlns}">
<Point>
<X>1.2</X>
<Y>2.1</Y>
</Point>
<Point>
<X>3.4</X>
<Y>4.3</Y>
</Point>
</Data>
"""
matchXML(toXML(rules, params), xml)
describe 'maps', ->
rules =
type: 'structure'
members:
Items:
type: 'map'
key: type: 'string'
value: type: 'string'
it 'translates maps', ->
params = { Items: { A: 'a', B: 'b' } }
xml = """
<Data xmlns="#{xmlns}">
<Items>
<entry>
<key>A</key>
<value>a</value>
</entry>
<entry>
<key>B</key>
<value>b</value>
</entry>
</Items>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'allows renamed map keys and values', ->
params = { Items: { A: 'a', B: 'b' } }
otherRules =
type: 'structure'
members:
Items:
type: 'map'
key: type: 'string', locationName: 'MKEY'
value: type: 'string', locationName: 'MVALUE'
xml = """
<Data xmlns="#{xmlns}">
<Items>
<entry>
<MKEY>A</MKEY>
<MVALUE>a</MVALUE>
</entry>
<entry>
<MKEY>B</MKEY>
<MVALUE>b</MVALUE>
</entry>
</Items>
</Data>
"""
matchXML(toXML(otherRules, params), xml)
it 'ignores null', ->
expect(toXML(rules, Items: null)).to.equal('')
it 'ignores undefined', ->
expect(toXML(rules, Items: undefined)).to.equal('')
describe 'flattened maps', ->
rules =
type: 'structure'
members:
Items:
type: 'map'
locationName: 'Item'
flattened: true
key: type: 'string'
value: type: 'string'
it 'translates flattened maps', ->
params = { Items: { A: 'a', B: 'b' } }
xml = """
<Data xmlns="#{xmlns}">
<Item>
<key>A</key>
<value>a</value>
</Item>
<Item>
<key>B</key>
<value>b</value>
</Item>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'allows renamed map keys and values', ->
params = { Items: { A: 'a', B: 'b' } }
otherRules =
type: 'structure'
members:
Items:
locationName: 'Item'
flattened: true
type: 'map'
key: type: 'string', locationName: 'MKEY'
value: type: 'string', locationName: 'MVALUE'
xml = """
<Data xmlns="#{xmlns}">
<Item>
<MKEY>A</MKEY>
<MVALUE>a</MVALUE>
</Item>
<Item>
<MKEY>B</MKEY>
<MVALUE>b</MVALUE>
</Item>
</Data>
"""
matchXML(toXML(otherRules, params), xml)
it 'ignores null', ->
expect(toXML(rules, Items: null)).to.equal('')
it 'ignores undefined', ->
expect(toXML(rules, Items: undefined)).to.equal('')
describe 'numbers', ->
it 'integers', ->
rules = members: {Count:{type:'integer'}}
params = { Count: 123.0 }
xml = """
<Data xmlns="#{xmlns}">
<Count>123</Count>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'floats', ->
rules = members: {Count:{type:'float'}}
params = { Count: 123.123 }
xml = """
<Data xmlns="#{xmlns}">
<Count>123.123</Count>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'ints and floats formatted as numbers', ->
rules = members: {CountI:{type:'integer'},CountF:{type:'float'}}
params = { CountI: '123', CountF: '1.23' }
xml = """
<Data xmlns="#{xmlns}">
<CountI>123</CountI>
<CountF>1.23</CountF>
</Data>
"""
matchXML(toXML(rules, params), xml)
describe 'booleans', ->
it 'true', ->
rules = members: {Enabled:{type:'boolean'}}
params = { Enabled: true }
xml = """
<Data xmlns="#{xmlns}">
<Enabled>true</Enabled>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'false', ->
rules = members: {Enabled:{type:'boolean'}}
params = { Enabled: false }
xml = """
<Data xmlns="#{xmlns}">
<Enabled>false</Enabled>
</Data>
"""
matchXML(toXML(rules, params), xml)
describe 'timestamps', ->
time = new Date()
time.setMilliseconds(0)
it 'iso8601', ->
api.timestampFormat = 'iso8601'
rules = members: {Expires:{type:'timestamp'}}
params = { Expires: time }
xml = """
<Data xmlns="#{xmlns}">
<Expires>#{AWS.util.date.iso8601(time)}</Expires>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'rfc822', ->
api.timestampFormat = 'rfc822'
rules = members: {Expires:{type:'timestamp'}}
params = { Expires: time }
xml = """
<Data xmlns="#{xmlns}">
<Expires>#{AWS.util.date.rfc822(time)}</Expires>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'unix timestamp', ->
api.timestampFormat = 'unixTimestamp'
rules = members: {Expires:{type:'timestamp'}}
params = { Expires: time }
xml = """
<Data xmlns="#{xmlns}">
<Expires>#{AWS.util.date.unixTimestamp(time)}</Expires>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'follows the forat given on the shape', ->
api.timestampFormat = 'unixTimestamp'
rules = members: {Expires:{type:'timestamp',timestampFormat:'rfc822'}}
params = { Expires: time }
# despite the api configuration will specify unixTimesmap, we expect
# an rfc822 formatted date based on the format attribute
xml = """
<Data xmlns="#{xmlns}">
<Expires>#{AWS.util.date.rfc822(time)}</Expires>
</Data>
"""
matchXML(toXML(rules, params), xml)
describe 'xml attributes', ->
it 'can serialize xml attributes', ->
rules = members:
Config:
type: 'structure'
members:
Foo:
type: 'string'
Attr:
type: 'string'
xmlAttribute: true
locationName: 'attr:name'
params = { Config: { Foo: 'bar', Attr: 'abc' } }
xml = """
<Data xmlns="#{xmlns}">
<Config attr:name="abc"><Foo>bar</Foo></Config>
</Data>
"""
matchXML(toXML(rules, params), xml)
describe 'xml namespaces', ->
it 'can apply xml namespaces on structures', ->
rules = members:
Config:
type: 'structure'
xmlNamespace:
uri: 'URI'
members:
Foo:
type: 'string'
params = { Config: { Foo: 'bar' } }
xml = """
<Data xmlns="#{xmlns}">
<Config xmlns="URI"><Foo>bar</Foo></Config>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'applies namespace prefixes to the xmlns attribute', ->
rules = members:
Config:
type: 'structure'
xmlNamespace:
prefix: 'xsi'
uri: 'URI'
members:
Foo:
type: 'string'
params = { Config: { Foo: 'bar' } }
xml = """
<Data xmlns="#{xmlns}">
<Config xmlns:xsi="URI"><Foo>bar</Foo></Config>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'can apply namespaces to elements that have other attributes', ->
rules = members:
Config:
type: 'structure'
xmlNamespace:
prefix: 'xsi'
uri: 'URI'
members:
Foo:
type: 'string'
Bar:
type: 'string'
xmlAttribute: true
locationName: 'xsi:label'
params = { Config: { Foo: 'abc', Bar: 'xyz' } }
xml = """
<Data xmlns="#{xmlns}">
<Config xmlns:xsi="URI" xsi:label="xyz"><Foo>abc</Foo></Config>
</Data>
"""
matchXML(toXML(rules, params), xml)
| true | helpers = require('../helpers')
AWS = helpers.AWS
matchXML = helpers.matchXML
describe 'AWS.XML.Builder', ->
xmlns = 'http://mockservice.com/xmlns'
api = null
beforeEach ->
api = new AWS.Model.Api metadata: xmlNamespace: xmlns
toXML = (rules, params) ->
rules.type = 'structure'
shape = AWS.Model.Shape.create(rules, api: api)
builder = new AWS.XML.Builder()
builder.toXML(params, shape, 'Data')
describe 'toXML', ->
it 'wraps simple structures with location of body', ->
rules = members: { Name:{}, State:{} }
params = { Name:'PI:NAME:<NAME>END_PI', State: 'Enabled' }
xml = """
<Data xmlns="#{xmlns}">
<Name>abc</Name>
<State>Enabled</State>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'ignores null input', ->
rules = members: { Name:{}, State:{} }
params = { Name:null, State:undefined }
xml = ''
matchXML(toXML(rules, params), xml)
it 'ignores nested null input', ->
rules = members: {Struct:{type: 'structure', members: {State:{}}}}
params = { Struct: { State: null } }
xml = """
<Data xmlns="#{xmlns}">
<Struct/>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'orders xml members by the order they appear in the rules', ->
rules = xmlOrder: ['Count', 'State'], members: {Count:{type:'integer'},State:{}}
params = { State: 'Disabled', Count: 123 }
xml = """
<Data xmlns="#{xmlns}">
<Count>123</Count>
<State>Disabled</State>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'can serializes structures into XML', ->
rules = members:
Name: {}
Details:
type: 'structure'
members:
Abc: {}
Xyz: {}
params =
Details:
Xyz: 'xyz'
Abc: 'abc'
Name: 'PI:NAME:<NAME>END_PI'
xml = """
<Data xmlns="#{xmlns}">
<Name>PI:NAME:<NAME>END_PI</Name>
<Details>
<Abc>abc</Abc>
<Xyz>xyz</Xyz>
</Details>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'serializes empty structures as empty element', ->
rules = {members:{Config:{type:'structure',members:{Foo:{},Bar:{}}}}}
params = { Config: {} }
xml = """
<Data xmlns="#{xmlns}">
<Config/>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'does not serialize missing members', ->
rules = {members:{Config:{type:'structure',members:{Foo:{},Bar:{}}}}}
params = { Config: { Foo: 'abc' } }
xml = """
<Data xmlns="#{xmlns}">
<Config>
<Foo>abc</Foo>
</Config>
</Data>
"""
matchXML(toXML(rules, params), xml)
describe 'lists', ->
it 'serializes lists (default member names)', ->
rules = {members:{Aliases:{type:'list',member:{}}}}
params = {Aliases:['abc','mno','xyz']}
xml = """
<Data xmlns="#{xmlns}">
<Aliases>
<member>abc</member>
<member>mno</member>
<member>xyz</member>
</Aliases>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'serializes lists (custom member names)', ->
rules = {members:{Aliases:{type:'list',member:{locationName:'Alias'}}}}
params = {Aliases:['abc','mno','xyz']}
xml = """
<Data xmlns="#{xmlns}">
<Aliases>
<Alias>abc</Alias>
<Alias>mno</Alias>
<Alias>xyz</Alias>
</Aliases>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'includes lists elements even if they have no members', ->
rules = {members:{Aliases:{type:'list',member:{locationName:'Alias'}}}}
params = {Aliases:[]}
xml = """
<Data xmlns="#{xmlns}">
<Aliases/>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'serializes lists of structures', ->
rules = members:
Points:
type: 'list'
member:
type: 'structure'
locationName: 'Point'
members:
X: {type:'float'}
Y: {type:'float'}
params = {Points:[{X:1.2,Y:2.1},{X:3.4,Y:4.3}]}
xml = """
<Data xmlns="#{xmlns}">
<Points>
<Point>
<X>1.2</X>
<Y>2.1</Y>
</Point>
<Point>
<X>3.4</X>
<Y>4.3</Y>
</Point>
</Points>
</Data>
"""
matchXML(toXML(rules, params), xml)
describe 'flattened lists', ->
it 'serializes lists without a base wrapper', ->
rules = {members:{Aliases:{type:'list',flattened:true,member:{}}}}
params = {Aliases:['abc','mno','xyz']}
xml = """
<Data xmlns="#{xmlns}">
<Aliases>abc</Aliases>
<Aliases>mno</Aliases>
<Aliases>xyz</Aliases>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'serializes lists (custom member names)', ->
rules = members: {Aliases:{type:'list',flattened:true,member:{locationName:'Alias'}}}
params = {Aliases:['abc','mno','xyz']}
xml = """
<Data xmlns="#{xmlns}">
<Alias>abc</Alias>
<Alias>mno</Alias>
<Alias>xyz</Alias>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'omits lists elements when no members are given', ->
rules = {members:{Aliases:{type:'list',flattened:true,member:{locationName:'Alias'}}}}
params = {Aliases:[]}
xml = ''
matchXML(toXML(rules, params), xml)
it 'serializes lists of structures', ->
rules = members:
Points:
type: 'list'
flattened: true
name: 'PI:NAME:<NAME>END_PI'
member:
type: 'structure'
locationName: 'Point'
members:
X: {type:'float'}
Y: {type:'float'}
params = {Points:[{X:1.2,Y:2.1},{X:3.4,Y:4.3}]}
xml = """
<Data xmlns="#{xmlns}">
<Point>
<X>1.2</X>
<Y>2.1</Y>
</Point>
<Point>
<X>3.4</X>
<Y>4.3</Y>
</Point>
</Data>
"""
matchXML(toXML(rules, params), xml)
describe 'maps', ->
rules =
type: 'structure'
members:
Items:
type: 'map'
key: type: 'string'
value: type: 'string'
it 'translates maps', ->
params = { Items: { A: 'a', B: 'b' } }
xml = """
<Data xmlns="#{xmlns}">
<Items>
<entry>
<key>A</key>
<value>a</value>
</entry>
<entry>
<key>B</key>
<value>b</value>
</entry>
</Items>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'allows renamed map keys and values', ->
params = { Items: { A: 'a', B: 'b' } }
otherRules =
type: 'structure'
members:
Items:
type: 'map'
key: type: 'string', locationName: 'MKEY'
value: type: 'string', locationName: 'MVALUE'
xml = """
<Data xmlns="#{xmlns}">
<Items>
<entry>
<MKEY>A</MKEY>
<MVALUE>a</MVALUE>
</entry>
<entry>
<MKEY>B</MKEY>
<MVALUE>b</MVALUE>
</entry>
</Items>
</Data>
"""
matchXML(toXML(otherRules, params), xml)
it 'ignores null', ->
expect(toXML(rules, Items: null)).to.equal('')
it 'ignores undefined', ->
expect(toXML(rules, Items: undefined)).to.equal('')
describe 'flattened maps', ->
rules =
type: 'structure'
members:
Items:
type: 'map'
locationName: 'Item'
flattened: true
key: type: 'string'
value: type: 'string'
it 'translates flattened maps', ->
params = { Items: { A: 'a', B: 'b' } }
xml = """
<Data xmlns="#{xmlns}">
<Item>
<key>A</key>
<value>a</value>
</Item>
<Item>
<key>B</key>
<value>b</value>
</Item>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'allows renamed map keys and values', ->
params = { Items: { A: 'a', B: 'b' } }
otherRules =
type: 'structure'
members:
Items:
locationName: 'Item'
flattened: true
type: 'map'
key: type: 'string', locationName: 'MKEY'
value: type: 'string', locationName: 'MVALUE'
xml = """
<Data xmlns="#{xmlns}">
<Item>
<MKEY>A</MKEY>
<MVALUE>a</MVALUE>
</Item>
<Item>
<MKEY>B</MKEY>
<MVALUE>b</MVALUE>
</Item>
</Data>
"""
matchXML(toXML(otherRules, params), xml)
it 'ignores null', ->
expect(toXML(rules, Items: null)).to.equal('')
it 'ignores undefined', ->
expect(toXML(rules, Items: undefined)).to.equal('')
describe 'numbers', ->
it 'integers', ->
rules = members: {Count:{type:'integer'}}
params = { Count: 123.0 }
xml = """
<Data xmlns="#{xmlns}">
<Count>123</Count>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'floats', ->
rules = members: {Count:{type:'float'}}
params = { Count: 123.123 }
xml = """
<Data xmlns="#{xmlns}">
<Count>123.123</Count>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'ints and floats formatted as numbers', ->
rules = members: {CountI:{type:'integer'},CountF:{type:'float'}}
params = { CountI: '123', CountF: '1.23' }
xml = """
<Data xmlns="#{xmlns}">
<CountI>123</CountI>
<CountF>1.23</CountF>
</Data>
"""
matchXML(toXML(rules, params), xml)
describe 'booleans', ->
it 'true', ->
rules = members: {Enabled:{type:'boolean'}}
params = { Enabled: true }
xml = """
<Data xmlns="#{xmlns}">
<Enabled>true</Enabled>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'false', ->
rules = members: {Enabled:{type:'boolean'}}
params = { Enabled: false }
xml = """
<Data xmlns="#{xmlns}">
<Enabled>false</Enabled>
</Data>
"""
matchXML(toXML(rules, params), xml)
describe 'timestamps', ->
time = new Date()
time.setMilliseconds(0)
it 'iso8601', ->
api.timestampFormat = 'iso8601'
rules = members: {Expires:{type:'timestamp'}}
params = { Expires: time }
xml = """
<Data xmlns="#{xmlns}">
<Expires>#{AWS.util.date.iso8601(time)}</Expires>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'rfc822', ->
api.timestampFormat = 'rfc822'
rules = members: {Expires:{type:'timestamp'}}
params = { Expires: time }
xml = """
<Data xmlns="#{xmlns}">
<Expires>#{AWS.util.date.rfc822(time)}</Expires>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'unix timestamp', ->
api.timestampFormat = 'unixTimestamp'
rules = members: {Expires:{type:'timestamp'}}
params = { Expires: time }
xml = """
<Data xmlns="#{xmlns}">
<Expires>#{AWS.util.date.unixTimestamp(time)}</Expires>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'follows the forat given on the shape', ->
api.timestampFormat = 'unixTimestamp'
rules = members: {Expires:{type:'timestamp',timestampFormat:'rfc822'}}
params = { Expires: time }
# despite the api configuration will specify unixTimesmap, we expect
# an rfc822 formatted date based on the format attribute
xml = """
<Data xmlns="#{xmlns}">
<Expires>#{AWS.util.date.rfc822(time)}</Expires>
</Data>
"""
matchXML(toXML(rules, params), xml)
describe 'xml attributes', ->
it 'can serialize xml attributes', ->
rules = members:
Config:
type: 'structure'
members:
Foo:
type: 'string'
Attr:
type: 'string'
xmlAttribute: true
locationName: 'attr:name'
params = { Config: { Foo: 'bar', Attr: 'abc' } }
xml = """
<Data xmlns="#{xmlns}">
<Config attr:name="abc"><Foo>bar</Foo></Config>
</Data>
"""
matchXML(toXML(rules, params), xml)
describe 'xml namespaces', ->
it 'can apply xml namespaces on structures', ->
rules = members:
Config:
type: 'structure'
xmlNamespace:
uri: 'URI'
members:
Foo:
type: 'string'
params = { Config: { Foo: 'bar' } }
xml = """
<Data xmlns="#{xmlns}">
<Config xmlns="URI"><Foo>bar</Foo></Config>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'applies namespace prefixes to the xmlns attribute', ->
rules = members:
Config:
type: 'structure'
xmlNamespace:
prefix: 'xsi'
uri: 'URI'
members:
Foo:
type: 'string'
params = { Config: { Foo: 'bar' } }
xml = """
<Data xmlns="#{xmlns}">
<Config xmlns:xsi="URI"><Foo>bar</Foo></Config>
</Data>
"""
matchXML(toXML(rules, params), xml)
it 'can apply namespaces to elements that have other attributes', ->
rules = members:
Config:
type: 'structure'
xmlNamespace:
prefix: 'xsi'
uri: 'URI'
members:
Foo:
type: 'string'
Bar:
type: 'string'
xmlAttribute: true
locationName: 'xsi:label'
params = { Config: { Foo: 'abc', Bar: 'xyz' } }
xml = """
<Data xmlns="#{xmlns}">
<Config xmlns:xsi="URI" xsi:label="xyz"><Foo>abc</Foo></Config>
</Data>
"""
matchXML(toXML(rules, params), xml)
|
[
{
"context": "ail: 'E-Mail'\n full_name: 'Full Name'\n language_choice: 'Language Choice'\n ",
"end": 3668,
"score": 0.925242006778717,
"start": 3659,
"tag": "NAME",
"value": "Full Name"
},
{
"context": "k_as: 'Mark as'\n old_password: ... | app/assets/javascripts/i18n.js.coffee | fwoeck/voice-rails | 1 | env.i18n =
en:
dialog:
agent_created: 'You successfully added the new user<br /><strong>NAME</strong>.'
browser_warning: 'For now, Chrome CHROME+ and Firefox FIREFOX+ are the only supported browsers. Use this platform at own risk.'
call_failed: 'Sorry, your call to<br /><strong>TO</strong> failed.'
call_rejected: 'Sorry, your call to<br /><strong>TO</strong> was rejected.'
callee_busy: 'The callee is currently busy:<br /><strong>TO</strong>.'
cancel: 'Cancel'
dial_now: 'Dial now'
enter_number: 'Please enter a number to dial:'
form_with_errors: 'One or more fields contain invalid data. Please fill them in correctly and try again.'
hangup: 'Hangup'
hangup_this_call: 'Do you want to hangup this call?'
i_am_busy: 'I\'m busy'
incoming_call: 'You have an incoming call from<br /><strong>NAME</strong>.'
lost_server_conn: 'Sorry, we lost our connection to the server —<br />please check your network and try to re-login.'
no_messages: 'Sorry, we stopped receiving messages —<br />please open just one app window at a time.'
ok: 'Ok'
outgoing_call: 'You are about to call<br /><strong>NAME</strong>.'
proceed: 'Proceed'
no_hungup_call: 'This is only available after you finished a call.'
reload_necessary: 'We need to reload the browser window to activate the new settings.'
reload: 'Reload'
shortcut_header: 'Keyboard shortcuts'
take_call: 'Take call'
transfer_call: 'Do you want to transfer this call to<br /><strong>AGENT</strong>?'
transfer: 'Transfer'
yes: 'Yes'
agents:
agent_is: 'agent is'
agents_are: 'agents are'
available: 'available'
status:
away: 'I\'m away from desk'
busy: 'I\'m currently busy'
ready: 'I\'m ready to take calls'
silent: 'I\'m silent'
ringing: 'I\'m receiving a call'
talking: 'I\'m currently talking'
unknown: 'Availability unknown'
customers:
customer_is: 'customer is'
customers_are: 'customers are'
queued: 'queued'
crmuser:
create_ticket: "Create a #{env.crmProvider} ticket from this call"
default_subject: 'Ticket for CALL'
recent_tickets: "Recent tickets at #{env.crmProvider}"
request_new_user: "Request a new #{env.crmProvider} user for this customer"
help:
A: 'CR: Confirm current dialog'
B: 'ESC: Close current dialog'
a: 'Ctrl+A: Show the agents page'
b: 'Ctrl+B: Set my state to "busy"'
d: 'Ctrl+D: Show the dashboard'
f: 'Ctrl+F: Filter the agent list'
h: 'Ctrl+H: Hangup the current call'
i: 'Ctrl+I: Show this shortcut list'
m: 'Ctrl+M: Type a chat message'
o: 'Ctrl+O: Dial an outbound number'
r: 'Ctrl+R: Set my state to "ready"'
s: 'Ctrl+S: Show the stats page'
x: 'Ctrl+X: Hide the call display'
domain:
agent: 'Agent'
answered_at: 'Answered at'
availability: 'Availability'
called_at: 'Called at'
caller_id: 'Caller Id'
clear: 'Clear'
email: 'E-Mail'
full_name: 'Full Name'
language_choice: 'Language Choice'
language: 'Language'
languages: 'Languages'
line: 'Line'
logout: 'Logout'
mailbox: 'Mailbox'
mark_as: 'Mark as'
old_password: 'Old Password'
password: 'New Password'
confirmation: 'Password Confirmation'
queued_at: 'Queued at'
remarks: 'Remarks'
roles: 'Roles'
requested_skill: 'Requested Skill'
save_record: 'Save Record'
save_profile: 'Save Profile'
sip_extension: 'SIP Extension'
sip_secret: 'SIP Password'
skills: 'Skills'
ui_locale: 'Browser Locale'
user: 'user'
crmuser_id: "#{env.crmProvider} Id"
headers:
agent_management: 'Agent Management'
agent_overview: 'Agent Overview'
agent_profile: 'Agent Profile'
agent_table: 'Agent Table'
agent_list: 'Agent List'
callcenter_stats: 'Call Center Statistics'
call_statistics: 'Call Statistics'
connected_agents: 'Connected Agents'
current_calls: 'Current Calls'
customer_history: 'Customer history'
customers: 'Customers'
dashboard: 'Dashboard'
details_for: 'Details for'
help: 'Help'
inbound_calls: 'Inbound Calls'
media_player: 'Show media player..'
my_settings: 'My Settings'
new_agent: 'Add an Agent'
new_customers: 'New Customers'
show_dispatched: 'Show dispatched'
team_chat: 'Team Chat'
use_auto_ready: 'Use auto-ready'
use_web_phone: 'Use the web-phone'
calls:
active_calls: 'Active calls'
avg_queue_delay: '∅ Queue delay'
call_count: 'Count'
call_queue_empty: 'The call queue is empty right now.'
dispatched_calls: 'Dispatched calls'
hungup_call_to: 'Your finished call to'
incoming_calls: 'Incoming calls'
max_queue_delay: 'Max. queue delay'
queued_calls: 'Queued calls'
seconds: 'Seconds'
you_are_talking: 'You are talking to'
placeholder:
an_email_address: 'An e-mail address..'
enter_entry_tags: 'Enter some tags..'
enter_remarks: 'Enter remarks for this call..'
enter_timespan: 'Enter a timespan..'
find_an_agent: 'Find an agent..'
find_calls: 'Enter call specific terms..'
find_customers: 'Enter customer related terms..'
no_recent_messg: 'There are no recent messages in the team chat until now — be the first to write one!'
optional_text: 'Enter optional text..'
refresh_tickets: "Refresh this customer's #{env.crmProvider} tickets"
the_full_name: 'The full name..'
the_user_id: 'User Id..'
type_a_number: 'Type a number..'
type_here: 'Type here..'
errors:
ajax_error: 'Sorry, the server returned an error message:<br />MSG'
crmuser_format: 'Enter 9 digits'
email_format: 'Enter a valid email address'
extension_format: 'Enter 3 digits'
fullname_format: 'Enter the agent\'s full name'
line_is_busy: 'Please hangup and close the current call display, before you dial again.'
must_be_text: 'Enter some words'
number_format: 'Local numbers: 030... / Intl. numbers: 0049...'
password_format: 'Enter 8 or more chars.: 1 lower, 1 upper, 1 digit'
password_match: 'Must match the first password'
routing_error: 'Sorry, an error happened while accessing the new browser URL.'
sip_secret: '6 or more digits'
webrtc_access: 'We could not open the sound device.<br />Please allow the browser to access it<br />in the WebRTC settings.'
de:
dialog:
agent_created: 'Sie haben den Benutzer<br /><strong>NAME</strong> hinzugefügt.'
browser_warning: 'Derzeit werden nur Chrome CHROME+ und Firefox FIREFOX+ als Browser unterstützt. Diese Plattform arbeitet eventuell fehlerhaft.'
call_failed: 'Leider schlug Ihr Anruf an<br /><strong>TO</strong> fehl.'
call_rejected: 'Leider wurde Ihr Anruf an<br /><strong>TO</strong> abgewiesen.'
callee_busy: 'Die angerufene Nummer<br /><strong>TO</strong> ist im Moment besetzt.'
cancel: 'Abbruch'
dial_now: 'Jetzt wählen'
enter_number: 'Bitte geben Sie eine Nummer ein:'
form_with_errors: 'Ein oder mehr Felder sind unvollständig. Bitte ergänzen/korrigieren Sie dies zuerst.'
hangup: 'Auflegen'
hangup_this_call: 'Möchten Sie diesen Anruf auflegen?'
i_am_busy: 'Jetzt nicht'
incoming_call: 'Sie bekommen einen Anruf von<br /><strong>NAME</strong>.'
lost_server_conn: 'Leider haben wir die Verbindung zum Server verloren — bitte prüfen Sie Ihr Netzwerk<br />und melden sich erneut an.'
no_messages: 'Wir empfangen keine Nachrichten mehr —<br />bitte öffnen Sie nur ein Fenster zur Zeit.'
ok: 'Ok'
outgoing_call: 'Sie rufen jetzt<br /><strong>NAME</strong> an.'
proceed: 'Fortfahren'
no_hungup_call: 'Diese Funktion ist nur nach einem beendeten Anruf verfügbar.'
reload_necessary: 'Um diese Einstellung zu aktivieren, muss der Browser neu geladen werden.'
reload: 'Neu laden'
shortcut_header: 'Tastaturkürzel'
take_call: 'Annehmen'
transfer_call: 'Möchten Sie diesen Anruf zu<br /><strong>AGENT</strong> durchstellen?'
transfer: 'Durchstellen'
yes: 'Ja'
agents:
agent_is: 'Agent ist'
agents_are: 'Agenten sind'
available: 'verfügbar'
status:
away: 'Ich bin abwesend'
busy: 'Ich bin beschäftigt'
ready: 'Ich nehme Anrufe an'
silent: 'Ich bin still'
ringing: 'Ich werde grade angerufen'
talking: 'Ich spreche grade'
unknown: 'Bereitschaft unbekannt'
customers:
customer_is: 'Kunde ist'
customers_are: 'Kunden sind'
queued: 'in der Warteschleife'
crmuser:
create_ticket: "Erzeugt ein #{env.crmProvider}-Ticket für diesen Anruf"
default_subject: 'Ticket für CALL'
recent_tickets: "Aktuelle #{env.crmProvider}-Tickets"
request_new_user: "Legt einen neuen #{env.crmProvider}-User für diesen Kunden an"
help:
A: 'CR: Bestätigt aktuellen Dialog'
B: 'ESC: Schließt aktuellen Dialog'
a: 'Strg+A: Zeigt die Agenten-Ansicht'
b: 'Strg+B: Setzt Status auf "abwesend"'
d: 'Strg+D: Zeigt die Dashboard-Ansicht'
f: 'Strg+F: Filtert die Agenten-Liste'
h: 'Strg+H: Legt aktuellen Anruf auf'
i: 'Strg+I: Zeigt diese Kürzel-Liste'
m: 'Strg+M: Chat-Nachricht schreiben'
o: 'Strg+O: Ausgehenden Anruf tätigen'
r: 'Strg+R: Setzt Status auf "bereit"'
s: 'Strg+S: Zeigt die Anruf-Statistik'
x: 'Strg+X: Schließt die Anruf-Ansicht'
domain:
agent: 'Agent'
answered_at: 'Antwort um'
availability: 'Verfügbarkeit'
called_at: 'Verbindung'
caller_id: 'Anrufer Id'
clear: 'Rückgängig'
email: 'E-Mail'
full_name: 'Ganzer Name'
language_choice: 'Sprachwahl'
language: 'Sprache'
languages: 'Sprachen'
line: 'Leitung'
logout: 'Abmelden'
mailbox: 'Mailbox'
mark_as: 'Status ist'
old_password: 'Altes Passwort'
password: 'Neues Passwort'
confirmation: 'Passwort bestätigen'
queued_at: 'Verbunden'
remarks: 'Bemerkung'
roles: 'Rollen'
requested_skill: 'Gewählter Dienst'
save_record: 'Speichern'
save_profile: 'Profil Speichern'
sip_extension: 'SIP-Benutzer'
sip_secret: 'SIP-Passwort'
skills: 'Dienst'
ui_locale: 'Browsersprache'
user: 'user'
user: 'Benutzer'
crmuser_id: "#{env.crmProvider} Id"
headers:
agent_management: 'Agenten-Verwaltung'
agent_overview: 'Agenten-Übersicht'
agent_profile: 'Agenten-Profil'
agent_table: 'Agenten-Tabelle'
agent_list: 'Agenten-Liste'
callcenter_stats: 'Call-Center Statistik'
call_statistics: 'Anruf-Statistik'
connected_agents: 'Verbundene Agenten'
current_calls: 'Aktuelle Anrufe'
customer_history: 'Kunden-Verzeichnis'
customers: 'Kunden'
dashboard: 'Dashboard'
details_for: 'Details zu'
help: 'Hilfe'
inbound_calls: 'Eingehende Anrufe'
media_player: 'Zeige Media-Player..'
my_settings: 'Meine Einstellungen'
new_agent: 'Agenten hinzufügen'
new_customers: 'Neue Kunden'
show_dispatched: 'Verbundene zeigen'
team_chat: 'Team-Chat'
use_auto_ready: 'Auto-Ready nutzen'
use_web_phone: 'Web-Phone nutzen'
calls:
active_calls: 'Aktive Anrufe'
avg_queue_delay: '∅ Wartezeit'
call_count: 'Anzahl'
call_queue_empty: 'Die Warteschleife ist im Moment leer.'
dispatched_calls: 'Bearbeitete Anrufe'
hungup_call_to: 'Ihr beendeter Anruf von'
incoming_calls: 'Eingehende Anrufe'
max_queue_delay: 'Max. Wartezeit'
queued_calls: 'Wartende Anrufe'
seconds: 'Sekunden'
you_are_talking: 'Sie sprechen mit'
placeholder:
an_email_address: 'Eine E-Mail-Adresse..'
enter_entry_tags: 'Anruf-Tags eingeben..'
enter_remarks: 'Geben Sie eine Bemerkung ein..'
enter_timespan: 'Zeitspanne wählen..'
find_an_agent: 'Agenten suchen..'
find_calls: 'Anrufbezogene Daten suchen..'
find_customers: 'Kundenbezogene Daten suchen..'
no_recent_messg: 'Derzeit gibt es noch keine Nachrichten im Team-Chat — schreiben Sie doch die erste!'
optional_text: 'Optionalen Text eingeben..'
refresh_tickets: "#{env.crmProvider}-Tickets dieses Kunden neu laden"
the_full_name: 'Der ganze Name..'
the_user_id: 'Benutzer-Id..'
type_a_number: 'Tippen Sie eine Zahl..'
type_here: 'Tippen Sie hier..'
errors:
ajax_error: 'Leider hat der Server einen Fehler gemeldet:<br />MSG'
crmuser_format: '9 Ziffern eingeben'
email_format: 'Geben Sie eine E-Mailadresse ein'
extension_format: '3 Ziffern eingeben'
fullname_format: 'Geben Sie den ganzen Namen ein'
line_is_busy: 'Bitte legen Sie auf und schließen Sie das Anruffeld, bevor Sie erneut wählen.'
must_be_text: 'Geben Sie einen Text ein'
number_format: 'Lokale Nummern: 030... / Int. Nummern: 0049...'
password_format: '8 oder mehr Zeichen: 1 klein, 1 Groß, 1 Ziffer'
password_match: 'Muss dem Passwort entsprechen'
routing_error: 'Leider ist beim Aufruf der Browser-URL ein Fehler aufgetreten.'
sip_secret: '6 oder mehr Ziffern'
webrtc_access: 'Das Mikrofon konnte nicht gefunden werden.<br />Bitte erlauben Sie den Browser-Zugriff<br />in den WebRTC Einstellungen.'
| 106474 | env.i18n =
en:
dialog:
agent_created: 'You successfully added the new user<br /><strong>NAME</strong>.'
browser_warning: 'For now, Chrome CHROME+ and Firefox FIREFOX+ are the only supported browsers. Use this platform at own risk.'
call_failed: 'Sorry, your call to<br /><strong>TO</strong> failed.'
call_rejected: 'Sorry, your call to<br /><strong>TO</strong> was rejected.'
callee_busy: 'The callee is currently busy:<br /><strong>TO</strong>.'
cancel: 'Cancel'
dial_now: 'Dial now'
enter_number: 'Please enter a number to dial:'
form_with_errors: 'One or more fields contain invalid data. Please fill them in correctly and try again.'
hangup: 'Hangup'
hangup_this_call: 'Do you want to hangup this call?'
i_am_busy: 'I\'m busy'
incoming_call: 'You have an incoming call from<br /><strong>NAME</strong>.'
lost_server_conn: 'Sorry, we lost our connection to the server —<br />please check your network and try to re-login.'
no_messages: 'Sorry, we stopped receiving messages —<br />please open just one app window at a time.'
ok: 'Ok'
outgoing_call: 'You are about to call<br /><strong>NAME</strong>.'
proceed: 'Proceed'
no_hungup_call: 'This is only available after you finished a call.'
reload_necessary: 'We need to reload the browser window to activate the new settings.'
reload: 'Reload'
shortcut_header: 'Keyboard shortcuts'
take_call: 'Take call'
transfer_call: 'Do you want to transfer this call to<br /><strong>AGENT</strong>?'
transfer: 'Transfer'
yes: 'Yes'
agents:
agent_is: 'agent is'
agents_are: 'agents are'
available: 'available'
status:
away: 'I\'m away from desk'
busy: 'I\'m currently busy'
ready: 'I\'m ready to take calls'
silent: 'I\'m silent'
ringing: 'I\'m receiving a call'
talking: 'I\'m currently talking'
unknown: 'Availability unknown'
customers:
customer_is: 'customer is'
customers_are: 'customers are'
queued: 'queued'
crmuser:
create_ticket: "Create a #{env.crmProvider} ticket from this call"
default_subject: 'Ticket for CALL'
recent_tickets: "Recent tickets at #{env.crmProvider}"
request_new_user: "Request a new #{env.crmProvider} user for this customer"
help:
A: 'CR: Confirm current dialog'
B: 'ESC: Close current dialog'
a: 'Ctrl+A: Show the agents page'
b: 'Ctrl+B: Set my state to "busy"'
d: 'Ctrl+D: Show the dashboard'
f: 'Ctrl+F: Filter the agent list'
h: 'Ctrl+H: Hangup the current call'
i: 'Ctrl+I: Show this shortcut list'
m: 'Ctrl+M: Type a chat message'
o: 'Ctrl+O: Dial an outbound number'
r: 'Ctrl+R: Set my state to "ready"'
s: 'Ctrl+S: Show the stats page'
x: 'Ctrl+X: Hide the call display'
domain:
agent: 'Agent'
answered_at: 'Answered at'
availability: 'Availability'
called_at: 'Called at'
caller_id: 'Caller Id'
clear: 'Clear'
email: 'E-Mail'
full_name: '<NAME>'
language_choice: 'Language Choice'
language: 'Language'
languages: 'Languages'
line: 'Line'
logout: 'Logout'
mailbox: 'Mailbox'
mark_as: 'Mark as'
old_password: '<PASSWORD>'
password: '<PASSWORD>'
confirmation: '<PASSWORD>'
queued_at: 'Queued at'
remarks: 'Remarks'
roles: 'Roles'
requested_skill: 'Requested Skill'
save_record: 'Save Record'
save_profile: 'Save Profile'
sip_extension: 'SIP Extension'
sip_secret: 'SIP Password'
skills: 'Skills'
ui_locale: 'Browser Locale'
user: 'user'
crmuser_id: "#{env.crmProvider} Id"
headers:
agent_management: 'Agent Management'
agent_overview: 'Agent Overview'
agent_profile: 'Agent Profile'
agent_table: 'Agent Table'
agent_list: 'Agent List'
callcenter_stats: 'Call Center Statistics'
call_statistics: 'Call Statistics'
connected_agents: 'Connected Agents'
current_calls: 'Current Calls'
customer_history: 'Customer history'
customers: 'Customers'
dashboard: 'Dashboard'
details_for: 'Details for'
help: 'Help'
inbound_calls: 'Inbound Calls'
media_player: 'Show media player..'
my_settings: 'My Settings'
new_agent: 'Add an Agent'
new_customers: 'New Customers'
show_dispatched: 'Show dispatched'
team_chat: 'Team Chat'
use_auto_ready: 'Use auto-ready'
use_web_phone: 'Use the web-phone'
calls:
active_calls: 'Active calls'
avg_queue_delay: '∅ Queue delay'
call_count: 'Count'
call_queue_empty: 'The call queue is empty right now.'
dispatched_calls: 'Dispatched calls'
hungup_call_to: 'Your finished call to'
incoming_calls: 'Incoming calls'
max_queue_delay: 'Max. queue delay'
queued_calls: 'Queued calls'
seconds: 'Seconds'
you_are_talking: 'You are talking to'
placeholder:
an_email_address: 'An e-mail address..'
enter_entry_tags: 'Enter some tags..'
enter_remarks: 'Enter remarks for this call..'
enter_timespan: 'Enter a timespan..'
find_an_agent: 'Find an agent..'
find_calls: 'Enter call specific terms..'
find_customers: 'Enter customer related terms..'
no_recent_messg: 'There are no recent messages in the team chat until now — be the first to write one!'
optional_text: 'Enter optional text..'
refresh_tickets: "Refresh this customer's #{env.crmProvider} tickets"
the_full_name: 'The full name..'
the_user_id: 'User Id..'
type_a_number: 'Type a number..'
type_here: 'Type here..'
errors:
ajax_error: 'Sorry, the server returned an error message:<br />MSG'
crmuser_format: 'Enter 9 digits'
email_format: 'Enter a valid email address'
extension_format: 'Enter 3 digits'
fullname_format: 'Enter the agent\'s full name'
line_is_busy: 'Please hangup and close the current call display, before you dial again.'
must_be_text: 'Enter some words'
number_format: 'Local numbers: 030... / Intl. numbers: 0049...'
password_format: 'Enter 8 or more chars.: 1 lower, 1 upper, 1 digit'
password_match: '<PASSWORD>'
routing_error: 'Sorry, an error happened while accessing the new browser URL.'
sip_secret: '6 or more digits'
webrtc_access: 'We could not open the sound device.<br />Please allow the browser to access it<br />in the WebRTC settings.'
de:
dialog:
agent_created: 'Sie haben den Benutzer<br /><strong>NAME</strong> hinzugefügt.'
browser_warning: 'Derzeit werden nur Chrome CHROME+ und Firefox FIREFOX+ als Browser unterstützt. Diese Plattform arbeitet eventuell fehlerhaft.'
call_failed: 'Leider schlug Ihr Anruf an<br /><strong>TO</strong> fehl.'
call_rejected: 'Leider wurde Ihr Anruf an<br /><strong>TO</strong> abgewiesen.'
callee_busy: 'Die angerufene Nummer<br /><strong>TO</strong> ist im Moment besetzt.'
cancel: 'Abbruch'
dial_now: 'Jetzt wählen'
enter_number: 'Bitte geben Sie eine Nummer ein:'
form_with_errors: 'Ein oder mehr Felder sind unvollständig. Bitte ergänzen/korrigieren Sie dies zuerst.'
hangup: 'Auflegen'
hangup_this_call: 'Möchten Sie diesen Anruf auflegen?'
i_am_busy: 'Jetzt nicht'
incoming_call: 'Sie bekommen einen Anruf von<br /><strong>NAME</strong>.'
lost_server_conn: 'Leider haben wir die Verbindung zum Server verloren — bitte prüfen Sie Ihr Netzwerk<br />und melden sich erneut an.'
no_messages: 'Wir empfangen keine Nachrichten mehr —<br />bitte öffnen Sie nur ein Fenster zur Zeit.'
ok: 'Ok'
outgoing_call: 'Sie rufen jetzt<br /><strong>NAME</strong> an.'
proceed: 'Fortfahren'
no_hungup_call: 'Diese Funktion ist nur nach einem beendeten Anruf verfügbar.'
reload_necessary: 'Um diese Einstellung zu aktivieren, muss der Browser neu geladen werden.'
reload: 'Neu laden'
shortcut_header: 'Tastaturkürzel'
take_call: 'Annehmen'
transfer_call: 'Möchten Sie diesen Anruf zu<br /><strong>AGENT</strong> durchstellen?'
transfer: 'Durchstellen'
yes: 'Ja'
agents:
agent_is: 'Agent ist'
agents_are: 'Agenten sind'
available: 'verfügbar'
status:
away: 'Ich bin abwesend'
busy: 'Ich bin beschäftigt'
ready: 'Ich nehme Anrufe an'
silent: 'Ich bin still'
ringing: 'Ich werde grade angerufen'
talking: 'Ich spreche grade'
unknown: 'Bereitschaft unbekannt'
customers:
customer_is: 'Kunde ist'
customers_are: 'Kunden sind'
queued: 'in der Warteschleife'
crmuser:
create_ticket: "Erzeugt ein #{env.crmProvider}-Ticket für diesen Anruf"
default_subject: 'Ticket für CALL'
recent_tickets: "Aktuelle #{env.crmProvider}-Tickets"
request_new_user: "Legt einen neuen #{env.crmProvider}-User für diesen Kunden an"
help:
A: 'CR: Bestätigt aktuellen Dialog'
B: 'ESC: Schließt aktuellen Dialog'
a: 'Strg+A: Zeigt die Agenten-Ansicht'
b: 'Strg+B: Setzt Status auf "abwesend"'
d: 'Strg+D: Zeigt die Dashboard-Ansicht'
f: 'Strg+F: Filtert die Agenten-Liste'
h: 'Strg+H: Legt aktuellen Anruf auf'
i: 'Strg+I: Zeigt diese Kürzel-Liste'
m: 'Strg+M: Chat-Nachricht schreiben'
o: 'Strg+O: Ausgehenden Anruf tätigen'
r: 'Strg+R: Setzt Status auf "bereit"'
s: 'Strg+S: Zeigt die Anruf-Statistik'
x: 'Strg+X: Schließt die Anruf-Ansicht'
domain:
agent: 'Agent'
answered_at: 'Antwort um'
availability: 'Verfügbarkeit'
called_at: 'Verbindung'
caller_id: 'Anrufer Id'
clear: 'Rückgängig'
email: 'E-Mail'
full_name: '<NAME>'
language_choice: 'Sprachwahl'
language: 'Sprache'
languages: 'Sprachen'
line: 'Leitung'
logout: 'Abmelden'
mailbox: 'Mailbox'
mark_as: 'Status ist'
old_password: '<PASSWORD>'
password: '<PASSWORD>'
confirmation: 'Passwort best<PASSWORD>'
queued_at: 'Verbunden'
remarks: 'Bemerkung'
roles: 'Rollen'
requested_skill: 'Gewählter Dienst'
save_record: 'Speichern'
save_profile: 'Profil Speichern'
sip_extension: 'SIP-Benutzer'
sip_secret: 'SIP-Passwort'
skills: 'Dienst'
ui_locale: 'Browsersprache'
user: 'user'
user: '<NAME>'
crmuser_id: "#{env.crmProvider} Id"
headers:
agent_management: 'Agenten-Verwaltung'
agent_overview: 'Agenten-Übersicht'
agent_profile: 'Agenten-Profil'
agent_table: 'Agenten-Tabelle'
agent_list: 'Agenten-Liste'
callcenter_stats: 'Call-Center Statistik'
call_statistics: 'Anruf-Statistik'
connected_agents: 'Verbundene Agenten'
current_calls: 'Aktuelle Anrufe'
customer_history: 'Kunden-Verzeichnis'
customers: 'Kunden'
dashboard: 'Dashboard'
details_for: 'Details zu'
help: 'Hilfe'
inbound_calls: 'Eingehende Anrufe'
media_player: 'Zeige Media-Player..'
my_settings: 'Meine Einstellungen'
new_agent: 'Agenten hinzufügen'
new_customers: 'Neue Kunden'
show_dispatched: 'Verbundene zeigen'
team_chat: 'Team-Chat'
use_auto_ready: 'Auto-Ready nutzen'
use_web_phone: 'Web-Phone nutzen'
calls:
active_calls: 'Aktive Anrufe'
avg_queue_delay: '∅ Wartezeit'
call_count: 'Anzahl'
call_queue_empty: 'Die Warteschleife ist im Moment leer.'
dispatched_calls: 'Bearbeitete Anrufe'
hungup_call_to: 'Ihr beendeter Anruf von'
incoming_calls: 'Eingehende Anrufe'
max_queue_delay: 'Max. Wartezeit'
queued_calls: 'Wartende Anrufe'
seconds: 'Sekunden'
you_are_talking: 'Sie sprechen mit'
placeholder:
an_email_address: 'Eine E-Mail-Adresse..'
enter_entry_tags: 'Anruf-Tags eingeben..'
enter_remarks: 'Geben Sie eine Bemerkung ein..'
enter_timespan: 'Zeitspanne wählen..'
find_an_agent: 'Agenten suchen..'
find_calls: 'Anrufbezogene Daten suchen..'
find_customers: 'Kundenbezogene Daten suchen..'
no_recent_messg: 'Derzeit gibt es noch keine Nachrichten im Team-Chat — schreiben Sie doch die erste!'
optional_text: 'Optionalen Text eingeben..'
refresh_tickets: "#{env.crmProvider}-Tickets dieses Kunden neu laden"
the_full_name: 'Der ganze Name..'
the_user_id: 'Benutzer-Id..'
type_a_number: 'Tippen Sie eine Zahl..'
type_here: 'Tippen Sie hier..'
errors:
ajax_error: 'Leider hat der Server einen Fehler gemeldet:<br />MSG'
crmuser_format: '9 Ziffern eingeben'
email_format: 'Geben Sie eine E-Mailadresse ein'
extension_format: '3 Ziffern eingeben'
fullname_format: 'Geben Sie den ganzen Namen ein'
line_is_busy: 'Bitte legen Sie auf und schließen Sie das Anruffeld, bevor Sie erneut wählen.'
must_be_text: 'Geben Sie einen Text ein'
number_format: 'Lokale Nummern: 030... / Int. Nummern: 0049...'
password_format: '8 oder mehr Zeichen: <PASSWORD>'
password_match: '<PASSWORD>'
routing_error: 'Leider ist beim Aufruf der Browser-URL ein Fehler aufgetreten.'
sip_secret: '<KEY>'
webrtc_access: 'Das Mikrofon konnte nicht gefunden werden.<br />Bitte erlauben Sie den Browser-Zugriff<br />in den WebRTC Einstellungen.'
| true | env.i18n =
en:
dialog:
agent_created: 'You successfully added the new user<br /><strong>NAME</strong>.'
browser_warning: 'For now, Chrome CHROME+ and Firefox FIREFOX+ are the only supported browsers. Use this platform at own risk.'
call_failed: 'Sorry, your call to<br /><strong>TO</strong> failed.'
call_rejected: 'Sorry, your call to<br /><strong>TO</strong> was rejected.'
callee_busy: 'The callee is currently busy:<br /><strong>TO</strong>.'
cancel: 'Cancel'
dial_now: 'Dial now'
enter_number: 'Please enter a number to dial:'
form_with_errors: 'One or more fields contain invalid data. Please fill them in correctly and try again.'
hangup: 'Hangup'
hangup_this_call: 'Do you want to hangup this call?'
i_am_busy: 'I\'m busy'
incoming_call: 'You have an incoming call from<br /><strong>NAME</strong>.'
lost_server_conn: 'Sorry, we lost our connection to the server —<br />please check your network and try to re-login.'
no_messages: 'Sorry, we stopped receiving messages —<br />please open just one app window at a time.'
ok: 'Ok'
outgoing_call: 'You are about to call<br /><strong>NAME</strong>.'
proceed: 'Proceed'
no_hungup_call: 'This is only available after you finished a call.'
reload_necessary: 'We need to reload the browser window to activate the new settings.'
reload: 'Reload'
shortcut_header: 'Keyboard shortcuts'
take_call: 'Take call'
transfer_call: 'Do you want to transfer this call to<br /><strong>AGENT</strong>?'
transfer: 'Transfer'
yes: 'Yes'
agents:
agent_is: 'agent is'
agents_are: 'agents are'
available: 'available'
status:
away: 'I\'m away from desk'
busy: 'I\'m currently busy'
ready: 'I\'m ready to take calls'
silent: 'I\'m silent'
ringing: 'I\'m receiving a call'
talking: 'I\'m currently talking'
unknown: 'Availability unknown'
customers:
customer_is: 'customer is'
customers_are: 'customers are'
queued: 'queued'
crmuser:
create_ticket: "Create a #{env.crmProvider} ticket from this call"
default_subject: 'Ticket for CALL'
recent_tickets: "Recent tickets at #{env.crmProvider}"
request_new_user: "Request a new #{env.crmProvider} user for this customer"
help:
A: 'CR: Confirm current dialog'
B: 'ESC: Close current dialog'
a: 'Ctrl+A: Show the agents page'
b: 'Ctrl+B: Set my state to "busy"'
d: 'Ctrl+D: Show the dashboard'
f: 'Ctrl+F: Filter the agent list'
h: 'Ctrl+H: Hangup the current call'
i: 'Ctrl+I: Show this shortcut list'
m: 'Ctrl+M: Type a chat message'
o: 'Ctrl+O: Dial an outbound number'
r: 'Ctrl+R: Set my state to "ready"'
s: 'Ctrl+S: Show the stats page'
x: 'Ctrl+X: Hide the call display'
domain:
agent: 'Agent'
answered_at: 'Answered at'
availability: 'Availability'
called_at: 'Called at'
caller_id: 'Caller Id'
clear: 'Clear'
email: 'E-Mail'
full_name: 'PI:NAME:<NAME>END_PI'
language_choice: 'Language Choice'
language: 'Language'
languages: 'Languages'
line: 'Line'
logout: 'Logout'
mailbox: 'Mailbox'
mark_as: 'Mark as'
old_password: 'PI:PASSWORD:<PASSWORD>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
confirmation: 'PI:PASSWORD:<PASSWORD>END_PI'
queued_at: 'Queued at'
remarks: 'Remarks'
roles: 'Roles'
requested_skill: 'Requested Skill'
save_record: 'Save Record'
save_profile: 'Save Profile'
sip_extension: 'SIP Extension'
sip_secret: 'SIP Password'
skills: 'Skills'
ui_locale: 'Browser Locale'
user: 'user'
crmuser_id: "#{env.crmProvider} Id"
headers:
agent_management: 'Agent Management'
agent_overview: 'Agent Overview'
agent_profile: 'Agent Profile'
agent_table: 'Agent Table'
agent_list: 'Agent List'
callcenter_stats: 'Call Center Statistics'
call_statistics: 'Call Statistics'
connected_agents: 'Connected Agents'
current_calls: 'Current Calls'
customer_history: 'Customer history'
customers: 'Customers'
dashboard: 'Dashboard'
details_for: 'Details for'
help: 'Help'
inbound_calls: 'Inbound Calls'
media_player: 'Show media player..'
my_settings: 'My Settings'
new_agent: 'Add an Agent'
new_customers: 'New Customers'
show_dispatched: 'Show dispatched'
team_chat: 'Team Chat'
use_auto_ready: 'Use auto-ready'
use_web_phone: 'Use the web-phone'
calls:
active_calls: 'Active calls'
avg_queue_delay: '∅ Queue delay'
call_count: 'Count'
call_queue_empty: 'The call queue is empty right now.'
dispatched_calls: 'Dispatched calls'
hungup_call_to: 'Your finished call to'
incoming_calls: 'Incoming calls'
max_queue_delay: 'Max. queue delay'
queued_calls: 'Queued calls'
seconds: 'Seconds'
you_are_talking: 'You are talking to'
placeholder:
an_email_address: 'An e-mail address..'
enter_entry_tags: 'Enter some tags..'
enter_remarks: 'Enter remarks for this call..'
enter_timespan: 'Enter a timespan..'
find_an_agent: 'Find an agent..'
find_calls: 'Enter call specific terms..'
find_customers: 'Enter customer related terms..'
no_recent_messg: 'There are no recent messages in the team chat until now — be the first to write one!'
optional_text: 'Enter optional text..'
refresh_tickets: "Refresh this customer's #{env.crmProvider} tickets"
the_full_name: 'The full name..'
the_user_id: 'User Id..'
type_a_number: 'Type a number..'
type_here: 'Type here..'
errors:
ajax_error: 'Sorry, the server returned an error message:<br />MSG'
crmuser_format: 'Enter 9 digits'
email_format: 'Enter a valid email address'
extension_format: 'Enter 3 digits'
fullname_format: 'Enter the agent\'s full name'
line_is_busy: 'Please hangup and close the current call display, before you dial again.'
must_be_text: 'Enter some words'
number_format: 'Local numbers: 030... / Intl. numbers: 0049...'
password_format: 'Enter 8 or more chars.: 1 lower, 1 upper, 1 digit'
password_match: 'PI:PASSWORD:<PASSWORD>END_PI'
routing_error: 'Sorry, an error happened while accessing the new browser URL.'
sip_secret: '6 or more digits'
webrtc_access: 'We could not open the sound device.<br />Please allow the browser to access it<br />in the WebRTC settings.'
de:
dialog:
agent_created: 'Sie haben den Benutzer<br /><strong>NAME</strong> hinzugefügt.'
browser_warning: 'Derzeit werden nur Chrome CHROME+ und Firefox FIREFOX+ als Browser unterstützt. Diese Plattform arbeitet eventuell fehlerhaft.'
call_failed: 'Leider schlug Ihr Anruf an<br /><strong>TO</strong> fehl.'
call_rejected: 'Leider wurde Ihr Anruf an<br /><strong>TO</strong> abgewiesen.'
callee_busy: 'Die angerufene Nummer<br /><strong>TO</strong> ist im Moment besetzt.'
cancel: 'Abbruch'
dial_now: 'Jetzt wählen'
enter_number: 'Bitte geben Sie eine Nummer ein:'
form_with_errors: 'Ein oder mehr Felder sind unvollständig. Bitte ergänzen/korrigieren Sie dies zuerst.'
hangup: 'Auflegen'
hangup_this_call: 'Möchten Sie diesen Anruf auflegen?'
i_am_busy: 'Jetzt nicht'
incoming_call: 'Sie bekommen einen Anruf von<br /><strong>NAME</strong>.'
lost_server_conn: 'Leider haben wir die Verbindung zum Server verloren — bitte prüfen Sie Ihr Netzwerk<br />und melden sich erneut an.'
no_messages: 'Wir empfangen keine Nachrichten mehr —<br />bitte öffnen Sie nur ein Fenster zur Zeit.'
ok: 'Ok'
outgoing_call: 'Sie rufen jetzt<br /><strong>NAME</strong> an.'
proceed: 'Fortfahren'
no_hungup_call: 'Diese Funktion ist nur nach einem beendeten Anruf verfügbar.'
reload_necessary: 'Um diese Einstellung zu aktivieren, muss der Browser neu geladen werden.'
reload: 'Neu laden'
shortcut_header: 'Tastaturkürzel'
take_call: 'Annehmen'
transfer_call: 'Möchten Sie diesen Anruf zu<br /><strong>AGENT</strong> durchstellen?'
transfer: 'Durchstellen'
yes: 'Ja'
agents:
agent_is: 'Agent ist'
agents_are: 'Agenten sind'
available: 'verfügbar'
status:
away: 'Ich bin abwesend'
busy: 'Ich bin beschäftigt'
ready: 'Ich nehme Anrufe an'
silent: 'Ich bin still'
ringing: 'Ich werde grade angerufen'
talking: 'Ich spreche grade'
unknown: 'Bereitschaft unbekannt'
customers:
customer_is: 'Kunde ist'
customers_are: 'Kunden sind'
queued: 'in der Warteschleife'
crmuser:
create_ticket: "Erzeugt ein #{env.crmProvider}-Ticket für diesen Anruf"
default_subject: 'Ticket für CALL'
recent_tickets: "Aktuelle #{env.crmProvider}-Tickets"
request_new_user: "Legt einen neuen #{env.crmProvider}-User für diesen Kunden an"
help:
A: 'CR: Bestätigt aktuellen Dialog'
B: 'ESC: Schließt aktuellen Dialog'
a: 'Strg+A: Zeigt die Agenten-Ansicht'
b: 'Strg+B: Setzt Status auf "abwesend"'
d: 'Strg+D: Zeigt die Dashboard-Ansicht'
f: 'Strg+F: Filtert die Agenten-Liste'
h: 'Strg+H: Legt aktuellen Anruf auf'
i: 'Strg+I: Zeigt diese Kürzel-Liste'
m: 'Strg+M: Chat-Nachricht schreiben'
o: 'Strg+O: Ausgehenden Anruf tätigen'
r: 'Strg+R: Setzt Status auf "bereit"'
s: 'Strg+S: Zeigt die Anruf-Statistik'
x: 'Strg+X: Schließt die Anruf-Ansicht'
domain:
agent: 'Agent'
answered_at: 'Antwort um'
availability: 'Verfügbarkeit'
called_at: 'Verbindung'
caller_id: 'Anrufer Id'
clear: 'Rückgängig'
email: 'E-Mail'
full_name: 'PI:NAME:<NAME>END_PI'
language_choice: 'Sprachwahl'
language: 'Sprache'
languages: 'Sprachen'
line: 'Leitung'
logout: 'Abmelden'
mailbox: 'Mailbox'
mark_as: 'Status ist'
old_password: 'PI:PASSWORD:<PASSWORD>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
confirmation: 'Passwort bestPI:PASSWORD:<PASSWORD>END_PI'
queued_at: 'Verbunden'
remarks: 'Bemerkung'
roles: 'Rollen'
requested_skill: 'Gewählter Dienst'
save_record: 'Speichern'
save_profile: 'Profil Speichern'
sip_extension: 'SIP-Benutzer'
sip_secret: 'SIP-Passwort'
skills: 'Dienst'
ui_locale: 'Browsersprache'
user: 'user'
user: 'PI:NAME:<NAME>END_PI'
crmuser_id: "#{env.crmProvider} Id"
headers:
agent_management: 'Agenten-Verwaltung'
agent_overview: 'Agenten-Übersicht'
agent_profile: 'Agenten-Profil'
agent_table: 'Agenten-Tabelle'
agent_list: 'Agenten-Liste'
callcenter_stats: 'Call-Center Statistik'
call_statistics: 'Anruf-Statistik'
connected_agents: 'Verbundene Agenten'
current_calls: 'Aktuelle Anrufe'
customer_history: 'Kunden-Verzeichnis'
customers: 'Kunden'
dashboard: 'Dashboard'
details_for: 'Details zu'
help: 'Hilfe'
inbound_calls: 'Eingehende Anrufe'
media_player: 'Zeige Media-Player..'
my_settings: 'Meine Einstellungen'
new_agent: 'Agenten hinzufügen'
new_customers: 'Neue Kunden'
show_dispatched: 'Verbundene zeigen'
team_chat: 'Team-Chat'
use_auto_ready: 'Auto-Ready nutzen'
use_web_phone: 'Web-Phone nutzen'
calls:
active_calls: 'Aktive Anrufe'
avg_queue_delay: '∅ Wartezeit'
call_count: 'Anzahl'
call_queue_empty: 'Die Warteschleife ist im Moment leer.'
dispatched_calls: 'Bearbeitete Anrufe'
hungup_call_to: 'Ihr beendeter Anruf von'
incoming_calls: 'Eingehende Anrufe'
max_queue_delay: 'Max. Wartezeit'
queued_calls: 'Wartende Anrufe'
seconds: 'Sekunden'
you_are_talking: 'Sie sprechen mit'
placeholder:
an_email_address: 'Eine E-Mail-Adresse..'
enter_entry_tags: 'Anruf-Tags eingeben..'
enter_remarks: 'Geben Sie eine Bemerkung ein..'
enter_timespan: 'Zeitspanne wählen..'
find_an_agent: 'Agenten suchen..'
find_calls: 'Anrufbezogene Daten suchen..'
find_customers: 'Kundenbezogene Daten suchen..'
no_recent_messg: 'Derzeit gibt es noch keine Nachrichten im Team-Chat — schreiben Sie doch die erste!'
optional_text: 'Optionalen Text eingeben..'
refresh_tickets: "#{env.crmProvider}-Tickets dieses Kunden neu laden"
the_full_name: 'Der ganze Name..'
the_user_id: 'Benutzer-Id..'
type_a_number: 'Tippen Sie eine Zahl..'
type_here: 'Tippen Sie hier..'
errors:
ajax_error: 'Leider hat der Server einen Fehler gemeldet:<br />MSG'
crmuser_format: '9 Ziffern eingeben'
email_format: 'Geben Sie eine E-Mailadresse ein'
extension_format: '3 Ziffern eingeben'
fullname_format: 'Geben Sie den ganzen Namen ein'
line_is_busy: 'Bitte legen Sie auf und schließen Sie das Anruffeld, bevor Sie erneut wählen.'
must_be_text: 'Geben Sie einen Text ein'
number_format: 'Lokale Nummern: 030... / Int. Nummern: 0049...'
password_format: '8 oder mehr Zeichen: PI:PASSWORD:<PASSWORD>END_PI'
password_match: 'PI:PASSWORD:<PASSWORD>END_PI'
routing_error: 'Leider ist beim Aufruf der Browser-URL ein Fehler aufgetreten.'
sip_secret: 'PI:KEY:<KEY>END_PI'
webrtc_access: 'Das Mikrofon konnte nicht gefunden werden.<br />Bitte erlauben Sie den Browser-Zugriff<br />in den WebRTC Einstellungen.'
|
[
{
"context": "anes)\n tabsKey = 'Prin' if obj.compKey is 'Prin' and obj.level is 'Comp'\n tabsKey = 'Prac' i",
"end": 5705,
"score": 0.5667741298675537,
"start": 5703,
"tag": "KEY",
"value": "in"
},
{
"context": "s 'Prin' and obj.level is 'Comp'\n tabsKey = 'Prac' if o... | lib/src/navi/Nav.coffee | axiom6/aug | 0 |
import Mix from './Mix.js'
import Build from '../util/Build.js'
import Dir from './Dir.js'
class Nav extends Mix
constructor:( Main, stream, komps=null, pages={}, isRoutes=false ) ->
super( Main )
@stream = stream
@komps = komps
@pages = pages
@isRoutes = isRoutes
@navs = if @komps then @addInovToNavs( @komps ) else null
@touch = null
@build = new Build( @batch )
@dir = new Dir( @ )
@source = 'none'
@level = 'none' # set to either Comp Prac or Disp by Tocs.vue
@compKey = 'none'
@pracKey = 'none'
@dispKey = 'none'
@pageKey = 'none'
@inovKey = 'none' # Only used by Tabs to Tocs.vue and Comp.vue
@choice = 'none'
@checked = false
@warnMsg = 'none'
@debug = false
@pubs = []
@urls = []
@tabs = {}
@router = null
@routeLast = 'none'
@museLevels = ['Comp','Prac','Disp']
@museComps = ['Home','Prin','Info','Know','Wise','Cube','Test']
@museInovs = ['Info','Know','Wise','Soft','Data','Scie','Math']
@musePlanes = ['Info','Know','Wise']
# Special publsher for Vizu side bar
pubVizu:( obj ) ->
# console.log('Nav.pubVizu()', obj )
@stream.publish( 'Vizu', obj )
return
pub:( msg, isReplay=false ) ->
changeView = @viewChange( msg )
obj = @toObj( msg )
url = @toUrl( obj )
console.log('Nav.pub()', obj )
@doRoute( obj ) if @isRoutes
@pubs.push( obj ) if not isReplay and obj.compKey isnt 'Test'
@urls.push( url ) if not isReplay and obj.compKey isnt 'Test'
@stream.publish( 'View', obj ) if changeView
@stream.publish( 'Nav', obj )
return
viewChange:( obj ) ->
obj.compKey = @compKey if not @isDef(obj.compKey)
obj.pracKey = @pracKey if not @isDef(obj.pracKey)
obj.dispKey = @dispKey if not @isDef(obj.dispKey)
change = not ( obj.compKey is @compKey and obj.pracKey is @pracKey and obj.dispKey is @dispKey )
console.log( 'Nav.viewChange()', { change:change, compObj:obj.compKey, compNav:@compKey,
pracObj:obj.pracKey, pracNav:@pracKey, dispObj:obj.dispKey, dispNav:@dispKey, } ) if @debug and change
change
toObj:( msg ) ->
@set( msg )
@source = 'none' if not msg.source?
@pracKey = 'none' if @level is 'Comp'
@dispKey = 'none' if @level isnt 'Disp'
obj = { source:@source, level:@level, compKey:@compKey, pracKey:@pracKey, dispKey:@dispKey, pageKey:@pageKey }
obj.pageKey = @objPage( obj )
obj.inovKey = @objInov( obj )
obj.choice = @choice if @isApp('Jitter')
obj.checked = @checked if @isApp('Jitter')
obj.warnMsg = @warnMsg if @warnMsg isnt 'none'
@tab( obj ) # Publisn pageKey and inovKey to tabs
obj
set:( msg ) ->
for own key, val of msg
@[key] = val
return
tab:( obj ) ->
if @isDef(obj.pageKey)
@pageKey = obj.pageKey
tabsKey = @getTabsKey(obj)
@setPageKey( tabsKey, obj.pageKey, {} ) # Short message on 'Tab' subject
@stream.publish( 'Tab', { compKey:tabsKey, pageKey:obj.pageKey } )
console.log( 'Nav.set() pageKey', { compKey:tabsKey, pageKey:obj.pageKey } ) if @debug
if @isDef(obj.inovKey)
@inovKey = obj.inovKey
@setPageKey( obj.compKey, obj.inovKey, {} ) # Short message on 'Tab' subject
@stream.publish( 'Tab', { compKey:obj.compKey, pageKey:obj.inovKey } )
console.log( 'Nav.set() inovKey', { compKey:obj.compKey, inovKey:obj.inovKey } ) if @debug
return
toUrl:( obj ) ->
page = @objPage( obj )
inov = @objInov( obj )
url = window.location.protocol + '//' + window.location.host
url += if obj.compKey is 'Home' then '' else '/' + obj.compKey
url += '/' + obj.pracKey if obj.pracKey isnt 'none'
url += '/' + obj.dispKey if obj.dispKey isnt 'none'
url += '?' + 'page=' + page if page isnt 'none'
url += '&' + 'innovate=' + inov if inov isnt 'none'
console.log( 'Nav.toUrl()', url ) if @debug
window.history.pushState( {}, '', url )
url
toPub:( href ) =>
obj = {}
url = new URL(href)
page = url.searchParams.get("page")
innovate = url.searchParams.get("innovate")
paths = url.pathname.split('/')
obj.source = 'Url'
obj.compKey = if @isStr(paths[1]) then paths[1] else 'Home'
obj.pracKey = if @isStr(paths[2]) then paths[2] else 'none'
obj.dispKey = if @isStr(paths[3]) then paths[3] else 'none'
obj.pageKey = if page? then page else 'none'
obj.inovKey = if innovate? then innovate else 'none'
obj.level =
if obj.dispKey isnt 'none' then 'Disp'
else if obj.pracKey isnt 'none' then 'Prac'
else 'Comp'
console.log( 'Nav.toPub()', { url:href, obj:obj, paths:paths } ) if @debug
obj
doDir:( direct ) ->
@dir.dir( direct )
return
mountTouch:( msg, elem, nextTick, incKlasses, excKlasses=[] ) ->
nextTick( () =>
if @isDef(elem) and @touch?
@touch.listen( elem, incKlasses, excKlasses )
else
console.error( msg, "Nav.mountTouch() elem or touch undefined" ) )
return
doRoute:( obj ) ->
route = obj.compKey
return if route is @routeLast or route is 'none' or @isInov(route)
if @router?
@router.push( name:route )
else
console.error( 'Nav.doRoute() router not set for', route )
@routeLast = route
return
getTabsKey:( obj ) ->
tabsKey = 'none'
if @isApp('Muse')
tabsKey = obj.level if @inArray(obj.compKey,@musePlanes)
tabsKey = 'Prin' if obj.compKey is 'Prin' and obj.level is 'Comp'
tabsKey = 'Prac' if obj.compKey is 'Prin' and obj.level is 'Prac'
else
tabsKey = switch obj.level
when 'Comp' then obj.compKey
when 'Prac' then obj.pracKey
when 'Disp' then obj.dispKey
else obj.compKey
tabsKey
objPage:( obj ) ->
if obj.page is 'none' then @getPageKey( @getTabsKey(obj), false ) else obj.pageKey
objInov:( obj ) ->
if @inArray(obj.compKey,@musePlanes) then @getPageKey(obj.compKey) else 'none'
isShow:( tabsKey, pageKey ) ->
pageNav = @getPageKey( tabsKey )
pageKey is pageNav
# When @page matches return
# otherwise look for when the page is true at eech level
# this supports setting show true in pages
show:( pageArg ) ->
switch
when pageArg is @pageKey then true
when @level is "Disp" then pageArg is @getPageKey( @dispKey )
when @level is "Prac" then pageArg is @getPageKey( @pracKey )
when @level is "Comp" then pageArg is @getPageKey( @compKey )
else false
keyIdx:( key, idx ) ->
key + idx
# An important indicator of when Comps and Tabs are instanciated
setTabs:( tabsKey, pages ) ->
return if @hasTabs(tabsKey,false )
@pages[tabsKey] = pages
return
getTabs:( tabsKey ) ->
if @hasTabs(tabsKey,true) then @pages[tabsKey] else {}
setPageKey:( tabsKey, pageKey, propTabs ) ->
return if pageKey is 'none'
for own key, page of @pages[tabsKey]
page.show = key is pageKey # Update nav pages
propTabs[key].show = key is pageKey if propTabs[key]? # Also update Tabs.vue propTabs because it is a copy
return
getPageKey:( tabsKey, log=false ) ->
return 'none' if not @hasTabs(tabsKey,log)
for own key, page of @pages[tabsKey]
return key if page.show
'none'
hasPage:( tabsKey, pageKey, log=true ) ->
if @isDef(tabsKey) and @hasTabs(tabsKey)
if @isDef(pageKey) and @pages[tabsKey][pageKey]?
true
else
console.log( 'Nav.hasPage() bad pageKey', { tabsKey:tabsKey, pageKey:pageKey, pages:getTabs:(tabsKey) } ) if log and pageKey isnt 'none'
false
else
console.log( 'Nav.hasPage() bad tabsKey', { tabsKey:tabsKey, pageKey:pageKey } ) if log and pageKey isnt 'none'
false
getPage:( tabsKey, pageKey, log=false ) ->
if @hasTabs(tabsKey,log) and @pages[tabsKey][pageKey]?
@pages[tabsKey][pageKey]
else
console.error( 'Nav.getPage() bad page', { tabsKey:tabsKey, pageKey:pageKey } )
'none'
getInovKey:( tabsKey ) ->
if @inArray(tabsKey,@musePlanes) then @getPageKey(tabsKey) else 'none'
hasTabs:( tabsKey, log=false ) ->
has = @isDef(tabsKey) and @isDef(@pages[tabsKey])
console.log( 'Nav.hasTabs()', { tabsKey:tabsKey, has:has, pages:@pages } ) if not has and log
has
isMyNav:( obj, level, checkPageKey=false ) -> # @routes, @routeNames,
if checkPageKey
obj.level is level and @hasTabs(obj.pageKey,true)
else
obj.level is level
pracs:( compKey ) ->
if @batch[compKey]? then @batch[compKey].data.pracs else {}
disps:( compKey, pracKey ) ->
if @batch[compKey]? then @batch[compKey].data.pracs[pracKey].disps else {}
# Called as await sleep(2000) inside an asych function
sleep:(ms) ->
new Promise( (resolve) => setTimeout( resolve, ms ) )
delayCallback:( ms, callback ) ->
setTimeout( callback, ms )
return
# --- Innovate --- Inov in one place
# Across the board Inov detector for compKey pageKey and route
isInov:( compKey ) ->
@inArray( compKey, @museInovs )
addInovToNavs:( komps ) ->
return komps? if not @isApp('Muse')
navs = Object.assign( {}, komps )
#avs = @insInov( navs, @museInovs )
navs
insInov:( navs, prev, inov, next ) ->
navs[prev].south = inov if navs[prev]?
navs[prev].next = inov if navs[next]?
navs[inov] = { north:prev, prev:prev, south:next, next:next }
navs[next].north = inov
navs[next].prev = inov
navs
userAgent:() ->
navigator.userAgent.toLowerCase()
# Looks up lower case strings in navigator userAngent
# like 'android' 'mac' 'iphone' 'firefox'
# not 100% certain but usefull
inUserAgent:( str ) ->
@userAgent().indexOf(str) > -1
isMobile:() ->
@inUserAgent('android') or @inUserAgent('iphone')
export default Nav
###
set:( msg, isReplay ) ->
if isReplay
if msg.pageKey isnt 'none'
tabsKey = @getTabsKey(msg)
@setPageKey( tabsKey, msg.pageKey, {} ) # Short message on 'Tab' subject
@stream.publish( 'Tab', { compKey:tabsKey, pageKey:msg.pageKey } )
console.log( 'Nav.set() pageKey', { compKey:tabsKey, pageKey:msg.pageKey } ) if @debug
if msg.inovKey isnt 'none'
@setPageKey( msg.compKey, msg.inovKey, {} ) # Short message on 'Tab' subject
@stream.publish( 'Tab', { compKey:msg.compKey, pageKey:msg.inovKey } )
console.log( 'Nav.set() inovKey', { compKey:msg.compKey, inovKey:msg.inovKey } ) if @debug
for own key, val of msg
@[key] = val
return
###
| 124319 |
import Mix from './Mix.js'
import Build from '../util/Build.js'
import Dir from './Dir.js'
class Nav extends Mix
constructor:( Main, stream, komps=null, pages={}, isRoutes=false ) ->
super( Main )
@stream = stream
@komps = komps
@pages = pages
@isRoutes = isRoutes
@navs = if @komps then @addInovToNavs( @komps ) else null
@touch = null
@build = new Build( @batch )
@dir = new Dir( @ )
@source = 'none'
@level = 'none' # set to either Comp Prac or Disp by Tocs.vue
@compKey = 'none'
@pracKey = 'none'
@dispKey = 'none'
@pageKey = 'none'
@inovKey = 'none' # Only used by Tabs to Tocs.vue and Comp.vue
@choice = 'none'
@checked = false
@warnMsg = 'none'
@debug = false
@pubs = []
@urls = []
@tabs = {}
@router = null
@routeLast = 'none'
@museLevels = ['Comp','Prac','Disp']
@museComps = ['Home','Prin','Info','Know','Wise','Cube','Test']
@museInovs = ['Info','Know','Wise','Soft','Data','Scie','Math']
@musePlanes = ['Info','Know','Wise']
# Special publsher for Vizu side bar
pubVizu:( obj ) ->
# console.log('Nav.pubVizu()', obj )
@stream.publish( 'Vizu', obj )
return
pub:( msg, isReplay=false ) ->
changeView = @viewChange( msg )
obj = @toObj( msg )
url = @toUrl( obj )
console.log('Nav.pub()', obj )
@doRoute( obj ) if @isRoutes
@pubs.push( obj ) if not isReplay and obj.compKey isnt 'Test'
@urls.push( url ) if not isReplay and obj.compKey isnt 'Test'
@stream.publish( 'View', obj ) if changeView
@stream.publish( 'Nav', obj )
return
viewChange:( obj ) ->
obj.compKey = @compKey if not @isDef(obj.compKey)
obj.pracKey = @pracKey if not @isDef(obj.pracKey)
obj.dispKey = @dispKey if not @isDef(obj.dispKey)
change = not ( obj.compKey is @compKey and obj.pracKey is @pracKey and obj.dispKey is @dispKey )
console.log( 'Nav.viewChange()', { change:change, compObj:obj.compKey, compNav:@compKey,
pracObj:obj.pracKey, pracNav:@pracKey, dispObj:obj.dispKey, dispNav:@dispKey, } ) if @debug and change
change
toObj:( msg ) ->
@set( msg )
@source = 'none' if not msg.source?
@pracKey = 'none' if @level is 'Comp'
@dispKey = 'none' if @level isnt 'Disp'
obj = { source:@source, level:@level, compKey:@compKey, pracKey:@pracKey, dispKey:@dispKey, pageKey:@pageKey }
obj.pageKey = @objPage( obj )
obj.inovKey = @objInov( obj )
obj.choice = @choice if @isApp('Jitter')
obj.checked = @checked if @isApp('Jitter')
obj.warnMsg = @warnMsg if @warnMsg isnt 'none'
@tab( obj ) # Publisn pageKey and inovKey to tabs
obj
set:( msg ) ->
for own key, val of msg
@[key] = val
return
tab:( obj ) ->
if @isDef(obj.pageKey)
@pageKey = obj.pageKey
tabsKey = @getTabsKey(obj)
@setPageKey( tabsKey, obj.pageKey, {} ) # Short message on 'Tab' subject
@stream.publish( 'Tab', { compKey:tabsKey, pageKey:obj.pageKey } )
console.log( 'Nav.set() pageKey', { compKey:tabsKey, pageKey:obj.pageKey } ) if @debug
if @isDef(obj.inovKey)
@inovKey = obj.inovKey
@setPageKey( obj.compKey, obj.inovKey, {} ) # Short message on 'Tab' subject
@stream.publish( 'Tab', { compKey:obj.compKey, pageKey:obj.inovKey } )
console.log( 'Nav.set() inovKey', { compKey:obj.compKey, inovKey:obj.inovKey } ) if @debug
return
toUrl:( obj ) ->
page = @objPage( obj )
inov = @objInov( obj )
url = window.location.protocol + '//' + window.location.host
url += if obj.compKey is 'Home' then '' else '/' + obj.compKey
url += '/' + obj.pracKey if obj.pracKey isnt 'none'
url += '/' + obj.dispKey if obj.dispKey isnt 'none'
url += '?' + 'page=' + page if page isnt 'none'
url += '&' + 'innovate=' + inov if inov isnt 'none'
console.log( 'Nav.toUrl()', url ) if @debug
window.history.pushState( {}, '', url )
url
toPub:( href ) =>
obj = {}
url = new URL(href)
page = url.searchParams.get("page")
innovate = url.searchParams.get("innovate")
paths = url.pathname.split('/')
obj.source = 'Url'
obj.compKey = if @isStr(paths[1]) then paths[1] else 'Home'
obj.pracKey = if @isStr(paths[2]) then paths[2] else 'none'
obj.dispKey = if @isStr(paths[3]) then paths[3] else 'none'
obj.pageKey = if page? then page else 'none'
obj.inovKey = if innovate? then innovate else 'none'
obj.level =
if obj.dispKey isnt 'none' then 'Disp'
else if obj.pracKey isnt 'none' then 'Prac'
else 'Comp'
console.log( 'Nav.toPub()', { url:href, obj:obj, paths:paths } ) if @debug
obj
doDir:( direct ) ->
@dir.dir( direct )
return
mountTouch:( msg, elem, nextTick, incKlasses, excKlasses=[] ) ->
nextTick( () =>
if @isDef(elem) and @touch?
@touch.listen( elem, incKlasses, excKlasses )
else
console.error( msg, "Nav.mountTouch() elem or touch undefined" ) )
return
doRoute:( obj ) ->
route = obj.compKey
return if route is @routeLast or route is 'none' or @isInov(route)
if @router?
@router.push( name:route )
else
console.error( 'Nav.doRoute() router not set for', route )
@routeLast = route
return
getTabsKey:( obj ) ->
tabsKey = 'none'
if @isApp('Muse')
tabsKey = obj.level if @inArray(obj.compKey,@musePlanes)
tabsKey = 'Prin' if obj.compKey is 'Pr<KEY>' and obj.level is 'Comp'
tabsKey = '<KEY>' if obj.compKey is '<KEY>' and obj.level is 'Prac'
else
tabsKey = switch obj.level
when 'Comp' then obj.compKey
when 'Prac' then obj.pracKey
when 'Disp' then obj.dispKey
else obj.compKey
tabsKey
objPage:( obj ) ->
if obj.page is 'none' then @getPageKey( @getTabsKey(obj), false ) else obj.pageKey
objInov:( obj ) ->
if @inArray(obj.compKey,@musePlanes) then @getPageKey(obj.compKey) else 'none'
isShow:( tabsKey, pageKey ) ->
pageNav = @getPageKey( tabsKey )
pageKey is pageNav
# When @page matches return
# otherwise look for when the page is true at eech level
# this supports setting show true in pages
show:( pageArg ) ->
switch
when pageArg is @pageKey then true
when @level is "Disp" then pageArg is @getPageKey( @dispKey )
when @level is "Prac" then pageArg is @getPageKey( @pracKey )
when @level is "Comp" then pageArg is @getPageKey( @compKey )
else false
keyIdx:( key, idx ) ->
key + idx
# An important indicator of when Comps and Tabs are instanciated
setTabs:( tabsKey, pages ) ->
return if @hasTabs(tabsKey,false )
@pages[tabsKey] = pages
return
getTabs:( tabsKey ) ->
if @hasTabs(tabsKey,true) then @pages[tabsKey] else {}
setPageKey:( tabsKey, pageKey, propTabs ) ->
return if pageKey is 'none'
for own key, page of @pages[tabsKey]
page.show = key is pageKey # Update nav pages
propTabs[key].show = key is pageKey if propTabs[key]? # Also update Tabs.vue propTabs because it is a copy
return
getPageKey:( tabsKey, log=false ) ->
return 'none' if not @hasTabs(tabsKey,log)
for own key, page of @pages[tabsKey]
return key if page.show
'none'
hasPage:( tabsKey, pageKey, log=true ) ->
if @isDef(tabsKey) and @hasTabs(tabsKey)
if @isDef(pageKey) and @pages[tabsKey][pageKey]?
true
else
console.log( 'Nav.hasPage() bad pageKey', { tabsKey:tabsKey, pageKey:pageKey, pages:getTabs:(tabsKey) } ) if log and pageKey isnt 'none'
false
else
console.log( 'Nav.hasPage() bad tabsKey', { tabsKey:tabsKey, pageKey:pageKey } ) if log and pageKey isnt 'none'
false
getPage:( tabsKey, pageKey, log=false ) ->
if @hasTabs(tabsKey,log) and @pages[tabsKey][pageKey]?
@pages[tabsKey][pageKey]
else
console.error( 'Nav.getPage() bad page', { tabsKey:tabsKey, pageKey:pageKey } )
'none'
getInovKey:( tabsKey ) ->
if @inArray(tabsKey,@musePlanes) then @getPageKey(tabsKey) else 'none'
hasTabs:( tabsKey, log=false ) ->
has = @isDef(tabsKey) and @isDef(@pages[tabsKey])
console.log( 'Nav.hasTabs()', { tabsKey:tabsKey, has:has, pages:@pages } ) if not has and log
has
isMyNav:( obj, level, checkPageKey=false ) -> # @routes, @routeNames,
if checkPageKey
obj.level is level and @hasTabs(obj.pageKey,true)
else
obj.level is level
pracs:( compKey ) ->
if @batch[compKey]? then @batch[compKey].data.pracs else {}
disps:( compKey, pracKey ) ->
if @batch[compKey]? then @batch[compKey].data.pracs[pracKey].disps else {}
# Called as await sleep(2000) inside an asych function
sleep:(ms) ->
new Promise( (resolve) => setTimeout( resolve, ms ) )
delayCallback:( ms, callback ) ->
setTimeout( callback, ms )
return
# --- Innovate --- Inov in one place
# Across the board Inov detector for compKey pageKey and route
isInov:( compKey ) ->
@inArray( compKey, @museInovs )
addInovToNavs:( komps ) ->
return komps? if not @isApp('Muse')
navs = Object.assign( {}, komps )
#avs = @insInov( navs, @museInovs )
navs
insInov:( navs, prev, inov, next ) ->
navs[prev].south = inov if navs[prev]?
navs[prev].next = inov if navs[next]?
navs[inov] = { north:prev, prev:prev, south:next, next:next }
navs[next].north = inov
navs[next].prev = inov
navs
userAgent:() ->
navigator.userAgent.toLowerCase()
# Looks up lower case strings in navigator userAngent
# like 'android' 'mac' 'iphone' 'firefox'
# not 100% certain but usefull
inUserAgent:( str ) ->
@userAgent().indexOf(str) > -1
isMobile:() ->
@inUserAgent('android') or @inUserAgent('iphone')
export default Nav
###
set:( msg, isReplay ) ->
if isReplay
if msg.pageKey isnt 'none'
tabsKey = @getTabsKey(msg)
@setPageKey( tabsKey, msg.pageKey, {} ) # Short message on 'Tab' subject
@stream.publish( 'Tab', { compKey:tabsKey, pageKey:msg.pageKey } )
console.log( 'Nav.set() pageKey', { compKey:tabsKey, pageKey:msg.pageKey } ) if @debug
if msg.inovKey isnt 'none'
@setPageKey( msg.compKey, msg.inovKey, {} ) # Short message on 'Tab' subject
@stream.publish( 'Tab', { compKey:msg.compKey, pageKey:msg.inovKey } )
console.log( 'Nav.set() inovKey', { compKey:msg.compKey, inovKey:msg.inovKey } ) if @debug
for own key, val of msg
@[key] = val
return
###
| true |
import Mix from './Mix.js'
import Build from '../util/Build.js'
import Dir from './Dir.js'
class Nav extends Mix
constructor:( Main, stream, komps=null, pages={}, isRoutes=false ) ->
super( Main )
@stream = stream
@komps = komps
@pages = pages
@isRoutes = isRoutes
@navs = if @komps then @addInovToNavs( @komps ) else null
@touch = null
@build = new Build( @batch )
@dir = new Dir( @ )
@source = 'none'
@level = 'none' # set to either Comp Prac or Disp by Tocs.vue
@compKey = 'none'
@pracKey = 'none'
@dispKey = 'none'
@pageKey = 'none'
@inovKey = 'none' # Only used by Tabs to Tocs.vue and Comp.vue
@choice = 'none'
@checked = false
@warnMsg = 'none'
@debug = false
@pubs = []
@urls = []
@tabs = {}
@router = null
@routeLast = 'none'
@museLevels = ['Comp','Prac','Disp']
@museComps = ['Home','Prin','Info','Know','Wise','Cube','Test']
@museInovs = ['Info','Know','Wise','Soft','Data','Scie','Math']
@musePlanes = ['Info','Know','Wise']
# Special publsher for Vizu side bar
pubVizu:( obj ) ->
# console.log('Nav.pubVizu()', obj )
@stream.publish( 'Vizu', obj )
return
pub:( msg, isReplay=false ) ->
changeView = @viewChange( msg )
obj = @toObj( msg )
url = @toUrl( obj )
console.log('Nav.pub()', obj )
@doRoute( obj ) if @isRoutes
@pubs.push( obj ) if not isReplay and obj.compKey isnt 'Test'
@urls.push( url ) if not isReplay and obj.compKey isnt 'Test'
@stream.publish( 'View', obj ) if changeView
@stream.publish( 'Nav', obj )
return
viewChange:( obj ) ->
obj.compKey = @compKey if not @isDef(obj.compKey)
obj.pracKey = @pracKey if not @isDef(obj.pracKey)
obj.dispKey = @dispKey if not @isDef(obj.dispKey)
change = not ( obj.compKey is @compKey and obj.pracKey is @pracKey and obj.dispKey is @dispKey )
console.log( 'Nav.viewChange()', { change:change, compObj:obj.compKey, compNav:@compKey,
pracObj:obj.pracKey, pracNav:@pracKey, dispObj:obj.dispKey, dispNav:@dispKey, } ) if @debug and change
change
toObj:( msg ) ->
@set( msg )
@source = 'none' if not msg.source?
@pracKey = 'none' if @level is 'Comp'
@dispKey = 'none' if @level isnt 'Disp'
obj = { source:@source, level:@level, compKey:@compKey, pracKey:@pracKey, dispKey:@dispKey, pageKey:@pageKey }
obj.pageKey = @objPage( obj )
obj.inovKey = @objInov( obj )
obj.choice = @choice if @isApp('Jitter')
obj.checked = @checked if @isApp('Jitter')
obj.warnMsg = @warnMsg if @warnMsg isnt 'none'
@tab( obj ) # Publisn pageKey and inovKey to tabs
obj
set:( msg ) ->
for own key, val of msg
@[key] = val
return
tab:( obj ) ->
if @isDef(obj.pageKey)
@pageKey = obj.pageKey
tabsKey = @getTabsKey(obj)
@setPageKey( tabsKey, obj.pageKey, {} ) # Short message on 'Tab' subject
@stream.publish( 'Tab', { compKey:tabsKey, pageKey:obj.pageKey } )
console.log( 'Nav.set() pageKey', { compKey:tabsKey, pageKey:obj.pageKey } ) if @debug
if @isDef(obj.inovKey)
@inovKey = obj.inovKey
@setPageKey( obj.compKey, obj.inovKey, {} ) # Short message on 'Tab' subject
@stream.publish( 'Tab', { compKey:obj.compKey, pageKey:obj.inovKey } )
console.log( 'Nav.set() inovKey', { compKey:obj.compKey, inovKey:obj.inovKey } ) if @debug
return
toUrl:( obj ) ->
page = @objPage( obj )
inov = @objInov( obj )
url = window.location.protocol + '//' + window.location.host
url += if obj.compKey is 'Home' then '' else '/' + obj.compKey
url += '/' + obj.pracKey if obj.pracKey isnt 'none'
url += '/' + obj.dispKey if obj.dispKey isnt 'none'
url += '?' + 'page=' + page if page isnt 'none'
url += '&' + 'innovate=' + inov if inov isnt 'none'
console.log( 'Nav.toUrl()', url ) if @debug
window.history.pushState( {}, '', url )
url
toPub:( href ) =>
obj = {}
url = new URL(href)
page = url.searchParams.get("page")
innovate = url.searchParams.get("innovate")
paths = url.pathname.split('/')
obj.source = 'Url'
obj.compKey = if @isStr(paths[1]) then paths[1] else 'Home'
obj.pracKey = if @isStr(paths[2]) then paths[2] else 'none'
obj.dispKey = if @isStr(paths[3]) then paths[3] else 'none'
obj.pageKey = if page? then page else 'none'
obj.inovKey = if innovate? then innovate else 'none'
obj.level =
if obj.dispKey isnt 'none' then 'Disp'
else if obj.pracKey isnt 'none' then 'Prac'
else 'Comp'
console.log( 'Nav.toPub()', { url:href, obj:obj, paths:paths } ) if @debug
obj
doDir:( direct ) ->
@dir.dir( direct )
return
mountTouch:( msg, elem, nextTick, incKlasses, excKlasses=[] ) ->
nextTick( () =>
if @isDef(elem) and @touch?
@touch.listen( elem, incKlasses, excKlasses )
else
console.error( msg, "Nav.mountTouch() elem or touch undefined" ) )
return
doRoute:( obj ) ->
route = obj.compKey
return if route is @routeLast or route is 'none' or @isInov(route)
if @router?
@router.push( name:route )
else
console.error( 'Nav.doRoute() router not set for', route )
@routeLast = route
return
getTabsKey:( obj ) ->
tabsKey = 'none'
if @isApp('Muse')
tabsKey = obj.level if @inArray(obj.compKey,@musePlanes)
tabsKey = 'Prin' if obj.compKey is 'PrPI:KEY:<KEY>END_PI' and obj.level is 'Comp'
tabsKey = 'PI:KEY:<KEY>END_PI' if obj.compKey is 'PI:KEY:<KEY>END_PI' and obj.level is 'Prac'
else
tabsKey = switch obj.level
when 'Comp' then obj.compKey
when 'Prac' then obj.pracKey
when 'Disp' then obj.dispKey
else obj.compKey
tabsKey
objPage:( obj ) ->
if obj.page is 'none' then @getPageKey( @getTabsKey(obj), false ) else obj.pageKey
objInov:( obj ) ->
if @inArray(obj.compKey,@musePlanes) then @getPageKey(obj.compKey) else 'none'
isShow:( tabsKey, pageKey ) ->
pageNav = @getPageKey( tabsKey )
pageKey is pageNav
# When @page matches return
# otherwise look for when the page is true at eech level
# this supports setting show true in pages
show:( pageArg ) ->
switch
when pageArg is @pageKey then true
when @level is "Disp" then pageArg is @getPageKey( @dispKey )
when @level is "Prac" then pageArg is @getPageKey( @pracKey )
when @level is "Comp" then pageArg is @getPageKey( @compKey )
else false
keyIdx:( key, idx ) ->
key + idx
# An important indicator of when Comps and Tabs are instanciated
setTabs:( tabsKey, pages ) ->
return if @hasTabs(tabsKey,false )
@pages[tabsKey] = pages
return
getTabs:( tabsKey ) ->
if @hasTabs(tabsKey,true) then @pages[tabsKey] else {}
setPageKey:( tabsKey, pageKey, propTabs ) ->
return if pageKey is 'none'
for own key, page of @pages[tabsKey]
page.show = key is pageKey # Update nav pages
propTabs[key].show = key is pageKey if propTabs[key]? # Also update Tabs.vue propTabs because it is a copy
return
getPageKey:( tabsKey, log=false ) ->
return 'none' if not @hasTabs(tabsKey,log)
for own key, page of @pages[tabsKey]
return key if page.show
'none'
hasPage:( tabsKey, pageKey, log=true ) ->
if @isDef(tabsKey) and @hasTabs(tabsKey)
if @isDef(pageKey) and @pages[tabsKey][pageKey]?
true
else
console.log( 'Nav.hasPage() bad pageKey', { tabsKey:tabsKey, pageKey:pageKey, pages:getTabs:(tabsKey) } ) if log and pageKey isnt 'none'
false
else
console.log( 'Nav.hasPage() bad tabsKey', { tabsKey:tabsKey, pageKey:pageKey } ) if log and pageKey isnt 'none'
false
getPage:( tabsKey, pageKey, log=false ) ->
if @hasTabs(tabsKey,log) and @pages[tabsKey][pageKey]?
@pages[tabsKey][pageKey]
else
console.error( 'Nav.getPage() bad page', { tabsKey:tabsKey, pageKey:pageKey } )
'none'
getInovKey:( tabsKey ) ->
if @inArray(tabsKey,@musePlanes) then @getPageKey(tabsKey) else 'none'
hasTabs:( tabsKey, log=false ) ->
has = @isDef(tabsKey) and @isDef(@pages[tabsKey])
console.log( 'Nav.hasTabs()', { tabsKey:tabsKey, has:has, pages:@pages } ) if not has and log
has
isMyNav:( obj, level, checkPageKey=false ) -> # @routes, @routeNames,
if checkPageKey
obj.level is level and @hasTabs(obj.pageKey,true)
else
obj.level is level
pracs:( compKey ) ->
if @batch[compKey]? then @batch[compKey].data.pracs else {}
disps:( compKey, pracKey ) ->
if @batch[compKey]? then @batch[compKey].data.pracs[pracKey].disps else {}
# Called as await sleep(2000) inside an asych function
sleep:(ms) ->
new Promise( (resolve) => setTimeout( resolve, ms ) )
delayCallback:( ms, callback ) ->
setTimeout( callback, ms )
return
# --- Innovate --- Inov in one place
# Across the board Inov detector for compKey pageKey and route
isInov:( compKey ) ->
@inArray( compKey, @museInovs )
addInovToNavs:( komps ) ->
return komps? if not @isApp('Muse')
navs = Object.assign( {}, komps )
#avs = @insInov( navs, @museInovs )
navs
insInov:( navs, prev, inov, next ) ->
navs[prev].south = inov if navs[prev]?
navs[prev].next = inov if navs[next]?
navs[inov] = { north:prev, prev:prev, south:next, next:next }
navs[next].north = inov
navs[next].prev = inov
navs
userAgent:() ->
navigator.userAgent.toLowerCase()
# Looks up lower case strings in navigator userAngent
# like 'android' 'mac' 'iphone' 'firefox'
# not 100% certain but usefull
inUserAgent:( str ) ->
@userAgent().indexOf(str) > -1
isMobile:() ->
@inUserAgent('android') or @inUserAgent('iphone')
export default Nav
###
set:( msg, isReplay ) ->
if isReplay
if msg.pageKey isnt 'none'
tabsKey = @getTabsKey(msg)
@setPageKey( tabsKey, msg.pageKey, {} ) # Short message on 'Tab' subject
@stream.publish( 'Tab', { compKey:tabsKey, pageKey:msg.pageKey } )
console.log( 'Nav.set() pageKey', { compKey:tabsKey, pageKey:msg.pageKey } ) if @debug
if msg.inovKey isnt 'none'
@setPageKey( msg.compKey, msg.inovKey, {} ) # Short message on 'Tab' subject
@stream.publish( 'Tab', { compKey:msg.compKey, pageKey:msg.inovKey } )
console.log( 'Nav.set() inovKey', { compKey:msg.compKey, inovKey:msg.inovKey } ) if @debug
for own key, val of msg
@[key] = val
return
###
|
[
{
"context": "rowClicked}>\n <td className='name'>Tage Test</td>\n <td className='date'>{@props",
"end": 963,
"score": 0.8235144019126892,
"start": 954,
"tag": "NAME",
"value": "Tage Test"
},
{
"context": " <ReportRow\n key=... | clients/widgets/expense/reportlist.cjsx | jacob22/accounting | 0 | /*
Copyright 2019 Open End AB
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
require('./reportlist.css')
define ['react', 'gettext'], (React, gettext) ->
_ = gettext.gettext
class ReportRow extends React.Component
_rowClicked: () =>
@props.rowClicked(@props.toid)
render: () ->
<tr
className={'table-info' if @props.selected}
onClick={@_rowClicked}>
<td className='name'>Tage Test</td>
<td className='date'>{@props.toi.date}</td>
<td className='state'>{@props.toi.state}</td>
<td className='amount'>{@props.toi.amount}</td>
</tr>
class ReportList extends React.Component
@defaultProps:
selected: null
empty_text: _('There are no reports')
constructor: (props) ->
super(props)
@state = selected: props.selected
componentWillReceiveProps: (props) ->
@setState(selected: props.selected)
_rowClicked: (toid) ->
@setState(selected: toid)
@props.verificationSelected(toid)
render: () ->
rows = (
<ReportRow
key={toid}
rowClicked={@_rowClicked.bind(this)}
toid={toid}
toi={@props.toiData[toid]}
selected={toid == @state.selected} /> for toid in @props.toilist
)
if not rows.length
<div className='reportlist empty'>
{@props.empty_text}
</div>
else
<div className='reportlist'>
<table className='table table-striped table-hover'>
<tbody>
{rows}
</tbody>
</table>
</div>
| 64178 | /*
Copyright 2019 Open End AB
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
require('./reportlist.css')
define ['react', 'gettext'], (React, gettext) ->
_ = gettext.gettext
class ReportRow extends React.Component
_rowClicked: () =>
@props.rowClicked(@props.toid)
render: () ->
<tr
className={'table-info' if @props.selected}
onClick={@_rowClicked}>
<td className='name'><NAME></td>
<td className='date'>{@props.toi.date}</td>
<td className='state'>{@props.toi.state}</td>
<td className='amount'>{@props.toi.amount}</td>
</tr>
class ReportList extends React.Component
@defaultProps:
selected: null
empty_text: _('There are no reports')
constructor: (props) ->
super(props)
@state = selected: props.selected
componentWillReceiveProps: (props) ->
@setState(selected: props.selected)
_rowClicked: (toid) ->
@setState(selected: toid)
@props.verificationSelected(toid)
render: () ->
rows = (
<ReportRow
key={to<KEY>}
rowClicked={@_rowClicked.bind(this)}
toid={toid}
toi={@props.toiData[toid]}
selected={toid == @state.selected} /> for toid in @props.toilist
)
if not rows.length
<div className='reportlist empty'>
{@props.empty_text}
</div>
else
<div className='reportlist'>
<table className='table table-striped table-hover'>
<tbody>
{rows}
</tbody>
</table>
</div>
| true | /*
Copyright 2019 Open End AB
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
require('./reportlist.css')
define ['react', 'gettext'], (React, gettext) ->
_ = gettext.gettext
class ReportRow extends React.Component
_rowClicked: () =>
@props.rowClicked(@props.toid)
render: () ->
<tr
className={'table-info' if @props.selected}
onClick={@_rowClicked}>
<td className='name'>PI:NAME:<NAME>END_PI</td>
<td className='date'>{@props.toi.date}</td>
<td className='state'>{@props.toi.state}</td>
<td className='amount'>{@props.toi.amount}</td>
</tr>
class ReportList extends React.Component
@defaultProps:
selected: null
empty_text: _('There are no reports')
constructor: (props) ->
super(props)
@state = selected: props.selected
componentWillReceiveProps: (props) ->
@setState(selected: props.selected)
_rowClicked: (toid) ->
@setState(selected: toid)
@props.verificationSelected(toid)
render: () ->
rows = (
<ReportRow
key={toPI:KEY:<KEY>END_PI}
rowClicked={@_rowClicked.bind(this)}
toid={toid}
toi={@props.toiData[toid]}
selected={toid == @state.selected} /> for toid in @props.toilist
)
if not rows.length
<div className='reportlist empty'>
{@props.empty_text}
</div>
else
<div className='reportlist'>
<table className='table table-striped table-hover'>
<tbody>
{rows}
</tbody>
</table>
</div>
|
[
{
"context": "###\n * @author \t\tAbdelhakim RAFIK\n * @version \tv1.0.1\n * @license \tMIT License\n * @",
"end": 33,
"score": 0.9998905062675476,
"start": 17,
"tag": "NAME",
"value": "Abdelhakim RAFIK"
},
{
"context": "nse \tMIT License\n * @copyright \tCopyright (c) 2021 Abdelhaki... | src/app/controllers/articleController.coffee | AbdelhakimRafik/Project | 1 | ###
* @author Abdelhakim RAFIK
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 Abdelhakim RAFIK
* @date June 2021
###
{ Article } = require '../../models'
###
Get all articles or filtred list if offset and limit are provided
###
module.exports.getArticles = (req, res) ->
# get articles
articles = await Article.findAll offset: req.params.offset, limit: req.params.limit
# return article list
res.json articles
###
Get article by id
###
module.exports.getArticleById = (req, res) ->
# get article from data base with given id
article = await Article.findByPk req.params.id
# return article
res.json article
###
Register a new article
###
module.exports.addArticle = (req, res) ->
# add article to database
Article.create req.body
.then () ->
# if article created successfully
res.json message: 'Article created successfully'
return
.catch (exp) ->
if exp.name is 'SequelizeValidationError'
res.status(400).json
message: 'Data validation error'
errors: exp.errors.map (err) -> err.message
else
res.staus(500).json
message: 'Server error occured'
return
return
###
Update a given article data
###
module.exports.updateArticle = (req, res) ->
# update article information
Article.update req.body, where: id: req.params.id
.then () ->
res.json message: "Article updated successfully"
return
.catch (exp) ->
if exp.name is 'SequelizeValidationError'
res.status(400).json
message: 'Data validation error'
errors: exp.errors.map (err) -> err.message
else
res.staus(500).json
message: 'Server error occured'
return
return
###
Delete article by given id
###
module.exports.deleteArticle = (req, res) ->
# delete article by id
deleted = await Article.destroy where: id: req.params.id
# if article deleted
if deleted
res.json
message: "Article deleted successfully"
else
res.status(500).json
message: "Article not found" | 178116 | ###
* @author <NAME>
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 <NAME>
* @date June 2021
###
{ Article } = require '../../models'
###
Get all articles or filtred list if offset and limit are provided
###
module.exports.getArticles = (req, res) ->
# get articles
articles = await Article.findAll offset: req.params.offset, limit: req.params.limit
# return article list
res.json articles
###
Get article by id
###
module.exports.getArticleById = (req, res) ->
# get article from data base with given id
article = await Article.findByPk req.params.id
# return article
res.json article
###
Register a new article
###
module.exports.addArticle = (req, res) ->
# add article to database
Article.create req.body
.then () ->
# if article created successfully
res.json message: 'Article created successfully'
return
.catch (exp) ->
if exp.name is 'SequelizeValidationError'
res.status(400).json
message: 'Data validation error'
errors: exp.errors.map (err) -> err.message
else
res.staus(500).json
message: 'Server error occured'
return
return
###
Update a given article data
###
module.exports.updateArticle = (req, res) ->
# update article information
Article.update req.body, where: id: req.params.id
.then () ->
res.json message: "Article updated successfully"
return
.catch (exp) ->
if exp.name is 'SequelizeValidationError'
res.status(400).json
message: 'Data validation error'
errors: exp.errors.map (err) -> err.message
else
res.staus(500).json
message: 'Server error occured'
return
return
###
Delete article by given id
###
module.exports.deleteArticle = (req, res) ->
# delete article by id
deleted = await Article.destroy where: id: req.params.id
# if article deleted
if deleted
res.json
message: "Article deleted successfully"
else
res.status(500).json
message: "Article not found" | true | ###
* @author PI:NAME:<NAME>END_PI
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 PI:NAME:<NAME>END_PI
* @date June 2021
###
{ Article } = require '../../models'
###
Get all articles or filtred list if offset and limit are provided
###
module.exports.getArticles = (req, res) ->
# get articles
articles = await Article.findAll offset: req.params.offset, limit: req.params.limit
# return article list
res.json articles
###
Get article by id
###
module.exports.getArticleById = (req, res) ->
# get article from data base with given id
article = await Article.findByPk req.params.id
# return article
res.json article
###
Register a new article
###
module.exports.addArticle = (req, res) ->
# add article to database
Article.create req.body
.then () ->
# if article created successfully
res.json message: 'Article created successfully'
return
.catch (exp) ->
if exp.name is 'SequelizeValidationError'
res.status(400).json
message: 'Data validation error'
errors: exp.errors.map (err) -> err.message
else
res.staus(500).json
message: 'Server error occured'
return
return
###
Update a given article data
###
module.exports.updateArticle = (req, res) ->
# update article information
Article.update req.body, where: id: req.params.id
.then () ->
res.json message: "Article updated successfully"
return
.catch (exp) ->
if exp.name is 'SequelizeValidationError'
res.status(400).json
message: 'Data validation error'
errors: exp.errors.map (err) -> err.message
else
res.staus(500).json
message: 'Server error occured'
return
return
###
Delete article by given id
###
module.exports.deleteArticle = (req, res) ->
# delete article by id
deleted = await Article.destroy where: id: req.params.id
# if article deleted
if deleted
res.json
message: "Article deleted successfully"
else
res.status(500).json
message: "Article not found" |
[
{
"context": "GS IN THE SOFTWARE.\n\n# Taken from hubot at commit 71d1c686d9ffdfad54751080c699979fa17190a1 and modified to fit current use.\n\nFs = require 'f",
"end": 1166,
"score": 0.9775893092155457,
"start": 1126,
"tag": "PASSWORD",
"value": "71d1c686d9ffdfad54751080c699979fa17190a1"
}... | src/bot.coffee | kumpelblase2/modlab-chat | 0 | # Copyright (c) 2013 GitHub Inc.
#
# 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.
# Taken from hubot at commit 71d1c686d9ffdfad54751080c699979fa17190a1 and modified to fit current use.
Fs = require 'fs'
Log = require 'log'
Path = require 'path'
HttpClient = require 'scoped-http-client'
{EventEmitter} = require 'events'
User = require './user'
Response = require './response'
{Listener,TextListener} = require './listener'
{EnterMessage,LeaveMessage,TopicMessage,CatchAllMessage} = require './message'
DEFAULT_ADAPTER = ['twitch']
class Bot
# bots receive messages from a chat source (Campfire, irc, etc), and
# dispatch them to matching listeners.
#
# adapterPath - A String of the path to local adapters.
# adapter - A String of the adapter name.
# httpd - A Boolean whether to enable the HTTP daemon.
# name - A String of the bot name, defaults to Hubot.
#
# Returns nothing.
constructor: (adapterPath, adapter, name = 'kumpelbot') ->
@name = name
@events = new EventEmitter
@alias = false
@adapter = null
@Response = Response
@commands = []
@listeners = []
@logger = new Log sails.config.log.level or 'info'
@pingIntervalId = null
@parseVersion()
@loadAdapter adapterPath, adapter
@adapterName = adapter
@errorHandlers = []
@on 'error', (err, msg) =>
@invokeErrorHandlers(err, msg)
process.on 'uncaughtException', (err) =>
@emit 'error', err
# Public: Adds a Listener that attempts to match incoming messages based on
# a Regex.
#
# regex - A Regex that determines if the callback should be called.
# callback - A Function that is called with a Response object.
#
# Returns nothing.
hear: (regex, callback) ->
@listeners.push new TextListener(@, regex, callback)
# Public: Adds a Listener that attempts to match incoming messages directed
# at the bot based on a Regex. All regexes treat patterns like they begin
# with a '^'
#
# regex - A Regex that determines if the callback should be called.
# callback - A Function that is called with a Response object.
#
# Returns nothing.
respond: (regex, callback) ->
re = regex.toString().split('/')
re.shift()
modifiers = re.pop()
if re[0] and re[0][0] is '^'
@logger.warning "Anchors don't work well with respond, perhaps you want to use 'hear'"
@logger.warning "The regex in question was #{regex.toString()}"
pattern = re.join('/')
name = @name.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
if @alias
alias = @alias.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
newRegex = new RegExp(
"^\\s*[@]?(?:#{alias}[:,]?|#{name}[:,]?)\\s*(?:#{pattern})"
modifiers
)
else
newRegex = new RegExp(
"^\\s*[@]?#{name}[:,]?\\s*(?:#{pattern})",
modifiers
)
@listeners.push new TextListener(@, newRegex, callback)
# Public: Adds a Listener that triggers when anyone enters the room.
#
# callback - A Function that is called with a Response object.
#
# Returns nothing.
enter: (callback) ->
@listeners.push new Listener(
@,
((msg) -> msg instanceof EnterMessage),
callback
)
# Public: Adds a Listener that triggers when anyone leaves the room.
#
# callback - A Function that is called with a Response object.
#
# Returns nothing.
leave: (callback) ->
@listeners.push new Listener(
@,
((msg) -> msg instanceof LeaveMessage),
callback
)
# Public: Adds an error handler when an uncaught exception or user emitted
# error event occurs.
#
# callback - A Function that is called with the error object.
#
# Returns nothing.
error: (callback) ->
@errorHandlers.push callback
# Calls and passes any registered error handlers for unhandled exceptions or
# user emitted error events.
#
# err - An Error object.
# msg - An optional Response object that generated the error
#
# Returns nothing.
invokeErrorHandlers: (err, msg) ->
@logger.error err.stack
for errorHandler in @errorHandlers
try
errorHandler(err, msg)
catch errErr
@logger.error "while invoking error handler: #{errErr}\n#{errErr.stack}"
# Public: Adds a Listener that triggers when no other text matchers match.
#
# callback - A Function that is called with a Response object.
#
# Returns nothing.
catchAll: (callback) ->
@listeners.push new Listener(
@,
((msg) -> msg instanceof CatchAllMessage),
((msg) -> msg.message = msg.message.message; callback msg)
)
# Public: Passes the given message to any interested Listeners.
#
# message - A Message instance. Listeners can flag this message as 'done' to
# prevent further execution.
#
# Returns nothing.
receive: (message) ->
results = []
for listener in @listeners
try
results.push listener.call(message)
break if message.done
catch error
@emit('error', error, new @Response(@, message, []))
false
if message not instanceof CatchAllMessage and results.indexOf(true) is -1
@receive new CatchAllMessage(message)
# Public: Loads a file in path.
#
# path - A String path on the filesystem.
# file - A String filename in path on the filesystem.
#
# Returns nothing.
loadFile: (path, file) ->
ext = Path.extname file
full = Path.join path, Path.basename(file, ext)
if require.extensions[ext]
try
require(full) @
@parseHelp Path.join(path, file)
catch error
@logger.error "Unable to load #{full}: #{error.stack}"
process.exit(1)
# Public: Loads every script in the given path.
#
# path - A String path on the filesystem.
#
# Returns nothing.
load: (path) ->
@logger.debug "Loading scripts from #{path}"
if Fs.existsSync(path)
for file in Fs.readdirSync(path).sort()
@loadFile path, file
# Load the adapter Hubot is going to use.
#
# path - A String of the path to adapter if local.
# adapter - A String of the adapter name to use.
#
# Returns nothing.
loadAdapter: (path, adapter) ->
@logger.debug "Loading adapter #{adapter}"
path = path || './adapters'
try
path = if adapter in DEFAULT_ADAPTER
"#{path}/#{adapter}"
else
adapter
@adapter = require(path).use @
catch err
@logger.error "Cannot load adapter #{adapter} - #{err}"
process.exit(1)
# Public: Help Commands for Running Scripts.
#
# Returns an Array of help commands for running scripts.
helpCommands: ->
@commands.sort()
# Private: load help info from a loaded script.
#
# path - A String path to the file on disk.
#
# Returns nothing.
parseHelp: (path) ->
@logger.debug "Parsing help for #{path}"
scriptName = Path.basename(path).replace /\.(coffee|js)$/, ''
scriptDocumentation = {}
body = Fs.readFileSync path, 'utf-8'
currentSection = null
for line in body.split "\n"
break unless line[0] is '#' or line.substr(0, 2) is '//'
cleanedLine = line.replace(/^(#|\/\/)\s?/, "").trim()
continue if cleanedLine.length is 0
continue if cleanedLine.toLowerCase() is 'none'
nextSection = cleanedLine.toLowerCase().replace(':', '')
if nextSection in HUBOT_DOCUMENTATION_SECTIONS
currentSection = nextSection
scriptDocumentation[currentSection] = []
else
if currentSection
scriptDocumentation[currentSection].push cleanedLine.trim()
if currentSection is 'commands'
@commands.push cleanedLine.trim()
if currentSection is null
@logger.info "#{path} is using deprecated documentation syntax"
scriptDocumentation.commands = []
for line in body.split("\n")
break if not (line[0] is '#' or line.substr(0, 2) is '//')
continue if not line.match('-')
cleanedLine = line[2..line.length].replace(/^hubot/i, @name).trim()
scriptDocumentation.commands.push cleanedLine
@commands.push cleanedLine
# Public: A helper send function which delegates to the adapter's send
# function.
#
# user - A User instance.
# strings - One or more Strings for each message to send.
#
# Returns nothing.
send: (user, strings...) ->
@adapter.send user, strings...
# Public: A helper reply function which delegates to the adapter's reply
# function.
#
# user - A User instance.
# strings - One or more Strings for each message to send.
#
# Returns nothing.
reply: (user, strings...) ->
@adapter.reply user, strings...
# Public: A helper send function to message a room that the bot is in.
#
# room - String designating the room to message.
# strings - One or more Strings for each message to send.
#
# Returns nothing.
messageRoom: (room, strings...) ->
user = { room: room }
@adapter.send user, strings...
# Public: A wrapper around the EventEmitter API to make usage
# semanticly better.
#
# event - The event name.
# listener - A Function that is called with the event parameter
# when event happens.
#
# Returns nothing.
on: (event, args...) ->
@events.on event, args...
# Public: A wrapper around the EventEmitter API to make usage
# semanticly better.
#
# event - The event name.
# args... - Arguments emitted by the event
#
# Returns nothing.
emit: (event, args...) ->
@events.emit event, args...
# Public: Kick off the event loop for the adapter
#
# Returns nothing.
run: ->
@emit "running"
@adapter.run()
# Public: Gracefully shutdown the bot process
#
# Returns nothing.
shutdown: ->
clearInterval @pingIntervalId if @pingIntervalId?
@adapter.close()
# Public: The version of Hubot from npm
#
# Returns a String of the version number.
parseVersion: ->
pkg = require Path.join __dirname, '..', 'package.json'
@version = pkg.version
# Public: Creates a scoped http client with chainable methods for
# modifying the request. This doesn't actually make a request though.
# Once your request is assembled, you can call `get()`/`post()`/etc to
# send the request.
#
# url - String URL to access.
#
# Examples:
#
# res.http("http://example.com")
# # set a single header
# .header('Authorization', 'bearer abcdef')
#
# # set multiple headers
# .headers(Authorization: 'bearer abcdef', Accept: 'application/json')
#
# # add URI query parameters
# .query(a: 1, b: 'foo & bar')
#
# # make the actual request
# .get() (err, res, body) ->
# console.log body
#
# # or, you can POST data
# .post(data) (err, res, body) ->
# console.log body
#
# Returns a ScopedClient instance.
http: (url) ->
HttpClient.create(url)
.header('User-Agent', "#{@name}/#{@version}")
module.exports = Bot
| 116591 | # Copyright (c) 2013 GitHub Inc.
#
# 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.
# Taken from hubot at commit <PASSWORD> and modified to fit current use.
Fs = require 'fs'
Log = require 'log'
Path = require 'path'
HttpClient = require 'scoped-http-client'
{EventEmitter} = require 'events'
User = require './user'
Response = require './response'
{Listener,TextListener} = require './listener'
{EnterMessage,LeaveMessage,TopicMessage,CatchAllMessage} = require './message'
DEFAULT_ADAPTER = ['twitch']
class Bot
# bots receive messages from a chat source (Campfire, irc, etc), and
# dispatch them to matching listeners.
#
# adapterPath - A String of the path to local adapters.
# adapter - A String of the adapter name.
# httpd - A Boolean whether to enable the HTTP daemon.
# name - A String of the bot name, defaults to Hubot.
#
# Returns nothing.
constructor: (adapterPath, adapter, name = 'kumpelbot') ->
@name = <NAME>
@events = new EventEmitter
@alias = false
@adapter = null
@Response = Response
@commands = []
@listeners = []
@logger = new Log sails.config.log.level or 'info'
@pingIntervalId = null
@parseVersion()
@loadAdapter adapterPath, adapter
@adapterName = adapter
@errorHandlers = []
@on 'error', (err, msg) =>
@invokeErrorHandlers(err, msg)
process.on 'uncaughtException', (err) =>
@emit 'error', err
# Public: Adds a Listener that attempts to match incoming messages based on
# a Regex.
#
# regex - A Regex that determines if the callback should be called.
# callback - A Function that is called with a Response object.
#
# Returns nothing.
hear: (regex, callback) ->
@listeners.push new TextListener(@, regex, callback)
# Public: Adds a Listener that attempts to match incoming messages directed
# at the bot based on a Regex. All regexes treat patterns like they begin
# with a '^'
#
# regex - A Regex that determines if the callback should be called.
# callback - A Function that is called with a Response object.
#
# Returns nothing.
respond: (regex, callback) ->
re = regex.toString().split('/')
re.shift()
modifiers = re.pop()
if re[0] and re[0][0] is '^'
@logger.warning "Anchors don't work well with respond, perhaps you want to use 'hear'"
@logger.warning "The regex in question was #{regex.toString()}"
pattern = re.join('/')
name = @name.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
if @alias
alias = @alias.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
newRegex = new RegExp(
"^\\s*[@]?(?:#{alias}[:,]?|#{name}[:,]?)\\s*(?:#{pattern})"
modifiers
)
else
newRegex = new RegExp(
"^\\s*[@]?#{name}[:,]?\\s*(?:#{pattern})",
modifiers
)
@listeners.push new TextListener(@, newRegex, callback)
# Public: Adds a Listener that triggers when anyone enters the room.
#
# callback - A Function that is called with a Response object.
#
# Returns nothing.
enter: (callback) ->
@listeners.push new Listener(
@,
((msg) -> msg instanceof EnterMessage),
callback
)
# Public: Adds a Listener that triggers when anyone leaves the room.
#
# callback - A Function that is called with a Response object.
#
# Returns nothing.
leave: (callback) ->
@listeners.push new Listener(
@,
((msg) -> msg instanceof LeaveMessage),
callback
)
# Public: Adds an error handler when an uncaught exception or user emitted
# error event occurs.
#
# callback - A Function that is called with the error object.
#
# Returns nothing.
error: (callback) ->
@errorHandlers.push callback
# Calls and passes any registered error handlers for unhandled exceptions or
# user emitted error events.
#
# err - An Error object.
# msg - An optional Response object that generated the error
#
# Returns nothing.
invokeErrorHandlers: (err, msg) ->
@logger.error err.stack
for errorHandler in @errorHandlers
try
errorHandler(err, msg)
catch errErr
@logger.error "while invoking error handler: #{errErr}\n#{errErr.stack}"
# Public: Adds a Listener that triggers when no other text matchers match.
#
# callback - A Function that is called with a Response object.
#
# Returns nothing.
catchAll: (callback) ->
@listeners.push new Listener(
@,
((msg) -> msg instanceof CatchAllMessage),
((msg) -> msg.message = msg.message.message; callback msg)
)
# Public: Passes the given message to any interested Listeners.
#
# message - A Message instance. Listeners can flag this message as 'done' to
# prevent further execution.
#
# Returns nothing.
receive: (message) ->
results = []
for listener in @listeners
try
results.push listener.call(message)
break if message.done
catch error
@emit('error', error, new @Response(@, message, []))
false
if message not instanceof CatchAllMessage and results.indexOf(true) is -1
@receive new CatchAllMessage(message)
# Public: Loads a file in path.
#
# path - A String path on the filesystem.
# file - A String filename in path on the filesystem.
#
# Returns nothing.
loadFile: (path, file) ->
ext = Path.extname file
full = Path.join path, Path.basename(file, ext)
if require.extensions[ext]
try
require(full) @
@parseHelp Path.join(path, file)
catch error
@logger.error "Unable to load #{full}: #{error.stack}"
process.exit(1)
# Public: Loads every script in the given path.
#
# path - A String path on the filesystem.
#
# Returns nothing.
load: (path) ->
@logger.debug "Loading scripts from #{path}"
if Fs.existsSync(path)
for file in Fs.readdirSync(path).sort()
@loadFile path, file
# Load the adapter Hubot is going to use.
#
# path - A String of the path to adapter if local.
# adapter - A String of the adapter name to use.
#
# Returns nothing.
loadAdapter: (path, adapter) ->
@logger.debug "Loading adapter #{adapter}"
path = path || './adapters'
try
path = if adapter in DEFAULT_ADAPTER
"#{path}/#{adapter}"
else
adapter
@adapter = require(path).use @
catch err
@logger.error "Cannot load adapter #{adapter} - #{err}"
process.exit(1)
# Public: Help Commands for Running Scripts.
#
# Returns an Array of help commands for running scripts.
helpCommands: ->
@commands.sort()
# Private: load help info from a loaded script.
#
# path - A String path to the file on disk.
#
# Returns nothing.
parseHelp: (path) ->
@logger.debug "Parsing help for #{path}"
scriptName = Path.basename(path).replace /\.(coffee|js)$/, ''
scriptDocumentation = {}
body = Fs.readFileSync path, 'utf-8'
currentSection = null
for line in body.split "\n"
break unless line[0] is '#' or line.substr(0, 2) is '//'
cleanedLine = line.replace(/^(#|\/\/)\s?/, "").trim()
continue if cleanedLine.length is 0
continue if cleanedLine.toLowerCase() is 'none'
nextSection = cleanedLine.toLowerCase().replace(':', '')
if nextSection in HUBOT_DOCUMENTATION_SECTIONS
currentSection = nextSection
scriptDocumentation[currentSection] = []
else
if currentSection
scriptDocumentation[currentSection].push cleanedLine.trim()
if currentSection is 'commands'
@commands.push cleanedLine.trim()
if currentSection is null
@logger.info "#{path} is using deprecated documentation syntax"
scriptDocumentation.commands = []
for line in body.split("\n")
break if not (line[0] is '#' or line.substr(0, 2) is '//')
continue if not line.match('-')
cleanedLine = line[2..line.length].replace(/^hubot/i, @name).trim()
scriptDocumentation.commands.push cleanedLine
@commands.push cleanedLine
# Public: A helper send function which delegates to the adapter's send
# function.
#
# user - A User instance.
# strings - One or more Strings for each message to send.
#
# Returns nothing.
send: (user, strings...) ->
@adapter.send user, strings...
# Public: A helper reply function which delegates to the adapter's reply
# function.
#
# user - A User instance.
# strings - One or more Strings for each message to send.
#
# Returns nothing.
reply: (user, strings...) ->
@adapter.reply user, strings...
# Public: A helper send function to message a room that the bot is in.
#
# room - String designating the room to message.
# strings - One or more Strings for each message to send.
#
# Returns nothing.
messageRoom: (room, strings...) ->
user = { room: room }
@adapter.send user, strings...
# Public: A wrapper around the EventEmitter API to make usage
# semanticly better.
#
# event - The event name.
# listener - A Function that is called with the event parameter
# when event happens.
#
# Returns nothing.
on: (event, args...) ->
@events.on event, args...
# Public: A wrapper around the EventEmitter API to make usage
# semanticly better.
#
# event - The event name.
# args... - Arguments emitted by the event
#
# Returns nothing.
emit: (event, args...) ->
@events.emit event, args...
# Public: Kick off the event loop for the adapter
#
# Returns nothing.
run: ->
@emit "running"
@adapter.run()
# Public: Gracefully shutdown the bot process
#
# Returns nothing.
shutdown: ->
clearInterval @pingIntervalId if @pingIntervalId?
@adapter.close()
# Public: The version of Hubot from npm
#
# Returns a String of the version number.
parseVersion: ->
pkg = require Path.join __dirname, '..', 'package.json'
@version = pkg.version
# Public: Creates a scoped http client with chainable methods for
# modifying the request. This doesn't actually make a request though.
# Once your request is assembled, you can call `get()`/`post()`/etc to
# send the request.
#
# url - String URL to access.
#
# Examples:
#
# res.http("http://example.com")
# # set a single header
# .header('Authorization', 'bearer abcdef')
#
# # set multiple headers
# .headers(Authorization: 'bearer abcdef', Accept: 'application/json')
#
# # add URI query parameters
# .query(a: 1, b: 'foo & bar')
#
# # make the actual request
# .get() (err, res, body) ->
# console.log body
#
# # or, you can POST data
# .post(data) (err, res, body) ->
# console.log body
#
# Returns a ScopedClient instance.
http: (url) ->
HttpClient.create(url)
.header('User-Agent', "#{@name}/#{@version}")
module.exports = Bot
| true | # Copyright (c) 2013 GitHub Inc.
#
# 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.
# Taken from hubot at commit PI:PASSWORD:<PASSWORD>END_PI and modified to fit current use.
Fs = require 'fs'
Log = require 'log'
Path = require 'path'
HttpClient = require 'scoped-http-client'
{EventEmitter} = require 'events'
User = require './user'
Response = require './response'
{Listener,TextListener} = require './listener'
{EnterMessage,LeaveMessage,TopicMessage,CatchAllMessage} = require './message'
DEFAULT_ADAPTER = ['twitch']
class Bot
# bots receive messages from a chat source (Campfire, irc, etc), and
# dispatch them to matching listeners.
#
# adapterPath - A String of the path to local adapters.
# adapter - A String of the adapter name.
# httpd - A Boolean whether to enable the HTTP daemon.
# name - A String of the bot name, defaults to Hubot.
#
# Returns nothing.
constructor: (adapterPath, adapter, name = 'kumpelbot') ->
@name = PI:NAME:<NAME>END_PI
@events = new EventEmitter
@alias = false
@adapter = null
@Response = Response
@commands = []
@listeners = []
@logger = new Log sails.config.log.level or 'info'
@pingIntervalId = null
@parseVersion()
@loadAdapter adapterPath, adapter
@adapterName = adapter
@errorHandlers = []
@on 'error', (err, msg) =>
@invokeErrorHandlers(err, msg)
process.on 'uncaughtException', (err) =>
@emit 'error', err
# Public: Adds a Listener that attempts to match incoming messages based on
# a Regex.
#
# regex - A Regex that determines if the callback should be called.
# callback - A Function that is called with a Response object.
#
# Returns nothing.
hear: (regex, callback) ->
@listeners.push new TextListener(@, regex, callback)
# Public: Adds a Listener that attempts to match incoming messages directed
# at the bot based on a Regex. All regexes treat patterns like they begin
# with a '^'
#
# regex - A Regex that determines if the callback should be called.
# callback - A Function that is called with a Response object.
#
# Returns nothing.
respond: (regex, callback) ->
re = regex.toString().split('/')
re.shift()
modifiers = re.pop()
if re[0] and re[0][0] is '^'
@logger.warning "Anchors don't work well with respond, perhaps you want to use 'hear'"
@logger.warning "The regex in question was #{regex.toString()}"
pattern = re.join('/')
name = @name.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
if @alias
alias = @alias.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
newRegex = new RegExp(
"^\\s*[@]?(?:#{alias}[:,]?|#{name}[:,]?)\\s*(?:#{pattern})"
modifiers
)
else
newRegex = new RegExp(
"^\\s*[@]?#{name}[:,]?\\s*(?:#{pattern})",
modifiers
)
@listeners.push new TextListener(@, newRegex, callback)
# Public: Adds a Listener that triggers when anyone enters the room.
#
# callback - A Function that is called with a Response object.
#
# Returns nothing.
enter: (callback) ->
@listeners.push new Listener(
@,
((msg) -> msg instanceof EnterMessage),
callback
)
# Public: Adds a Listener that triggers when anyone leaves the room.
#
# callback - A Function that is called with a Response object.
#
# Returns nothing.
leave: (callback) ->
@listeners.push new Listener(
@,
((msg) -> msg instanceof LeaveMessage),
callback
)
# Public: Adds an error handler when an uncaught exception or user emitted
# error event occurs.
#
# callback - A Function that is called with the error object.
#
# Returns nothing.
error: (callback) ->
@errorHandlers.push callback
# Calls and passes any registered error handlers for unhandled exceptions or
# user emitted error events.
#
# err - An Error object.
# msg - An optional Response object that generated the error
#
# Returns nothing.
invokeErrorHandlers: (err, msg) ->
@logger.error err.stack
for errorHandler in @errorHandlers
try
errorHandler(err, msg)
catch errErr
@logger.error "while invoking error handler: #{errErr}\n#{errErr.stack}"
# Public: Adds a Listener that triggers when no other text matchers match.
#
# callback - A Function that is called with a Response object.
#
# Returns nothing.
catchAll: (callback) ->
@listeners.push new Listener(
@,
((msg) -> msg instanceof CatchAllMessage),
((msg) -> msg.message = msg.message.message; callback msg)
)
# Public: Passes the given message to any interested Listeners.
#
# message - A Message instance. Listeners can flag this message as 'done' to
# prevent further execution.
#
# Returns nothing.
receive: (message) ->
results = []
for listener in @listeners
try
results.push listener.call(message)
break if message.done
catch error
@emit('error', error, new @Response(@, message, []))
false
if message not instanceof CatchAllMessage and results.indexOf(true) is -1
@receive new CatchAllMessage(message)
# Public: Loads a file in path.
#
# path - A String path on the filesystem.
# file - A String filename in path on the filesystem.
#
# Returns nothing.
loadFile: (path, file) ->
ext = Path.extname file
full = Path.join path, Path.basename(file, ext)
if require.extensions[ext]
try
require(full) @
@parseHelp Path.join(path, file)
catch error
@logger.error "Unable to load #{full}: #{error.stack}"
process.exit(1)
# Public: Loads every script in the given path.
#
# path - A String path on the filesystem.
#
# Returns nothing.
load: (path) ->
@logger.debug "Loading scripts from #{path}"
if Fs.existsSync(path)
for file in Fs.readdirSync(path).sort()
@loadFile path, file
# Load the adapter Hubot is going to use.
#
# path - A String of the path to adapter if local.
# adapter - A String of the adapter name to use.
#
# Returns nothing.
loadAdapter: (path, adapter) ->
@logger.debug "Loading adapter #{adapter}"
path = path || './adapters'
try
path = if adapter in DEFAULT_ADAPTER
"#{path}/#{adapter}"
else
adapter
@adapter = require(path).use @
catch err
@logger.error "Cannot load adapter #{adapter} - #{err}"
process.exit(1)
# Public: Help Commands for Running Scripts.
#
# Returns an Array of help commands for running scripts.
helpCommands: ->
@commands.sort()
# Private: load help info from a loaded script.
#
# path - A String path to the file on disk.
#
# Returns nothing.
parseHelp: (path) ->
@logger.debug "Parsing help for #{path}"
scriptName = Path.basename(path).replace /\.(coffee|js)$/, ''
scriptDocumentation = {}
body = Fs.readFileSync path, 'utf-8'
currentSection = null
for line in body.split "\n"
break unless line[0] is '#' or line.substr(0, 2) is '//'
cleanedLine = line.replace(/^(#|\/\/)\s?/, "").trim()
continue if cleanedLine.length is 0
continue if cleanedLine.toLowerCase() is 'none'
nextSection = cleanedLine.toLowerCase().replace(':', '')
if nextSection in HUBOT_DOCUMENTATION_SECTIONS
currentSection = nextSection
scriptDocumentation[currentSection] = []
else
if currentSection
scriptDocumentation[currentSection].push cleanedLine.trim()
if currentSection is 'commands'
@commands.push cleanedLine.trim()
if currentSection is null
@logger.info "#{path} is using deprecated documentation syntax"
scriptDocumentation.commands = []
for line in body.split("\n")
break if not (line[0] is '#' or line.substr(0, 2) is '//')
continue if not line.match('-')
cleanedLine = line[2..line.length].replace(/^hubot/i, @name).trim()
scriptDocumentation.commands.push cleanedLine
@commands.push cleanedLine
# Public: A helper send function which delegates to the adapter's send
# function.
#
# user - A User instance.
# strings - One or more Strings for each message to send.
#
# Returns nothing.
send: (user, strings...) ->
@adapter.send user, strings...
# Public: A helper reply function which delegates to the adapter's reply
# function.
#
# user - A User instance.
# strings - One or more Strings for each message to send.
#
# Returns nothing.
reply: (user, strings...) ->
@adapter.reply user, strings...
# Public: A helper send function to message a room that the bot is in.
#
# room - String designating the room to message.
# strings - One or more Strings for each message to send.
#
# Returns nothing.
messageRoom: (room, strings...) ->
user = { room: room }
@adapter.send user, strings...
# Public: A wrapper around the EventEmitter API to make usage
# semanticly better.
#
# event - The event name.
# listener - A Function that is called with the event parameter
# when event happens.
#
# Returns nothing.
on: (event, args...) ->
@events.on event, args...
# Public: A wrapper around the EventEmitter API to make usage
# semanticly better.
#
# event - The event name.
# args... - Arguments emitted by the event
#
# Returns nothing.
emit: (event, args...) ->
@events.emit event, args...
# Public: Kick off the event loop for the adapter
#
# Returns nothing.
run: ->
@emit "running"
@adapter.run()
# Public: Gracefully shutdown the bot process
#
# Returns nothing.
shutdown: ->
clearInterval @pingIntervalId if @pingIntervalId?
@adapter.close()
# Public: The version of Hubot from npm
#
# Returns a String of the version number.
parseVersion: ->
pkg = require Path.join __dirname, '..', 'package.json'
@version = pkg.version
# Public: Creates a scoped http client with chainable methods for
# modifying the request. This doesn't actually make a request though.
# Once your request is assembled, you can call `get()`/`post()`/etc to
# send the request.
#
# url - String URL to access.
#
# Examples:
#
# res.http("http://example.com")
# # set a single header
# .header('Authorization', 'bearer abcdef')
#
# # set multiple headers
# .headers(Authorization: 'bearer abcdef', Accept: 'application/json')
#
# # add URI query parameters
# .query(a: 1, b: 'foo & bar')
#
# # make the actual request
# .get() (err, res, body) ->
# console.log body
#
# # or, you can POST data
# .post(data) (err, res, body) ->
# console.log body
#
# Returns a ScopedClient instance.
http: (url) ->
HttpClient.create(url)
.header('User-Agent', "#{@name}/#{@version}")
module.exports = Bot
|
[
{
"context": "point_stack: []\n cur_sink_point : null\n key : 'ult'\n \n constructor : ()->\n @translator_hash = ",
"end": 3266,
"score": 0.9899770617485046,
"start": 3263,
"tag": "KEY",
"value": "ult"
}
] | src/translator.coffee | hu2prod/gram | 0 | require 'fy'
module = @
class @Sink_point
buffer : []
namespace : {}
constructor : ()->
@buffer = []
@namespace = {}
push : (v)-> @buffer.push v
unshift : (v)-> @buffer.unshift v
toStringBlockJS : ()->
ret = "\t" + @buffer.join "\n"
ret.replace /\n/g, "\n\t"
toString : ()-> @buffer.join "\n"
# ###################################################################################################
class @bin_op_translator_framework
template_pre: null
template : ''
constructor : (template, template_pre = null)->
@template = template
@template_pre = template_pre
apply_template : (template, ctx, array)->
list = template.split /(\$(?:1|2|op))/
for v,k in list
switch v
when "$1"
list[k] = array[0]
when "$2"
list[k] = array[2]
when "$op"
list[k] = array[1]
list.join ""
# херит всё, если в подстановке будет, например, $2
# template = template.replace /\$1/g, array[0]
# template = template.replace /\$2/g, array[2]
# template = template.replace /\$op/g,array[1]
translate : (ctx, array)->
if @template_pre
ctx.cur_sink_point.push @apply_template @template, ctx, array
@apply_template @template, ctx, array
class @bin_op_translator_holder
op_list : {}
constructor : ()->
@op_list = {}
translate : (ctx, node)->
key = node.value_array[1].value
throw new Error "unknown bin_op '#{key}' known bin_ops #{Object.keys(@op_list).join(' ')}" if !@op_list[key]?
left = ctx.translate node.value_array[0]
right = ctx.translate node.value_array[2]
@op_list[key].translate ctx, [ left , key , right ]
# ###################################################################################################
class @un_op_translator_framework
template_pre: null
template : ''
constructor : (template, template_pre = null)->
@template = template
@template_pre = template_pre
apply_template : (template, ctx, array)->
list = template.split /(\$(?:1|2|op))/
for v,k in list
switch v
when "$1"
list[k] = array[1]
when "$op"
list[k] = array[0]
list.join ""
# template = template.replace /\$1/g, array[1]
# template = template.replace /\$op/g,array[0]
translate : (ctx, array)->
if @template_pre
ctx.cur_sink_point.push @apply_template @template, ctx, array
@apply_template @template, ctx, array
class @un_op_translator_holder
op_list : {}
op_position : 0 # default pre
left_position : 1
constructor : ()->
@op_list = {}
translate : (ctx, node)->
key = node.value_array[@op_position].value
throw new Error "unknown un_op '#{key}' known un_ops #{Object.keys(@op_list).join(' ')}" if !@op_list[key]?
left = ctx.translate node.value_array[@left_position]
@op_list[key].translate ctx, [ key , left ]
mode_pre : ()->
@op_position = 0
@left_position = 1
mode_post : ()->
@op_position = 1
@left_position = 0
# ###################################################################################################
class @Translator
translator_hash : {}
sink_point_stack: []
cur_sink_point : null
key : 'ult'
constructor : ()->
@translator_hash = {}
@reset()
sink_begin : ()->
@sink_point_stack.push @cur_sink_point
@cur_sink_point = new module.Sink_point
return
sink_end : ()->
temp = @cur_sink_point.toString()
@cur_sink_point = @sink_point_stack.pop()
@cur_sink_point.push temp
return
reset : ()->
@cur_sink_point = new module.Sink_point
@sink_point_stack = []
translate : (node)->
key = node.mx_hash[@key]
throw new Error "unknown node type '#{key}' mx='#{JSON.stringify node.mx_hash}' required key '#{@key}' value='#{node.value}'" if !@translator_hash[key]?
@translator_hash[key].translate @, node
# really public
trans : (node)->
@reset()
@cur_sink_point.push @translate node
@cur_sink_point.toString()
go : (node)->
@trans node
#
| 176454 | require 'fy'
module = @
class @Sink_point
buffer : []
namespace : {}
constructor : ()->
@buffer = []
@namespace = {}
push : (v)-> @buffer.push v
unshift : (v)-> @buffer.unshift v
toStringBlockJS : ()->
ret = "\t" + @buffer.join "\n"
ret.replace /\n/g, "\n\t"
toString : ()-> @buffer.join "\n"
# ###################################################################################################
class @bin_op_translator_framework
template_pre: null
template : ''
constructor : (template, template_pre = null)->
@template = template
@template_pre = template_pre
apply_template : (template, ctx, array)->
list = template.split /(\$(?:1|2|op))/
for v,k in list
switch v
when "$1"
list[k] = array[0]
when "$2"
list[k] = array[2]
when "$op"
list[k] = array[1]
list.join ""
# херит всё, если в подстановке будет, например, $2
# template = template.replace /\$1/g, array[0]
# template = template.replace /\$2/g, array[2]
# template = template.replace /\$op/g,array[1]
translate : (ctx, array)->
if @template_pre
ctx.cur_sink_point.push @apply_template @template, ctx, array
@apply_template @template, ctx, array
class @bin_op_translator_holder
op_list : {}
constructor : ()->
@op_list = {}
translate : (ctx, node)->
key = node.value_array[1].value
throw new Error "unknown bin_op '#{key}' known bin_ops #{Object.keys(@op_list).join(' ')}" if !@op_list[key]?
left = ctx.translate node.value_array[0]
right = ctx.translate node.value_array[2]
@op_list[key].translate ctx, [ left , key , right ]
# ###################################################################################################
class @un_op_translator_framework
template_pre: null
template : ''
constructor : (template, template_pre = null)->
@template = template
@template_pre = template_pre
apply_template : (template, ctx, array)->
list = template.split /(\$(?:1|2|op))/
for v,k in list
switch v
when "$1"
list[k] = array[1]
when "$op"
list[k] = array[0]
list.join ""
# template = template.replace /\$1/g, array[1]
# template = template.replace /\$op/g,array[0]
translate : (ctx, array)->
if @template_pre
ctx.cur_sink_point.push @apply_template @template, ctx, array
@apply_template @template, ctx, array
class @un_op_translator_holder
op_list : {}
op_position : 0 # default pre
left_position : 1
constructor : ()->
@op_list = {}
translate : (ctx, node)->
key = node.value_array[@op_position].value
throw new Error "unknown un_op '#{key}' known un_ops #{Object.keys(@op_list).join(' ')}" if !@op_list[key]?
left = ctx.translate node.value_array[@left_position]
@op_list[key].translate ctx, [ key , left ]
mode_pre : ()->
@op_position = 0
@left_position = 1
mode_post : ()->
@op_position = 1
@left_position = 0
# ###################################################################################################
class @Translator
translator_hash : {}
sink_point_stack: []
cur_sink_point : null
key : '<KEY>'
constructor : ()->
@translator_hash = {}
@reset()
sink_begin : ()->
@sink_point_stack.push @cur_sink_point
@cur_sink_point = new module.Sink_point
return
sink_end : ()->
temp = @cur_sink_point.toString()
@cur_sink_point = @sink_point_stack.pop()
@cur_sink_point.push temp
return
reset : ()->
@cur_sink_point = new module.Sink_point
@sink_point_stack = []
translate : (node)->
key = node.mx_hash[@key]
throw new Error "unknown node type '#{key}' mx='#{JSON.stringify node.mx_hash}' required key '#{@key}' value='#{node.value}'" if !@translator_hash[key]?
@translator_hash[key].translate @, node
# really public
trans : (node)->
@reset()
@cur_sink_point.push @translate node
@cur_sink_point.toString()
go : (node)->
@trans node
#
| true | require 'fy'
module = @
class @Sink_point
buffer : []
namespace : {}
constructor : ()->
@buffer = []
@namespace = {}
push : (v)-> @buffer.push v
unshift : (v)-> @buffer.unshift v
toStringBlockJS : ()->
ret = "\t" + @buffer.join "\n"
ret.replace /\n/g, "\n\t"
toString : ()-> @buffer.join "\n"
# ###################################################################################################
class @bin_op_translator_framework
template_pre: null
template : ''
constructor : (template, template_pre = null)->
@template = template
@template_pre = template_pre
apply_template : (template, ctx, array)->
list = template.split /(\$(?:1|2|op))/
for v,k in list
switch v
when "$1"
list[k] = array[0]
when "$2"
list[k] = array[2]
when "$op"
list[k] = array[1]
list.join ""
# херит всё, если в подстановке будет, например, $2
# template = template.replace /\$1/g, array[0]
# template = template.replace /\$2/g, array[2]
# template = template.replace /\$op/g,array[1]
translate : (ctx, array)->
if @template_pre
ctx.cur_sink_point.push @apply_template @template, ctx, array
@apply_template @template, ctx, array
class @bin_op_translator_holder
op_list : {}
constructor : ()->
@op_list = {}
translate : (ctx, node)->
key = node.value_array[1].value
throw new Error "unknown bin_op '#{key}' known bin_ops #{Object.keys(@op_list).join(' ')}" if !@op_list[key]?
left = ctx.translate node.value_array[0]
right = ctx.translate node.value_array[2]
@op_list[key].translate ctx, [ left , key , right ]
# ###################################################################################################
class @un_op_translator_framework
template_pre: null
template : ''
constructor : (template, template_pre = null)->
@template = template
@template_pre = template_pre
apply_template : (template, ctx, array)->
list = template.split /(\$(?:1|2|op))/
for v,k in list
switch v
when "$1"
list[k] = array[1]
when "$op"
list[k] = array[0]
list.join ""
# template = template.replace /\$1/g, array[1]
# template = template.replace /\$op/g,array[0]
translate : (ctx, array)->
if @template_pre
ctx.cur_sink_point.push @apply_template @template, ctx, array
@apply_template @template, ctx, array
class @un_op_translator_holder
op_list : {}
op_position : 0 # default pre
left_position : 1
constructor : ()->
@op_list = {}
translate : (ctx, node)->
key = node.value_array[@op_position].value
throw new Error "unknown un_op '#{key}' known un_ops #{Object.keys(@op_list).join(' ')}" if !@op_list[key]?
left = ctx.translate node.value_array[@left_position]
@op_list[key].translate ctx, [ key , left ]
mode_pre : ()->
@op_position = 0
@left_position = 1
mode_post : ()->
@op_position = 1
@left_position = 0
# ###################################################################################################
class @Translator
translator_hash : {}
sink_point_stack: []
cur_sink_point : null
key : 'PI:KEY:<KEY>END_PI'
constructor : ()->
@translator_hash = {}
@reset()
sink_begin : ()->
@sink_point_stack.push @cur_sink_point
@cur_sink_point = new module.Sink_point
return
sink_end : ()->
temp = @cur_sink_point.toString()
@cur_sink_point = @sink_point_stack.pop()
@cur_sink_point.push temp
return
reset : ()->
@cur_sink_point = new module.Sink_point
@sink_point_stack = []
translate : (node)->
key = node.mx_hash[@key]
throw new Error "unknown node type '#{key}' mx='#{JSON.stringify node.mx_hash}' required key '#{@key}' value='#{node.value}'" if !@translator_hash[key]?
@translator_hash[key].translate @, node
# really public
trans : (node)->
@reset()
@cur_sink_point.push @translate node
@cur_sink_point.toString()
go : (node)->
@trans node
#
|
[
{
"context": "ib/jquery.js'\nMove = require './../move.coffee'\n\n# Tim Huminski's favorite move. Does base damage of 0.5,\n# Never",
"end": 82,
"score": 0.9959545135498047,
"start": 70,
"tag": "NAME",
"value": "Tim Huminski"
}
] | src/js/moves/sandal.coffee | nagn/Battle-Resolution | 0 | $ = require './../lib/jquery.js'
Move = require './../move.coffee'
# Tim Huminski's favorite move. Does base damage of 0.5,
# Never very effective
module.exports = class Sandal extends Move
constructor: () ->
super 'THROW SANDAL'
getDamage: () ->
return 0.5
use: (cb) ->
super()
@target.damage(@getDamage())
@announce cb, 'It was not very effective... But then again it never really is, is it?'
| 6659 | $ = require './../lib/jquery.js'
Move = require './../move.coffee'
# <NAME>'s favorite move. Does base damage of 0.5,
# Never very effective
module.exports = class Sandal extends Move
constructor: () ->
super 'THROW SANDAL'
getDamage: () ->
return 0.5
use: (cb) ->
super()
@target.damage(@getDamage())
@announce cb, 'It was not very effective... But then again it never really is, is it?'
| true | $ = require './../lib/jquery.js'
Move = require './../move.coffee'
# PI:NAME:<NAME>END_PI's favorite move. Does base damage of 0.5,
# Never very effective
module.exports = class Sandal extends Move
constructor: () ->
super 'THROW SANDAL'
getDamage: () ->
return 0.5
use: (cb) ->
super()
@target.damage(@getDamage())
@announce cb, 'It was not very effective... But then again it never really is, is it?'
|
[
{
"context": "event on exit\", ->\n command = 'echo \"Hello, wrold!\"'\n handler = jasmine.createSpy('onExit')\n\n ",
"end": 4097,
"score": 0.5473076701164246,
"start": 4093,
"tag": "NAME",
"value": "rold"
}
] | home/.atom/packages/run-command/spec/command-runner-spec.coffee | shadowbq/dot.atom | 0 | {CompositeDisposable} = require 'atom'
CommandRunner = require '../lib/command-runner'
describe "CommandRunner", ->
beforeEach ->
@runner = new CommandRunner()
it "runs commands", ->
command = 'echo "Hello, wrold!"'
waitsForPromise =>
@runner.run(command).then (result) ->
expect(result.output).toEqual("Hello, wrold!\r\n")
expect(result.exited).toBe(true)
it "runs commands in the working directory", ->
spyOn(CommandRunner, 'workingDirectory').andReturn('/usr')
command = 'pwd'
waitsForPromise =>
@runner.run(command).then (result) ->
expect(result.output).toEqual('/usr\r\n')
it "returns all command results", ->
command = 'echo "out"; echo "more out"; >&2 echo "error"; false'
waitsForPromise =>
@runner.run(command).then (result) ->
expect(result.output).toEqual("out\r\nmore out\r\nerror\r\n")
expect(result.exited).toBe(true)
it "returns raw escape codes", ->
command = 'echo -e "\\x1B[31mHello\\033[0m, wrold!"'
waitsForPromise =>
@runner.run(command).then (result) ->
expect(result.output).toEqual("\x1B[31mHello\x1B[0m, wrold!\r\n")
it "can kill a long-running command", ->
command = 'while true; do echo -n; done'
promise = @runner.run(command)
@runner.kill('SIGKILL')
waitsForPromise ->
promise.then (result) ->
expect(result.signal).toEqual('SIGKILL')
it "kills one command before starting another", ->
firstCommand = 'while true; do echo -n; done'
secondCommand = 'echo -n'
firstPromise = @runner.run(firstCommand)
secondPromise = @runner.run(secondCommand)
waitsForPromise ->
firstPromise.then (result) ->
expect(result.signal).toBeTruthy()
waitsForPromise ->
secondPromise.then (result) ->
expect(result.exited).toBe(true)
describe "the working directory", ->
it "is set to a project directory", ->
spyOn(atom.workspace, 'getActiveTextEditor').andReturn(null)
spyOn(atom.project, 'getPaths').andReturn(['/foo/bar/baz'])
expect(CommandRunner.workingDirectory()).toEqual('/foo/bar/baz')
it "is set to the project directory of the current file", ->
spyOn(atom.workspace, 'getActiveTextEditor').andReturn
getPath: -> '/foo/baz/asdf/jkl.txt'
spyOn(atom.project, 'getPaths').andReturn [
'/foo/bar',
'/foo/baz',
'/foo/qux'
]
spyOn(atom.project, 'relativizePath').andReturn [
'/foo/baz', 'asdf/jkl.txt'
]
expect(CommandRunner.workingDirectory()).toEqual('/foo/baz')
expect(atom.project.relativizePath)
.toHaveBeenCalledWith('/foo/baz/asdf/jkl.txt')
it "is set to the current file path if not in a project", ->
spyOn(atom.workspace, 'getActiveTextEditor').andReturn
getPath: -> '/foo/baz/asdf/jkl.txt'
spyOn(atom.project, 'getPaths').andReturn(null)
expect(CommandRunner.workingDirectory()).toEqual('/foo/baz/asdf')
it "is set to the user's home directory if nothing is open", ->
spyOn(CommandRunner, 'homeDirectory').andReturn('/home/me')
spyOn(atom.workspace, 'getActiveTextEditor').andReturn(null)
spyOn(atom.project, 'getPaths').andReturn(null)
expect(CommandRunner.workingDirectory()).toEqual('/home/me')
describe "events", ->
it "emits an event when running a command", ->
command = 'echo "foo"'
handler = jasmine.createSpy('onCommand')
@runner.onCommand(handler)
waitsForPromise =>
@runner.run(command).then ->
expect(handler).toHaveBeenCalledWith('echo "foo"')
expect(handler.calls.length).toEqual(1)
it "emits events on output", ->
command = 'echo "foobar"'
dataHandler = jasmine.createSpy('onData')
@runner.onData(dataHandler)
waitsForPromise =>
@runner.run(command).then ->
expect(dataHandler).toHaveBeenCalledWith("foobar\r\n")
expect(dataHandler.calls.length).toEqual(1)
it "emits an event on exit", ->
command = 'echo "Hello, wrold!"'
handler = jasmine.createSpy('onExit')
@runner.onExit(handler)
waitsForPromise =>
@runner.run(command).then ->
expect(handler).toHaveBeenCalled()
expect(handler.calls.length).toEqual(1)
it "emits an event on kill", ->
command = 'while true; do echo -n; done'
handler = jasmine.createSpy('onKill')
@runner.onKill(handler)
promise = @runner.run(command)
@runner.kill('SIGKILL')
waitsForPromise ->
promise.then ->
expect(handler).toHaveBeenCalledWith('SIGKILL')
expect(handler.calls.length).toEqual(1)
| 114455 | {CompositeDisposable} = require 'atom'
CommandRunner = require '../lib/command-runner'
describe "CommandRunner", ->
beforeEach ->
@runner = new CommandRunner()
it "runs commands", ->
command = 'echo "Hello, wrold!"'
waitsForPromise =>
@runner.run(command).then (result) ->
expect(result.output).toEqual("Hello, wrold!\r\n")
expect(result.exited).toBe(true)
it "runs commands in the working directory", ->
spyOn(CommandRunner, 'workingDirectory').andReturn('/usr')
command = 'pwd'
waitsForPromise =>
@runner.run(command).then (result) ->
expect(result.output).toEqual('/usr\r\n')
it "returns all command results", ->
command = 'echo "out"; echo "more out"; >&2 echo "error"; false'
waitsForPromise =>
@runner.run(command).then (result) ->
expect(result.output).toEqual("out\r\nmore out\r\nerror\r\n")
expect(result.exited).toBe(true)
it "returns raw escape codes", ->
command = 'echo -e "\\x1B[31mHello\\033[0m, wrold!"'
waitsForPromise =>
@runner.run(command).then (result) ->
expect(result.output).toEqual("\x1B[31mHello\x1B[0m, wrold!\r\n")
it "can kill a long-running command", ->
command = 'while true; do echo -n; done'
promise = @runner.run(command)
@runner.kill('SIGKILL')
waitsForPromise ->
promise.then (result) ->
expect(result.signal).toEqual('SIGKILL')
it "kills one command before starting another", ->
firstCommand = 'while true; do echo -n; done'
secondCommand = 'echo -n'
firstPromise = @runner.run(firstCommand)
secondPromise = @runner.run(secondCommand)
waitsForPromise ->
firstPromise.then (result) ->
expect(result.signal).toBeTruthy()
waitsForPromise ->
secondPromise.then (result) ->
expect(result.exited).toBe(true)
describe "the working directory", ->
it "is set to a project directory", ->
spyOn(atom.workspace, 'getActiveTextEditor').andReturn(null)
spyOn(atom.project, 'getPaths').andReturn(['/foo/bar/baz'])
expect(CommandRunner.workingDirectory()).toEqual('/foo/bar/baz')
it "is set to the project directory of the current file", ->
spyOn(atom.workspace, 'getActiveTextEditor').andReturn
getPath: -> '/foo/baz/asdf/jkl.txt'
spyOn(atom.project, 'getPaths').andReturn [
'/foo/bar',
'/foo/baz',
'/foo/qux'
]
spyOn(atom.project, 'relativizePath').andReturn [
'/foo/baz', 'asdf/jkl.txt'
]
expect(CommandRunner.workingDirectory()).toEqual('/foo/baz')
expect(atom.project.relativizePath)
.toHaveBeenCalledWith('/foo/baz/asdf/jkl.txt')
it "is set to the current file path if not in a project", ->
spyOn(atom.workspace, 'getActiveTextEditor').andReturn
getPath: -> '/foo/baz/asdf/jkl.txt'
spyOn(atom.project, 'getPaths').andReturn(null)
expect(CommandRunner.workingDirectory()).toEqual('/foo/baz/asdf')
it "is set to the user's home directory if nothing is open", ->
spyOn(CommandRunner, 'homeDirectory').andReturn('/home/me')
spyOn(atom.workspace, 'getActiveTextEditor').andReturn(null)
spyOn(atom.project, 'getPaths').andReturn(null)
expect(CommandRunner.workingDirectory()).toEqual('/home/me')
describe "events", ->
it "emits an event when running a command", ->
command = 'echo "foo"'
handler = jasmine.createSpy('onCommand')
@runner.onCommand(handler)
waitsForPromise =>
@runner.run(command).then ->
expect(handler).toHaveBeenCalledWith('echo "foo"')
expect(handler.calls.length).toEqual(1)
it "emits events on output", ->
command = 'echo "foobar"'
dataHandler = jasmine.createSpy('onData')
@runner.onData(dataHandler)
waitsForPromise =>
@runner.run(command).then ->
expect(dataHandler).toHaveBeenCalledWith("foobar\r\n")
expect(dataHandler.calls.length).toEqual(1)
it "emits an event on exit", ->
command = 'echo "Hello, w<NAME>!"'
handler = jasmine.createSpy('onExit')
@runner.onExit(handler)
waitsForPromise =>
@runner.run(command).then ->
expect(handler).toHaveBeenCalled()
expect(handler.calls.length).toEqual(1)
it "emits an event on kill", ->
command = 'while true; do echo -n; done'
handler = jasmine.createSpy('onKill')
@runner.onKill(handler)
promise = @runner.run(command)
@runner.kill('SIGKILL')
waitsForPromise ->
promise.then ->
expect(handler).toHaveBeenCalledWith('SIGKILL')
expect(handler.calls.length).toEqual(1)
| true | {CompositeDisposable} = require 'atom'
CommandRunner = require '../lib/command-runner'
describe "CommandRunner", ->
beforeEach ->
@runner = new CommandRunner()
it "runs commands", ->
command = 'echo "Hello, wrold!"'
waitsForPromise =>
@runner.run(command).then (result) ->
expect(result.output).toEqual("Hello, wrold!\r\n")
expect(result.exited).toBe(true)
it "runs commands in the working directory", ->
spyOn(CommandRunner, 'workingDirectory').andReturn('/usr')
command = 'pwd'
waitsForPromise =>
@runner.run(command).then (result) ->
expect(result.output).toEqual('/usr\r\n')
it "returns all command results", ->
command = 'echo "out"; echo "more out"; >&2 echo "error"; false'
waitsForPromise =>
@runner.run(command).then (result) ->
expect(result.output).toEqual("out\r\nmore out\r\nerror\r\n")
expect(result.exited).toBe(true)
it "returns raw escape codes", ->
command = 'echo -e "\\x1B[31mHello\\033[0m, wrold!"'
waitsForPromise =>
@runner.run(command).then (result) ->
expect(result.output).toEqual("\x1B[31mHello\x1B[0m, wrold!\r\n")
it "can kill a long-running command", ->
command = 'while true; do echo -n; done'
promise = @runner.run(command)
@runner.kill('SIGKILL')
waitsForPromise ->
promise.then (result) ->
expect(result.signal).toEqual('SIGKILL')
it "kills one command before starting another", ->
firstCommand = 'while true; do echo -n; done'
secondCommand = 'echo -n'
firstPromise = @runner.run(firstCommand)
secondPromise = @runner.run(secondCommand)
waitsForPromise ->
firstPromise.then (result) ->
expect(result.signal).toBeTruthy()
waitsForPromise ->
secondPromise.then (result) ->
expect(result.exited).toBe(true)
describe "the working directory", ->
it "is set to a project directory", ->
spyOn(atom.workspace, 'getActiveTextEditor').andReturn(null)
spyOn(atom.project, 'getPaths').andReturn(['/foo/bar/baz'])
expect(CommandRunner.workingDirectory()).toEqual('/foo/bar/baz')
it "is set to the project directory of the current file", ->
spyOn(atom.workspace, 'getActiveTextEditor').andReturn
getPath: -> '/foo/baz/asdf/jkl.txt'
spyOn(atom.project, 'getPaths').andReturn [
'/foo/bar',
'/foo/baz',
'/foo/qux'
]
spyOn(atom.project, 'relativizePath').andReturn [
'/foo/baz', 'asdf/jkl.txt'
]
expect(CommandRunner.workingDirectory()).toEqual('/foo/baz')
expect(atom.project.relativizePath)
.toHaveBeenCalledWith('/foo/baz/asdf/jkl.txt')
it "is set to the current file path if not in a project", ->
spyOn(atom.workspace, 'getActiveTextEditor').andReturn
getPath: -> '/foo/baz/asdf/jkl.txt'
spyOn(atom.project, 'getPaths').andReturn(null)
expect(CommandRunner.workingDirectory()).toEqual('/foo/baz/asdf')
it "is set to the user's home directory if nothing is open", ->
spyOn(CommandRunner, 'homeDirectory').andReturn('/home/me')
spyOn(atom.workspace, 'getActiveTextEditor').andReturn(null)
spyOn(atom.project, 'getPaths').andReturn(null)
expect(CommandRunner.workingDirectory()).toEqual('/home/me')
describe "events", ->
it "emits an event when running a command", ->
command = 'echo "foo"'
handler = jasmine.createSpy('onCommand')
@runner.onCommand(handler)
waitsForPromise =>
@runner.run(command).then ->
expect(handler).toHaveBeenCalledWith('echo "foo"')
expect(handler.calls.length).toEqual(1)
it "emits events on output", ->
command = 'echo "foobar"'
dataHandler = jasmine.createSpy('onData')
@runner.onData(dataHandler)
waitsForPromise =>
@runner.run(command).then ->
expect(dataHandler).toHaveBeenCalledWith("foobar\r\n")
expect(dataHandler.calls.length).toEqual(1)
it "emits an event on exit", ->
command = 'echo "Hello, wPI:NAME:<NAME>END_PI!"'
handler = jasmine.createSpy('onExit')
@runner.onExit(handler)
waitsForPromise =>
@runner.run(command).then ->
expect(handler).toHaveBeenCalled()
expect(handler.calls.length).toEqual(1)
it "emits an event on kill", ->
command = 'while true; do echo -n; done'
handler = jasmine.createSpy('onKill')
@runner.onKill(handler)
promise = @runner.run(command)
@runner.kill('SIGKILL')
waitsForPromise ->
promise.then ->
expect(handler).toHaveBeenCalledWith('SIGKILL')
expect(handler.calls.length).toEqual(1)
|
[
{
"context": "quire 'util'\r\nfs = require 'fs'\r\n\r\nACCOUNT_KEY = 'test'\r\nRECORD = false\r\nRECORDED_FILE = 'test/bing_nock",
"end": 147,
"score": 0.9978238344192505,
"start": 143,
"tag": "KEY",
"value": "test"
},
{
"context": "eturn results', (done) ->\r\n search.spelling ... | test/search.coffee | Cryptix720/Bing-AI | 0 | Search = require '../src/search'
nock = require 'nock'
should = require 'should'
util = require 'util'
fs = require 'fs'
ACCOUNT_KEY = 'test'
RECORD = false
RECORDED_FILE = 'test/bing_nock.json'
describe 'search', ->
search = null
beforeEach ->
search = new Search ACCOUNT_KEY
search.useGzip = false
before ->
if RECORD
nock.recorder.rec output_objects: true
else
nock.load RECORDED_FILE
after ->
if RECORD
out = JSON.stringify nock.recorder.play(), null, 2
fs.writeFileSync RECORDED_FILE, out
describe 'top generation', ->
describe 'when the number of results is 40', ->
it 'should generate a 1 item list', ->
search.generateTops(40).should.eql [40]
describe 'when the number of results is 50', ->
it 'should generate a 1 item list', ->
search.generateTops(50).should.eql [50]
describe 'when the number of results is 80', ->
it 'should generate a 2 item list', ->
search.generateTops(80).should.eql [50, 30]
describe 'when the number of results is 100', ->
it 'should generate a 2 item list', ->
search.generateTops(100).should.eql [50, 50]
describe 'when the number of results is 112', ->
it 'should generate a 3 item list', ->
search.generateTops(112).should.eql [50, 50, 12]
describe 'skip generation', ->
describe 'offset of 0', ->
it 'when the number of results is 40', ->
search.generateSkips(40, 0).should.eql [0]
it 'when the number of results is 50', ->
search.generateSkips(50, 0).should.eql [0]
it 'when the number of results is 80', ->
search.generateSkips(80, 0).should.eql [0, 50]
it 'when the number of results is 100', ->
search.generateSkips(100, 0).should.eql [0, 50]
it 'when the number of results is 112', ->
search.generateSkips(112, 0).should.eql [0, 50, 100]
describe 'offset of 30', ->
it 'when the number of results is 40', ->
search.generateSkips(40, 30).should.eql [30]
it 'when the number of results is 50', ->
search.generateSkips(50, 30).should.eql [30]
it 'when the number of results is 80', ->
search.generateSkips(80, 30).should.eql [30, 80]
it 'when the number of results is 100', ->
search.generateSkips(100, 30).should.eql [30, 80]
it 'when the number of results is 112', ->
search.generateSkips(112, 30).should.eql [30, 80, 130]
describe 'quoted', ->
it 'should wrap a string in single quotes', ->
search.quoted('hello').should.eql "'hello'"
it 'should escape strings contain quotes', ->
search.quoted("Jack's Coffee").should.eql "'Jack''s Coffee'"
it 'should generated a quoted string with items seperated by + for a list',
->
search.quoted(['web', 'image']).should.eql "'web+image'"
describe 'counts', ->
it 'should return counts for all verticals', (done) ->
search.counts 'Pizzeria Italia', (err, results) ->
should.not.exist err
results.should.eql
web: 463
image: 896
video: 29
news: 84
spelling: 0
done()
describe 'web', ->
it 'should return results', (done) ->
search.web 'Pizzeria Italia', (err, results) ->
should.not.exist err
results.length.should.eql 50
results[0].should.have.properties [
'id'
'title'
'description'
'displayUrl'
'url']
done()
it 'should return 100 results', (done) ->
search.web 'Pizzeria Italia', {top: 100}, (err, results) ->
should.not.exist err
results.length.should.eql 100
done()
describe 'images', ->
it 'should return results', (done) ->
search.images 'Pizzeria Italia', (err, results) ->
should.not.exist err
results.length.should.eql 50
results[0].should.have.properties [
'id'
'title'
'url'
'sourceUrl'
'displayUrl'
'width'
'height'
'size'
'type'
'thumbnail'
]
results[0].thumbnail.should.have.properties [
'url'
'type'
'width'
'height'
'size'
]
done()
describe 'videos', ->
it 'should return results', (done) ->
search.videos 'Pizzeria Italia', (err, results) ->
should.not.exist err
results.length.should.eql 29
results[0].should.have.properties [
'id'
'title'
'url'
'displayUrl'
'runtime'
'thumbnail'
]
results[0].thumbnail.should.have.properties [
'url'
'type'
'width'
'height'
'size'
]
done()
describe 'news', ->
it 'should return results', (done) ->
search.news 'Pizzeria Italia', (err, results) ->
should.not.exist err
results.length.should.eql 13
results[0].should.have.properties [
'id'
'title'
'source'
'url'
'description'
'date'
]
done()
describe 'spelling', ->
it 'should return results', (done) ->
search.spelling 'tutta bell', (err, results) ->
should.not.exist err
results.should.eql ['tutta bella']
done()
describe 'related', ->
it 'should return results', (done) ->
search.related 'tutta bella', (err, results) ->
should.not.exist err
results.length.should.eql 8
results[0].should.have.properties ['query', 'url']
done()
describe 'composite', ->
it 'should return results', (done) ->
search.composite 'Pizzeria Italia', (err, result) ->
should.not.exist err
result.should.have.properties [
'web'
'images'
'videos'
'news'
'spelling'
'related'
]
done()
| 96558 | Search = require '../src/search'
nock = require 'nock'
should = require 'should'
util = require 'util'
fs = require 'fs'
ACCOUNT_KEY = '<KEY>'
RECORD = false
RECORDED_FILE = 'test/bing_nock.json'
describe 'search', ->
search = null
beforeEach ->
search = new Search ACCOUNT_KEY
search.useGzip = false
before ->
if RECORD
nock.recorder.rec output_objects: true
else
nock.load RECORDED_FILE
after ->
if RECORD
out = JSON.stringify nock.recorder.play(), null, 2
fs.writeFileSync RECORDED_FILE, out
describe 'top generation', ->
describe 'when the number of results is 40', ->
it 'should generate a 1 item list', ->
search.generateTops(40).should.eql [40]
describe 'when the number of results is 50', ->
it 'should generate a 1 item list', ->
search.generateTops(50).should.eql [50]
describe 'when the number of results is 80', ->
it 'should generate a 2 item list', ->
search.generateTops(80).should.eql [50, 30]
describe 'when the number of results is 100', ->
it 'should generate a 2 item list', ->
search.generateTops(100).should.eql [50, 50]
describe 'when the number of results is 112', ->
it 'should generate a 3 item list', ->
search.generateTops(112).should.eql [50, 50, 12]
describe 'skip generation', ->
describe 'offset of 0', ->
it 'when the number of results is 40', ->
search.generateSkips(40, 0).should.eql [0]
it 'when the number of results is 50', ->
search.generateSkips(50, 0).should.eql [0]
it 'when the number of results is 80', ->
search.generateSkips(80, 0).should.eql [0, 50]
it 'when the number of results is 100', ->
search.generateSkips(100, 0).should.eql [0, 50]
it 'when the number of results is 112', ->
search.generateSkips(112, 0).should.eql [0, 50, 100]
describe 'offset of 30', ->
it 'when the number of results is 40', ->
search.generateSkips(40, 30).should.eql [30]
it 'when the number of results is 50', ->
search.generateSkips(50, 30).should.eql [30]
it 'when the number of results is 80', ->
search.generateSkips(80, 30).should.eql [30, 80]
it 'when the number of results is 100', ->
search.generateSkips(100, 30).should.eql [30, 80]
it 'when the number of results is 112', ->
search.generateSkips(112, 30).should.eql [30, 80, 130]
describe 'quoted', ->
it 'should wrap a string in single quotes', ->
search.quoted('hello').should.eql "'hello'"
it 'should escape strings contain quotes', ->
search.quoted("Jack's Coffee").should.eql "'Jack''s Coffee'"
it 'should generated a quoted string with items seperated by + for a list',
->
search.quoted(['web', 'image']).should.eql "'web+image'"
describe 'counts', ->
it 'should return counts for all verticals', (done) ->
search.counts 'Pizzeria Italia', (err, results) ->
should.not.exist err
results.should.eql
web: 463
image: 896
video: 29
news: 84
spelling: 0
done()
describe 'web', ->
it 'should return results', (done) ->
search.web 'Pizzeria Italia', (err, results) ->
should.not.exist err
results.length.should.eql 50
results[0].should.have.properties [
'id'
'title'
'description'
'displayUrl'
'url']
done()
it 'should return 100 results', (done) ->
search.web 'Pizzeria Italia', {top: 100}, (err, results) ->
should.not.exist err
results.length.should.eql 100
done()
describe 'images', ->
it 'should return results', (done) ->
search.images 'Pizzeria Italia', (err, results) ->
should.not.exist err
results.length.should.eql 50
results[0].should.have.properties [
'id'
'title'
'url'
'sourceUrl'
'displayUrl'
'width'
'height'
'size'
'type'
'thumbnail'
]
results[0].thumbnail.should.have.properties [
'url'
'type'
'width'
'height'
'size'
]
done()
describe 'videos', ->
it 'should return results', (done) ->
search.videos 'Pizzeria Italia', (err, results) ->
should.not.exist err
results.length.should.eql 29
results[0].should.have.properties [
'id'
'title'
'url'
'displayUrl'
'runtime'
'thumbnail'
]
results[0].thumbnail.should.have.properties [
'url'
'type'
'width'
'height'
'size'
]
done()
describe 'news', ->
it 'should return results', (done) ->
search.news 'Pizzeria Italia', (err, results) ->
should.not.exist err
results.length.should.eql 13
results[0].should.have.properties [
'id'
'title'
'source'
'url'
'description'
'date'
]
done()
describe 'spelling', ->
it 'should return results', (done) ->
search.spelling '<NAME>', (err, results) ->
should.not.exist err
results.should.eql ['<NAME>']
done()
describe 'related', ->
it 'should return results', (done) ->
search.related '<NAME>', (err, results) ->
should.not.exist err
results.length.should.eql 8
results[0].should.have.properties ['query', 'url']
done()
describe 'composite', ->
it 'should return results', (done) ->
search.composite 'Pizzeria Italia', (err, result) ->
should.not.exist err
result.should.have.properties [
'web'
'images'
'videos'
'news'
'spelling'
'related'
]
done()
| true | Search = require '../src/search'
nock = require 'nock'
should = require 'should'
util = require 'util'
fs = require 'fs'
ACCOUNT_KEY = 'PI:KEY:<KEY>END_PI'
RECORD = false
RECORDED_FILE = 'test/bing_nock.json'
describe 'search', ->
search = null
beforeEach ->
search = new Search ACCOUNT_KEY
search.useGzip = false
before ->
if RECORD
nock.recorder.rec output_objects: true
else
nock.load RECORDED_FILE
after ->
if RECORD
out = JSON.stringify nock.recorder.play(), null, 2
fs.writeFileSync RECORDED_FILE, out
describe 'top generation', ->
describe 'when the number of results is 40', ->
it 'should generate a 1 item list', ->
search.generateTops(40).should.eql [40]
describe 'when the number of results is 50', ->
it 'should generate a 1 item list', ->
search.generateTops(50).should.eql [50]
describe 'when the number of results is 80', ->
it 'should generate a 2 item list', ->
search.generateTops(80).should.eql [50, 30]
describe 'when the number of results is 100', ->
it 'should generate a 2 item list', ->
search.generateTops(100).should.eql [50, 50]
describe 'when the number of results is 112', ->
it 'should generate a 3 item list', ->
search.generateTops(112).should.eql [50, 50, 12]
describe 'skip generation', ->
describe 'offset of 0', ->
it 'when the number of results is 40', ->
search.generateSkips(40, 0).should.eql [0]
it 'when the number of results is 50', ->
search.generateSkips(50, 0).should.eql [0]
it 'when the number of results is 80', ->
search.generateSkips(80, 0).should.eql [0, 50]
it 'when the number of results is 100', ->
search.generateSkips(100, 0).should.eql [0, 50]
it 'when the number of results is 112', ->
search.generateSkips(112, 0).should.eql [0, 50, 100]
describe 'offset of 30', ->
it 'when the number of results is 40', ->
search.generateSkips(40, 30).should.eql [30]
it 'when the number of results is 50', ->
search.generateSkips(50, 30).should.eql [30]
it 'when the number of results is 80', ->
search.generateSkips(80, 30).should.eql [30, 80]
it 'when the number of results is 100', ->
search.generateSkips(100, 30).should.eql [30, 80]
it 'when the number of results is 112', ->
search.generateSkips(112, 30).should.eql [30, 80, 130]
describe 'quoted', ->
it 'should wrap a string in single quotes', ->
search.quoted('hello').should.eql "'hello'"
it 'should escape strings contain quotes', ->
search.quoted("Jack's Coffee").should.eql "'Jack''s Coffee'"
it 'should generated a quoted string with items seperated by + for a list',
->
search.quoted(['web', 'image']).should.eql "'web+image'"
describe 'counts', ->
it 'should return counts for all verticals', (done) ->
search.counts 'Pizzeria Italia', (err, results) ->
should.not.exist err
results.should.eql
web: 463
image: 896
video: 29
news: 84
spelling: 0
done()
describe 'web', ->
it 'should return results', (done) ->
search.web 'Pizzeria Italia', (err, results) ->
should.not.exist err
results.length.should.eql 50
results[0].should.have.properties [
'id'
'title'
'description'
'displayUrl'
'url']
done()
it 'should return 100 results', (done) ->
search.web 'Pizzeria Italia', {top: 100}, (err, results) ->
should.not.exist err
results.length.should.eql 100
done()
describe 'images', ->
it 'should return results', (done) ->
search.images 'Pizzeria Italia', (err, results) ->
should.not.exist err
results.length.should.eql 50
results[0].should.have.properties [
'id'
'title'
'url'
'sourceUrl'
'displayUrl'
'width'
'height'
'size'
'type'
'thumbnail'
]
results[0].thumbnail.should.have.properties [
'url'
'type'
'width'
'height'
'size'
]
done()
describe 'videos', ->
it 'should return results', (done) ->
search.videos 'Pizzeria Italia', (err, results) ->
should.not.exist err
results.length.should.eql 29
results[0].should.have.properties [
'id'
'title'
'url'
'displayUrl'
'runtime'
'thumbnail'
]
results[0].thumbnail.should.have.properties [
'url'
'type'
'width'
'height'
'size'
]
done()
describe 'news', ->
it 'should return results', (done) ->
search.news 'Pizzeria Italia', (err, results) ->
should.not.exist err
results.length.should.eql 13
results[0].should.have.properties [
'id'
'title'
'source'
'url'
'description'
'date'
]
done()
describe 'spelling', ->
it 'should return results', (done) ->
search.spelling 'PI:NAME:<NAME>END_PI', (err, results) ->
should.not.exist err
results.should.eql ['PI:NAME:<NAME>END_PI']
done()
describe 'related', ->
it 'should return results', (done) ->
search.related 'PI:NAME:<NAME>END_PI', (err, results) ->
should.not.exist err
results.length.should.eql 8
results[0].should.have.properties ['query', 'url']
done()
describe 'composite', ->
it 'should return results', (done) ->
search.composite 'Pizzeria Italia', (err, result) ->
should.not.exist err
result.should.have.properties [
'web'
'images'
'videos'
'news'
'spelling'
'related'
]
done()
|
[
{
"context": "e http://incident57.com/codekit/help.php\n# @author Matthew Wagerfield @mwagerfield\n#\n#=================================",
"end": 281,
"score": 0.9998957514762878,
"start": 263,
"tag": "NAME",
"value": "Matthew Wagerfield"
},
{
"context": ".com/codekit/help.php\n# @au... | assets/scripts/coffee/scripts.coffee | wagerfield/danbo | 1 | #============================================================
#
# CoffeeScript Imports
#
# Lists the source files to be concatenated and compiled into
# ../js/scripts.js using CodeKit's import directives.
#
# @see http://incident57.com/codekit/help.php
# @author Matthew Wagerfield @mwagerfield
#
#============================================================
#------------------------------
# Core
#------------------------------
# @codekit-prepend "core/Math.coffee"
# @codekit-prepend "core/Ease.coffee"
# @codekit-prepend "core/Color.coffee"
# @codekit-prepend "core/Utils.coffee"
# @codekit-prepend "core/Class.coffee"
# @codekit-prepend "core/Base.coffee"
# @codekit-prepend "core/Layout.coffee"
#------------------------------
# Scene
#------------------------------
# @codekit-prepend "project/scene/Scene.coffee"
#------------------------------
# Project
#------------------------------
# @codekit-prepend "project/Main.coffee"
# Initialise the project.
$ -> DANBO.initialise()
| 11702 | #============================================================
#
# CoffeeScript Imports
#
# Lists the source files to be concatenated and compiled into
# ../js/scripts.js using CodeKit's import directives.
#
# @see http://incident57.com/codekit/help.php
# @author <NAME> @mwagerfield
#
#============================================================
#------------------------------
# Core
#------------------------------
# @codekit-prepend "core/Math.coffee"
# @codekit-prepend "core/Ease.coffee"
# @codekit-prepend "core/Color.coffee"
# @codekit-prepend "core/Utils.coffee"
# @codekit-prepend "core/Class.coffee"
# @codekit-prepend "core/Base.coffee"
# @codekit-prepend "core/Layout.coffee"
#------------------------------
# Scene
#------------------------------
# @codekit-prepend "project/scene/Scene.coffee"
#------------------------------
# Project
#------------------------------
# @codekit-prepend "project/Main.coffee"
# Initialise the project.
$ -> DANBO.initialise()
| true | #============================================================
#
# CoffeeScript Imports
#
# Lists the source files to be concatenated and compiled into
# ../js/scripts.js using CodeKit's import directives.
#
# @see http://incident57.com/codekit/help.php
# @author PI:NAME:<NAME>END_PI @mwagerfield
#
#============================================================
#------------------------------
# Core
#------------------------------
# @codekit-prepend "core/Math.coffee"
# @codekit-prepend "core/Ease.coffee"
# @codekit-prepend "core/Color.coffee"
# @codekit-prepend "core/Utils.coffee"
# @codekit-prepend "core/Class.coffee"
# @codekit-prepend "core/Base.coffee"
# @codekit-prepend "core/Layout.coffee"
#------------------------------
# Scene
#------------------------------
# @codekit-prepend "project/scene/Scene.coffee"
#------------------------------
# Project
#------------------------------
# @codekit-prepend "project/Main.coffee"
# Initialise the project.
$ -> DANBO.initialise()
|
[
{
"context": "taObj[0].data.waveletData\n model.public = 'public@a.gwave.com' in waveletData.participants\n tasks = [\n ",
"end": 3028,
"score": 0.9998785257339478,
"start": 3010,
"tag": "EMAIL",
"value": "public@a.gwave.com"
},
{
"context": "heckWaveData, waveDataObj)... | src/server/import/source_saver.coffee | LaPingvino/rizzoma | 88 | _ = require('underscore')
async = require('async')
CouchImportProcessor = require('./couch_processor').CouchImportProcessor
ex = require('./exceptions')
DateUtils = require('../utils/date_utils').DateUtils
WaveImportData = require('./models').WaveImportData
ImportSourceParser = require('./source_parser').ImportSourceParser
waveCts = require('../wave/constants')
UserCouchProcessor = require('../user/couch_processor').UserCouchProcessor
class SourceSaver
constructor: () ->
_getWaveId: (waveData) ->
###
Возвращает id по которому будет сохранен снимок волны
waveId+waveletId
@param: waveData: Object
@returns: string
###
if not waveData[0] or not waveData[0].data or not waveData[0].data.waveletData
return null
waveletData = waveData[0].data.waveletData
return waveletData.waveId + '_' + waveletData.waveletId
_checkWaveData: (waveData, callback) =>
waveId = @_getWaveId(waveData)
if not waveId
return callback(new ex.SourceParseImportError('Wrong wave source format'))
CouchImportProcessor.getById(waveId, (err, dbWave) ->
return callback(err) if err and err.message != 'not_found'
return callback(null) if err
if dbWave.lastImportingTimestamp and dbWave.importedWaveId
err = new ex.WaveAlreadyImportedImportError('Wave already imported', { gWaveId: waveId, importedWaveId: dbWave.importedWaveUrl})
else
err = new ex.WaveImportingInProcessImportError('Wave importing in process', { gWaveId: waveId, importedWaveId: dbWave.importedWaveUrl})
callback(err)
)
_addUserToParticipants: (user, waveDataObj, callback) ->
tasks = [
async.apply(UserCouchProcessor.getById, user.id)
(user, callback) ->
waveletData = waveDataObj[0].data.waveletData
participantsData = ImportSourceParser.parseParticipantsEmailsAndRoles(waveletData)
if _.isEmpty(participantsData.participantRoles) or not participantsData.participantRoles[user.email]
participantsData.participantRoles[user.email] = waveCts.WAVE_ROLE_MODERATOR
participantsData.partcipantEmails.push(user.email)
waveletData.participants = participantsData.partcipantEmails
waveletData.participantRoles = participantsData.participantRoles
callback(null, waveDataObj)
]
async.waterfall(tasks, callback)
save: (user, waveData, callback) ->
try
waveDataObj = ImportSourceParser.sourceToObject(waveData)
catch e
console.error(e)
return callback(new SourceParseError('Wrong wave source format'), null)
waveId = @_getWaveId(waveDataObj)
model = new WaveImportData(waveId)
waveletData = waveDataObj[0].data.waveletData
model.public = 'public@a.gwave.com' in waveletData.participants
tasks = [
async.apply(@_checkWaveData, waveDataObj)
async.apply(@_addUserToParticipants, user, waveDataObj)
(waveDataObj, callback) =>
model.userId = user.id
waveletData = waveDataObj[0].data.waveletData
participantsData = ImportSourceParser.parseParticipantsEmailsAndRoles(waveletData)
model.participants = participantsData.partcipantEmails
try
model.sourceData = JSON.stringify(waveDataObj)
catch err
console.error(e)
return callback(new SourceParseError('Wrong wave source format'))
model.lastUpdateTimestamp = DateUtils.getCurrentTimestamp()
CouchImportProcessor.save(model, callback)
]
async.waterfall(tasks, (err) ->
callback(err, waveId)
)
module.exports.SourceSaver = new SourceSaver() | 59328 | _ = require('underscore')
async = require('async')
CouchImportProcessor = require('./couch_processor').CouchImportProcessor
ex = require('./exceptions')
DateUtils = require('../utils/date_utils').DateUtils
WaveImportData = require('./models').WaveImportData
ImportSourceParser = require('./source_parser').ImportSourceParser
waveCts = require('../wave/constants')
UserCouchProcessor = require('../user/couch_processor').UserCouchProcessor
class SourceSaver
constructor: () ->
_getWaveId: (waveData) ->
###
Возвращает id по которому будет сохранен снимок волны
waveId+waveletId
@param: waveData: Object
@returns: string
###
if not waveData[0] or not waveData[0].data or not waveData[0].data.waveletData
return null
waveletData = waveData[0].data.waveletData
return waveletData.waveId + '_' + waveletData.waveletId
_checkWaveData: (waveData, callback) =>
waveId = @_getWaveId(waveData)
if not waveId
return callback(new ex.SourceParseImportError('Wrong wave source format'))
CouchImportProcessor.getById(waveId, (err, dbWave) ->
return callback(err) if err and err.message != 'not_found'
return callback(null) if err
if dbWave.lastImportingTimestamp and dbWave.importedWaveId
err = new ex.WaveAlreadyImportedImportError('Wave already imported', { gWaveId: waveId, importedWaveId: dbWave.importedWaveUrl})
else
err = new ex.WaveImportingInProcessImportError('Wave importing in process', { gWaveId: waveId, importedWaveId: dbWave.importedWaveUrl})
callback(err)
)
_addUserToParticipants: (user, waveDataObj, callback) ->
tasks = [
async.apply(UserCouchProcessor.getById, user.id)
(user, callback) ->
waveletData = waveDataObj[0].data.waveletData
participantsData = ImportSourceParser.parseParticipantsEmailsAndRoles(waveletData)
if _.isEmpty(participantsData.participantRoles) or not participantsData.participantRoles[user.email]
participantsData.participantRoles[user.email] = waveCts.WAVE_ROLE_MODERATOR
participantsData.partcipantEmails.push(user.email)
waveletData.participants = participantsData.partcipantEmails
waveletData.participantRoles = participantsData.participantRoles
callback(null, waveDataObj)
]
async.waterfall(tasks, callback)
save: (user, waveData, callback) ->
try
waveDataObj = ImportSourceParser.sourceToObject(waveData)
catch e
console.error(e)
return callback(new SourceParseError('Wrong wave source format'), null)
waveId = @_getWaveId(waveDataObj)
model = new WaveImportData(waveId)
waveletData = waveDataObj[0].data.waveletData
model.public = '<EMAIL>' in waveletData.participants
tasks = [
async.apply(@_checkWaveData, waveDataObj)
async.apply(@_addUserToParticipants, user, waveDataObj)
(waveDataObj, callback) =>
model.userId = user.id
waveletData = waveDataObj[0].data.waveletData
participantsData = ImportSourceParser.parseParticipantsEmailsAndRoles(waveletData)
model.participants = participantsData.partcipantEmails
try
model.sourceData = JSON.stringify(waveDataObj)
catch err
console.error(e)
return callback(new SourceParseError('Wrong wave source format'))
model.lastUpdateTimestamp = DateUtils.getCurrentTimestamp()
CouchImportProcessor.save(model, callback)
]
async.waterfall(tasks, (err) ->
callback(err, waveId)
)
module.exports.SourceSaver = new SourceSaver() | true | _ = require('underscore')
async = require('async')
CouchImportProcessor = require('./couch_processor').CouchImportProcessor
ex = require('./exceptions')
DateUtils = require('../utils/date_utils').DateUtils
WaveImportData = require('./models').WaveImportData
ImportSourceParser = require('./source_parser').ImportSourceParser
waveCts = require('../wave/constants')
UserCouchProcessor = require('../user/couch_processor').UserCouchProcessor
class SourceSaver
constructor: () ->
_getWaveId: (waveData) ->
###
Возвращает id по которому будет сохранен снимок волны
waveId+waveletId
@param: waveData: Object
@returns: string
###
if not waveData[0] or not waveData[0].data or not waveData[0].data.waveletData
return null
waveletData = waveData[0].data.waveletData
return waveletData.waveId + '_' + waveletData.waveletId
_checkWaveData: (waveData, callback) =>
waveId = @_getWaveId(waveData)
if not waveId
return callback(new ex.SourceParseImportError('Wrong wave source format'))
CouchImportProcessor.getById(waveId, (err, dbWave) ->
return callback(err) if err and err.message != 'not_found'
return callback(null) if err
if dbWave.lastImportingTimestamp and dbWave.importedWaveId
err = new ex.WaveAlreadyImportedImportError('Wave already imported', { gWaveId: waveId, importedWaveId: dbWave.importedWaveUrl})
else
err = new ex.WaveImportingInProcessImportError('Wave importing in process', { gWaveId: waveId, importedWaveId: dbWave.importedWaveUrl})
callback(err)
)
_addUserToParticipants: (user, waveDataObj, callback) ->
tasks = [
async.apply(UserCouchProcessor.getById, user.id)
(user, callback) ->
waveletData = waveDataObj[0].data.waveletData
participantsData = ImportSourceParser.parseParticipantsEmailsAndRoles(waveletData)
if _.isEmpty(participantsData.participantRoles) or not participantsData.participantRoles[user.email]
participantsData.participantRoles[user.email] = waveCts.WAVE_ROLE_MODERATOR
participantsData.partcipantEmails.push(user.email)
waveletData.participants = participantsData.partcipantEmails
waveletData.participantRoles = participantsData.participantRoles
callback(null, waveDataObj)
]
async.waterfall(tasks, callback)
save: (user, waveData, callback) ->
try
waveDataObj = ImportSourceParser.sourceToObject(waveData)
catch e
console.error(e)
return callback(new SourceParseError('Wrong wave source format'), null)
waveId = @_getWaveId(waveDataObj)
model = new WaveImportData(waveId)
waveletData = waveDataObj[0].data.waveletData
model.public = 'PI:EMAIL:<EMAIL>END_PI' in waveletData.participants
tasks = [
async.apply(@_checkWaveData, waveDataObj)
async.apply(@_addUserToParticipants, user, waveDataObj)
(waveDataObj, callback) =>
model.userId = user.id
waveletData = waveDataObj[0].data.waveletData
participantsData = ImportSourceParser.parseParticipantsEmailsAndRoles(waveletData)
model.participants = participantsData.partcipantEmails
try
model.sourceData = JSON.stringify(waveDataObj)
catch err
console.error(e)
return callback(new SourceParseError('Wrong wave source format'))
model.lastUpdateTimestamp = DateUtils.getCurrentTimestamp()
CouchImportProcessor.save(model, callback)
]
async.waterfall(tasks, (err) ->
callback(err, waveId)
)
module.exports.SourceSaver = new SourceSaver() |
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.999909520149231,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/react/_components/comments-sort.coffee | osu-katakuna/osu-katakuna-web | 5 | # Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import { Observer } from 'mobx-react'
import core from 'osu-core-singleton'
import * as React from 'react'
import { button, div } from 'react-dom-factories'
el = React.createElement
uiState = core.dataStore.uiState
export class CommentsSort extends React.PureComponent
render: =>
div className: osu.classWithModifiers('sort', @props.modifiers),
div className: 'sort__items',
div className: 'sort__item sort__item--title', osu.trans('sort._')
@renderButton('new')
@renderButton('old')
@renderButton('top')
renderButton: (sort) =>
el Observer, null, () =>
className = 'sort__item sort__item--button'
className += ' sort__item--active' if sort == (uiState.comments.loadingSort ? uiState.comments.currentSort)
button
className: className
'data-sort': sort
onClick: @setSort
osu.trans("sort.#{sort}")
setSort: (e) =>
$.publish 'comments:sort', sort: e.target.dataset.sort
| 38112 | # Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import { Observer } from 'mobx-react'
import core from 'osu-core-singleton'
import * as React from 'react'
import { button, div } from 'react-dom-factories'
el = React.createElement
uiState = core.dataStore.uiState
export class CommentsSort extends React.PureComponent
render: =>
div className: osu.classWithModifiers('sort', @props.modifiers),
div className: 'sort__items',
div className: 'sort__item sort__item--title', osu.trans('sort._')
@renderButton('new')
@renderButton('old')
@renderButton('top')
renderButton: (sort) =>
el Observer, null, () =>
className = 'sort__item sort__item--button'
className += ' sort__item--active' if sort == (uiState.comments.loadingSort ? uiState.comments.currentSort)
button
className: className
'data-sort': sort
onClick: @setSort
osu.trans("sort.#{sort}")
setSort: (e) =>
$.publish 'comments:sort', sort: e.target.dataset.sort
| true | # Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import { Observer } from 'mobx-react'
import core from 'osu-core-singleton'
import * as React from 'react'
import { button, div } from 'react-dom-factories'
el = React.createElement
uiState = core.dataStore.uiState
export class CommentsSort extends React.PureComponent
render: =>
div className: osu.classWithModifiers('sort', @props.modifiers),
div className: 'sort__items',
div className: 'sort__item sort__item--title', osu.trans('sort._')
@renderButton('new')
@renderButton('old')
@renderButton('top')
renderButton: (sort) =>
el Observer, null, () =>
className = 'sort__item sort__item--button'
className += ' sort__item--active' if sort == (uiState.comments.loadingSort ? uiState.comments.currentSort)
button
className: className
'data-sort': sort
onClick: @setSort
osu.trans("sort.#{sort}")
setSort: (e) =>
$.publish 'comments:sort', sort: e.target.dataset.sort
|
[
{
"context": "(eft) - left\n# r(ight) - right\n#\n# Author:\n# whyjustin\n\n\n# Copyright (c) 2014 Justin Young\n# Permission ",
"end": 406,
"score": 0.999400794506073,
"start": 397,
"tag": "USERNAME",
"value": "whyjustin"
},
{
"context": "t\n#\n# Author:\n# whyjustin\n\n\n# ... | src/2048.coffee | buzzedword/hubot-2048-slack | 0 | # Description:
# A 2048 Game Engine for Hubot
#
# Commands:
# hubot 2048 me - Start a game of 2048
# hubot 2048 <direction> - Move tiles in a <direction>
# hubot 2048 reset - Resets the current game of 2048
# hubot 2048 stop - Stops the current game of 2048
#
# Notes:
# Direction Commands:
# u(p) - up
# d(own) - down
# l(eft) - left
# r(ight) - right
#
# Author:
# whyjustin
# Copyright (c) 2014 Justin Young
# 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.
#
# Some portions of code are copied from atom-2048 and available under the following license
# Copyright (c) 2014 Peng Sun
# 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.
Tile = (position, value) ->
@x = position.x
@y = position.y
@value = value or 2
@previousPosition = null
@mergedFrom = null
return
Grid = (size) ->
@size = size
@cells = []
@build()
return
GameManager = (size, renderer) ->
@size = size
@startTiles = 2
@renderer = renderer
@setup()
return
Tile::savePosition = ->
@previousPosition =
x: @x
y: @y
return
Tile::updatePosition = (position) ->
@x = position.x
@y = position.y
return
Grid::build = ->
x = 0
while x < @size
row = @cells[x] = []
y = 0
while y < @size
row.push null
y++
x++
return
Grid::randomAvailableCell = ->
cells = @availableCells()
return cells[Math.floor(Math.random() * cells.length)] if cells.length
Grid::availableCells = ->
cells = []
@eachCell (x, y, tile) ->
unless tile
cells.push
x: x
y: y
return
return cells
Grid::eachCell = (callback) ->
x = 0
while x < @size
y = 0
while y < @size
callback x, y, @cells[x][y]
y++
x++
return
Grid::cellsAvailable = ->
return !!@availableCells().length
Grid::cellAvailable = (cell) ->
return not @cellOccupied(cell)
Grid::cellOccupied = (cell) ->
return !!@cellContent(cell)
Grid::cellContent = (cell) ->
if @withinBounds(cell)
return @cells[cell.x][cell.y]
else
return null
Grid::insertTile = (tile) ->
@cells[tile.x][tile.y] = tile
return
Grid::removeTile = (tile) ->
@cells[tile.x][tile.y] = null
return
Grid::withinBounds = (position) ->
return position.x >= 0 and position.x < @size and position.y >= 0 and position.y < @size
GameManager::setup = ->
@grid = new Grid(@size)
@score = 0
@over = false
@won = false
@keepPlaying = false
@addStartTiles()
@actuate()
return
GameManager::getRenderer = ->
return @renderer
GameManager::keepPlaying = ->
@keepPlaying = true
return
GameManager::isGameTerminated = ->
if @over or (@won and not @keepPlaying)
true
else
false
GameManager::addStartTiles = ->
i = 0
while i < @startTiles
@addRandomTile()
i++
return
GameManager::addRandomTile = ->
if @grid.cellsAvailable()
value = (if Math.random() < 0.9 then 2 else 4)
tile = new Tile(@grid.randomAvailableCell(), value)
@grid.insertTile tile
return
GameManager::actuate = ->
@renderer.render @grid,
score: @score,
over: @over,
won: @won,
terminated: @isGameTerminated()
return
GameManager::prepareTiles = ->
@grid.eachCell (x, y, tile) ->
if tile
tile.mergedFrom = null
tile.savePosition()
return
return
GameManager::moveTile = (tile, cell) ->
@grid.cells[tile.x][tile.y] = null
@grid.cells[cell.x][cell.y] = tile
tile.updatePosition cell
return
GameManager::move = (direction) ->
self = this
return if @isGameTerminated()
cell = undefined
tile = undefined
vector = @getVector(direction)
traversales = @buildTraversals(vector)
moved = false
@prepareTiles()
traversales.x.forEach (x) ->
traversales.y.forEach (y) ->
cell =
x: x
y: y
tile = self.grid.cellContent(cell)
if tile
positions = self.findFarthestPosition(cell, vector)
next = self.grid.cellContent(positions.next)
if next and next.value is tile.value and not next.mergedFrom
merged = new Tile(positions.next, tile.value * 2)
merged.mergedFrom = [
tile
next
]
self.grid.insertTile merged
self.grid.removeTile tile
tile.updatePosition positions.next
self.score += merged.value
self.won = true if merged.value is 2048
else
self.moveTile tile, positions.farthest
moved = true unless self.positionsEqual(cell, tile)
return
return
if moved
@addRandomTile()
@over = true unless @movesAvailable()
@actuate()
return
GameManager::getVector = (direction) ->
map =
0:
x: 0
y: -1
1:
x: 1
y: 0
2:
x: 0
y: 1
3:
x: -1
y: 0
return map[direction]
GameManager::buildTraversals = (vector) ->
traversales =
x: []
y: []
pos = 0
while pos < @size
traversales.x.push pos
traversales.y.push pos
pos++
traversales.x = traversales.x.reverse() if vector.x is 1
traversales.y = traversales.y.reverse() if vector.y is 1
return traversales
GameManager::findFarthestPosition = (cell, vector) ->
previous = undefined
loop
previous = cell
cell =
x: previous.x + vector.x
y: previous.y + vector.y
break unless @grid.withinBounds(cell) and @grid.cellAvailable(cell)
farthest: previous
next: cell
GameManager::movesAvailable = ->
@grid.cellsAvailable() or @tileMatchesAvailable()
GameManager::tileMatchesAvailable = ->
self = this
tile = undefined
x = 0
while x < @size
y = 0
while y < @size
tile = @grid.cellContent(
x: x
y: y
)
if tile
direction = 0
while direction < 4
vector = self.getVector(direction)
cell =
x: x + vector.x
y: y + vector.y
other = self.grid.cellContent(cell)
return true if other and other.value is tile.value
direction++
y++
x++
return false
GameManager::positionsEqual = (first, second) ->
first.x is second.x and first.y is second.y
Renderer = ->
@msg = undefined
Renderer::setMsg = (msg) ->
@msg = msg
Renderer::renderHorizontalLine = (length) ->
self = this
i = 0
message = '`-'
while i < length
message += '--'
i++
message += '`'
self.msg.send message
Renderer::render = (grid, metadata) ->
self = this;
self.renderHorizontalLine grid.cells.length
grid.cells.forEach (column) ->
message = '`|'
column.forEach (cell) ->
value = if cell then cell.value else ' '
message += value + '|'
message += '`'
self.msg.send message
self.renderHorizontalLine grid.cells.length
self.msg.send "`Score: #{metadata.score}`"
gameManagerKey = 'gameManager'
getUserName = (msg) ->
# Running under hipchat adaptor
if msg.message.user.mention_name?
msg.message.user.mention_name
else
msg.message.user.name
sendHelp = (robot, msg) ->
prefix = robot.alias or robot.name
msg.send "Start Game: #{prefix} 2048 me"
msg.send "Move Tile: #{prefix} 2048 {direction}"
msg.send "Directions: u(p), d(own), l(eft), r(ight)"
msg.send "Reset Game: #{prefix} 2048 reset"
msg.send "Stop Game: #{prefix} 2048 stop"
module.exports = (robot) ->
robot.respond /2048 me/i, (msg) ->
gameManager = robot.brain.get(gameManagerKey)
unless gameManager?
msg.send "#{getUserName(msg)} has started a game of 2048."
hubotRenderer = new Renderer()
hubotRenderer.setMsg msg
gameManager = new GameManager(4, hubotRenderer)
robot.brain.set(gameManagerKey, gameManager)
robot.brain.save()
else
msg.send "2048 game already in progress."
sendHelp robot, msg
robot.respond /2048 help/i, (msg) ->
sendHelp robot, msg
robot.respond /2048 (u(p)?|d(own)?|l(eft)?|r(ight)?)/i, (msg) ->
gameManager = robot.brain.get(gameManagerKey)
unless gameManager?
msg.send "No 2048 game in progress."
sendHelp robot, msg
return
directioon = switch msg.match[1].toLowerCase()
when 'd', 'down' then 1
when 'u', 'up' then 3
when 'l', 'left' then 0
when 'r', 'right' then 2
hubotRenderer = gameManager.getRenderer()
hubotRenderer.setMsg msg
gameManager.move directioon
robot.respond /2048 reset/i, (msg) ->
gameManager = robot.brain.get(gameManagerKey)
unless gameManager?
msg.send "No 2048 game in progress."
sendHelp robot, msg
return
msg.send "#{getUserName(msg)} has started a game of 2048."
gameManager.setup()
robot.respond /2048 stop/i, (msg) ->
robot.brain.set(gameManagerKey, null)
robot.brain.save()
| 223993 | # Description:
# A 2048 Game Engine for Hubot
#
# Commands:
# hubot 2048 me - Start a game of 2048
# hubot 2048 <direction> - Move tiles in a <direction>
# hubot 2048 reset - Resets the current game of 2048
# hubot 2048 stop - Stops the current game of 2048
#
# Notes:
# Direction Commands:
# u(p) - up
# d(own) - down
# l(eft) - left
# r(ight) - right
#
# Author:
# whyjustin
# Copyright (c) 2014 <NAME>
# 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.
#
# Some portions of code are copied from atom-2048 and available under the following license
# Copyright (c) 2014 <NAME>
# 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.
Tile = (position, value) ->
@x = position.x
@y = position.y
@value = value or 2
@previousPosition = null
@mergedFrom = null
return
Grid = (size) ->
@size = size
@cells = []
@build()
return
GameManager = (size, renderer) ->
@size = size
@startTiles = 2
@renderer = renderer
@setup()
return
Tile::savePosition = ->
@previousPosition =
x: @x
y: @y
return
Tile::updatePosition = (position) ->
@x = position.x
@y = position.y
return
Grid::build = ->
x = 0
while x < @size
row = @cells[x] = []
y = 0
while y < @size
row.push null
y++
x++
return
Grid::randomAvailableCell = ->
cells = @availableCells()
return cells[Math.floor(Math.random() * cells.length)] if cells.length
Grid::availableCells = ->
cells = []
@eachCell (x, y, tile) ->
unless tile
cells.push
x: x
y: y
return
return cells
Grid::eachCell = (callback) ->
x = 0
while x < @size
y = 0
while y < @size
callback x, y, @cells[x][y]
y++
x++
return
Grid::cellsAvailable = ->
return !!@availableCells().length
Grid::cellAvailable = (cell) ->
return not @cellOccupied(cell)
Grid::cellOccupied = (cell) ->
return !!@cellContent(cell)
Grid::cellContent = (cell) ->
if @withinBounds(cell)
return @cells[cell.x][cell.y]
else
return null
Grid::insertTile = (tile) ->
@cells[tile.x][tile.y] = tile
return
Grid::removeTile = (tile) ->
@cells[tile.x][tile.y] = null
return
Grid::withinBounds = (position) ->
return position.x >= 0 and position.x < @size and position.y >= 0 and position.y < @size
GameManager::setup = ->
@grid = new Grid(@size)
@score = 0
@over = false
@won = false
@keepPlaying = false
@addStartTiles()
@actuate()
return
GameManager::getRenderer = ->
return @renderer
GameManager::keepPlaying = ->
@keepPlaying = true
return
GameManager::isGameTerminated = ->
if @over or (@won and not @keepPlaying)
true
else
false
GameManager::addStartTiles = ->
i = 0
while i < @startTiles
@addRandomTile()
i++
return
GameManager::addRandomTile = ->
if @grid.cellsAvailable()
value = (if Math.random() < 0.9 then 2 else 4)
tile = new Tile(@grid.randomAvailableCell(), value)
@grid.insertTile tile
return
GameManager::actuate = ->
@renderer.render @grid,
score: @score,
over: @over,
won: @won,
terminated: @isGameTerminated()
return
GameManager::prepareTiles = ->
@grid.eachCell (x, y, tile) ->
if tile
tile.mergedFrom = null
tile.savePosition()
return
return
GameManager::moveTile = (tile, cell) ->
@grid.cells[tile.x][tile.y] = null
@grid.cells[cell.x][cell.y] = tile
tile.updatePosition cell
return
GameManager::move = (direction) ->
self = this
return if @isGameTerminated()
cell = undefined
tile = undefined
vector = @getVector(direction)
traversales = @buildTraversals(vector)
moved = false
@prepareTiles()
traversales.x.forEach (x) ->
traversales.y.forEach (y) ->
cell =
x: x
y: y
tile = self.grid.cellContent(cell)
if tile
positions = self.findFarthestPosition(cell, vector)
next = self.grid.cellContent(positions.next)
if next and next.value is tile.value and not next.mergedFrom
merged = new Tile(positions.next, tile.value * 2)
merged.mergedFrom = [
tile
next
]
self.grid.insertTile merged
self.grid.removeTile tile
tile.updatePosition positions.next
self.score += merged.value
self.won = true if merged.value is 2048
else
self.moveTile tile, positions.farthest
moved = true unless self.positionsEqual(cell, tile)
return
return
if moved
@addRandomTile()
@over = true unless @movesAvailable()
@actuate()
return
GameManager::getVector = (direction) ->
map =
0:
x: 0
y: -1
1:
x: 1
y: 0
2:
x: 0
y: 1
3:
x: -1
y: 0
return map[direction]
GameManager::buildTraversals = (vector) ->
traversales =
x: []
y: []
pos = 0
while pos < @size
traversales.x.push pos
traversales.y.push pos
pos++
traversales.x = traversales.x.reverse() if vector.x is 1
traversales.y = traversales.y.reverse() if vector.y is 1
return traversales
GameManager::findFarthestPosition = (cell, vector) ->
previous = undefined
loop
previous = cell
cell =
x: previous.x + vector.x
y: previous.y + vector.y
break unless @grid.withinBounds(cell) and @grid.cellAvailable(cell)
farthest: previous
next: cell
GameManager::movesAvailable = ->
@grid.cellsAvailable() or @tileMatchesAvailable()
GameManager::tileMatchesAvailable = ->
self = this
tile = undefined
x = 0
while x < @size
y = 0
while y < @size
tile = @grid.cellContent(
x: x
y: y
)
if tile
direction = 0
while direction < 4
vector = self.getVector(direction)
cell =
x: x + vector.x
y: y + vector.y
other = self.grid.cellContent(cell)
return true if other and other.value is tile.value
direction++
y++
x++
return false
GameManager::positionsEqual = (first, second) ->
first.x is second.x and first.y is second.y
Renderer = ->
@msg = undefined
Renderer::setMsg = (msg) ->
@msg = msg
Renderer::renderHorizontalLine = (length) ->
self = this
i = 0
message = '`-'
while i < length
message += '--'
i++
message += '`'
self.msg.send message
Renderer::render = (grid, metadata) ->
self = this;
self.renderHorizontalLine grid.cells.length
grid.cells.forEach (column) ->
message = '`|'
column.forEach (cell) ->
value = if cell then cell.value else ' '
message += value + '|'
message += '`'
self.msg.send message
self.renderHorizontalLine grid.cells.length
self.msg.send "`Score: #{metadata.score}`"
gameManagerKey = 'gameManager'
getUserName = (msg) ->
# Running under hipchat adaptor
if msg.message.user.mention_name?
msg.message.user.mention_name
else
msg.message.user.name
sendHelp = (robot, msg) ->
prefix = robot.alias or robot.name
msg.send "Start Game: #{prefix} 2048 me"
msg.send "Move Tile: #{prefix} 2048 {direction}"
msg.send "Directions: u(p), d(own), l(eft), r(ight)"
msg.send "Reset Game: #{prefix} 2048 reset"
msg.send "Stop Game: #{prefix} 2048 stop"
module.exports = (robot) ->
robot.respond /2048 me/i, (msg) ->
gameManager = robot.brain.get(gameManagerKey)
unless gameManager?
msg.send "#{getUserName(msg)} has started a game of 2048."
hubotRenderer = new Renderer()
hubotRenderer.setMsg msg
gameManager = new GameManager(4, hubotRenderer)
robot.brain.set(gameManagerKey, gameManager)
robot.brain.save()
else
msg.send "2048 game already in progress."
sendHelp robot, msg
robot.respond /2048 help/i, (msg) ->
sendHelp robot, msg
robot.respond /2048 (u(p)?|d(own)?|l(eft)?|r(ight)?)/i, (msg) ->
gameManager = robot.brain.get(gameManagerKey)
unless gameManager?
msg.send "No 2048 game in progress."
sendHelp robot, msg
return
directioon = switch msg.match[1].toLowerCase()
when 'd', 'down' then 1
when 'u', 'up' then 3
when 'l', 'left' then 0
when 'r', 'right' then 2
hubotRenderer = gameManager.getRenderer()
hubotRenderer.setMsg msg
gameManager.move directioon
robot.respond /2048 reset/i, (msg) ->
gameManager = robot.brain.get(gameManagerKey)
unless gameManager?
msg.send "No 2048 game in progress."
sendHelp robot, msg
return
msg.send "#{getUserName(msg)} has started a game of 2048."
gameManager.setup()
robot.respond /2048 stop/i, (msg) ->
robot.brain.set(gameManagerKey, null)
robot.brain.save()
| true | # Description:
# A 2048 Game Engine for Hubot
#
# Commands:
# hubot 2048 me - Start a game of 2048
# hubot 2048 <direction> - Move tiles in a <direction>
# hubot 2048 reset - Resets the current game of 2048
# hubot 2048 stop - Stops the current game of 2048
#
# Notes:
# Direction Commands:
# u(p) - up
# d(own) - down
# l(eft) - left
# r(ight) - right
#
# Author:
# whyjustin
# Copyright (c) 2014 PI:NAME:<NAME>END_PI
# 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.
#
# Some portions of code are copied from atom-2048 and available under the following license
# Copyright (c) 2014 PI:NAME:<NAME>END_PI
# 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.
Tile = (position, value) ->
@x = position.x
@y = position.y
@value = value or 2
@previousPosition = null
@mergedFrom = null
return
Grid = (size) ->
@size = size
@cells = []
@build()
return
GameManager = (size, renderer) ->
@size = size
@startTiles = 2
@renderer = renderer
@setup()
return
Tile::savePosition = ->
@previousPosition =
x: @x
y: @y
return
Tile::updatePosition = (position) ->
@x = position.x
@y = position.y
return
Grid::build = ->
x = 0
while x < @size
row = @cells[x] = []
y = 0
while y < @size
row.push null
y++
x++
return
Grid::randomAvailableCell = ->
cells = @availableCells()
return cells[Math.floor(Math.random() * cells.length)] if cells.length
Grid::availableCells = ->
cells = []
@eachCell (x, y, tile) ->
unless tile
cells.push
x: x
y: y
return
return cells
Grid::eachCell = (callback) ->
x = 0
while x < @size
y = 0
while y < @size
callback x, y, @cells[x][y]
y++
x++
return
Grid::cellsAvailable = ->
return !!@availableCells().length
Grid::cellAvailable = (cell) ->
return not @cellOccupied(cell)
Grid::cellOccupied = (cell) ->
return !!@cellContent(cell)
Grid::cellContent = (cell) ->
if @withinBounds(cell)
return @cells[cell.x][cell.y]
else
return null
Grid::insertTile = (tile) ->
@cells[tile.x][tile.y] = tile
return
Grid::removeTile = (tile) ->
@cells[tile.x][tile.y] = null
return
Grid::withinBounds = (position) ->
return position.x >= 0 and position.x < @size and position.y >= 0 and position.y < @size
GameManager::setup = ->
@grid = new Grid(@size)
@score = 0
@over = false
@won = false
@keepPlaying = false
@addStartTiles()
@actuate()
return
GameManager::getRenderer = ->
return @renderer
GameManager::keepPlaying = ->
@keepPlaying = true
return
GameManager::isGameTerminated = ->
if @over or (@won and not @keepPlaying)
true
else
false
GameManager::addStartTiles = ->
i = 0
while i < @startTiles
@addRandomTile()
i++
return
GameManager::addRandomTile = ->
if @grid.cellsAvailable()
value = (if Math.random() < 0.9 then 2 else 4)
tile = new Tile(@grid.randomAvailableCell(), value)
@grid.insertTile tile
return
GameManager::actuate = ->
@renderer.render @grid,
score: @score,
over: @over,
won: @won,
terminated: @isGameTerminated()
return
GameManager::prepareTiles = ->
@grid.eachCell (x, y, tile) ->
if tile
tile.mergedFrom = null
tile.savePosition()
return
return
GameManager::moveTile = (tile, cell) ->
@grid.cells[tile.x][tile.y] = null
@grid.cells[cell.x][cell.y] = tile
tile.updatePosition cell
return
GameManager::move = (direction) ->
self = this
return if @isGameTerminated()
cell = undefined
tile = undefined
vector = @getVector(direction)
traversales = @buildTraversals(vector)
moved = false
@prepareTiles()
traversales.x.forEach (x) ->
traversales.y.forEach (y) ->
cell =
x: x
y: y
tile = self.grid.cellContent(cell)
if tile
positions = self.findFarthestPosition(cell, vector)
next = self.grid.cellContent(positions.next)
if next and next.value is tile.value and not next.mergedFrom
merged = new Tile(positions.next, tile.value * 2)
merged.mergedFrom = [
tile
next
]
self.grid.insertTile merged
self.grid.removeTile tile
tile.updatePosition positions.next
self.score += merged.value
self.won = true if merged.value is 2048
else
self.moveTile tile, positions.farthest
moved = true unless self.positionsEqual(cell, tile)
return
return
if moved
@addRandomTile()
@over = true unless @movesAvailable()
@actuate()
return
GameManager::getVector = (direction) ->
map =
0:
x: 0
y: -1
1:
x: 1
y: 0
2:
x: 0
y: 1
3:
x: -1
y: 0
return map[direction]
GameManager::buildTraversals = (vector) ->
traversales =
x: []
y: []
pos = 0
while pos < @size
traversales.x.push pos
traversales.y.push pos
pos++
traversales.x = traversales.x.reverse() if vector.x is 1
traversales.y = traversales.y.reverse() if vector.y is 1
return traversales
GameManager::findFarthestPosition = (cell, vector) ->
previous = undefined
loop
previous = cell
cell =
x: previous.x + vector.x
y: previous.y + vector.y
break unless @grid.withinBounds(cell) and @grid.cellAvailable(cell)
farthest: previous
next: cell
GameManager::movesAvailable = ->
@grid.cellsAvailable() or @tileMatchesAvailable()
GameManager::tileMatchesAvailable = ->
self = this
tile = undefined
x = 0
while x < @size
y = 0
while y < @size
tile = @grid.cellContent(
x: x
y: y
)
if tile
direction = 0
while direction < 4
vector = self.getVector(direction)
cell =
x: x + vector.x
y: y + vector.y
other = self.grid.cellContent(cell)
return true if other and other.value is tile.value
direction++
y++
x++
return false
GameManager::positionsEqual = (first, second) ->
first.x is second.x and first.y is second.y
Renderer = ->
@msg = undefined
Renderer::setMsg = (msg) ->
@msg = msg
Renderer::renderHorizontalLine = (length) ->
self = this
i = 0
message = '`-'
while i < length
message += '--'
i++
message += '`'
self.msg.send message
Renderer::render = (grid, metadata) ->
self = this;
self.renderHorizontalLine grid.cells.length
grid.cells.forEach (column) ->
message = '`|'
column.forEach (cell) ->
value = if cell then cell.value else ' '
message += value + '|'
message += '`'
self.msg.send message
self.renderHorizontalLine grid.cells.length
self.msg.send "`Score: #{metadata.score}`"
gameManagerKey = 'gameManager'
getUserName = (msg) ->
# Running under hipchat adaptor
if msg.message.user.mention_name?
msg.message.user.mention_name
else
msg.message.user.name
sendHelp = (robot, msg) ->
prefix = robot.alias or robot.name
msg.send "Start Game: #{prefix} 2048 me"
msg.send "Move Tile: #{prefix} 2048 {direction}"
msg.send "Directions: u(p), d(own), l(eft), r(ight)"
msg.send "Reset Game: #{prefix} 2048 reset"
msg.send "Stop Game: #{prefix} 2048 stop"
module.exports = (robot) ->
robot.respond /2048 me/i, (msg) ->
gameManager = robot.brain.get(gameManagerKey)
unless gameManager?
msg.send "#{getUserName(msg)} has started a game of 2048."
hubotRenderer = new Renderer()
hubotRenderer.setMsg msg
gameManager = new GameManager(4, hubotRenderer)
robot.brain.set(gameManagerKey, gameManager)
robot.brain.save()
else
msg.send "2048 game already in progress."
sendHelp robot, msg
robot.respond /2048 help/i, (msg) ->
sendHelp robot, msg
robot.respond /2048 (u(p)?|d(own)?|l(eft)?|r(ight)?)/i, (msg) ->
gameManager = robot.brain.get(gameManagerKey)
unless gameManager?
msg.send "No 2048 game in progress."
sendHelp robot, msg
return
directioon = switch msg.match[1].toLowerCase()
when 'd', 'down' then 1
when 'u', 'up' then 3
when 'l', 'left' then 0
when 'r', 'right' then 2
hubotRenderer = gameManager.getRenderer()
hubotRenderer.setMsg msg
gameManager.move directioon
robot.respond /2048 reset/i, (msg) ->
gameManager = robot.brain.get(gameManagerKey)
unless gameManager?
msg.send "No 2048 game in progress."
sendHelp robot, msg
return
msg.send "#{getUserName(msg)} has started a game of 2048."
gameManager.setup()
robot.respond /2048 stop/i, (msg) ->
robot.brain.set(gameManagerKey, null)
robot.brain.save()
|
[
{
"context": "# Automatically creates project files\n#\n# Author: Anshul Kharbanda\n# Created: 10 - 20 - 2017\n\n# Describe Gitignore\nd",
"end": 89,
"score": 0.9998742341995239,
"start": 73,
"tag": "NAME",
"value": "Anshul Kharbanda"
}
] | spec/license-spec.coffee | andydevs/auto-create-files | 5 | # Auto Create Files
#
# Automatically creates project files
#
# Author: Anshul Kharbanda
# Created: 10 - 20 - 2017
# Describe Gitignore
describe 'License', ->
# Variables
activatedPromise = null
workspaceView = null
# Do before each
beforeEach ->
activatedPromise = atom.packages.activatePackage 'auto-create-files'
workspaceView = atom.views.getView atom.workspace
jasmine.attachToDOM workspaceView
# Describe create command
describe 'auto-create-files:license', ->
it 'Shows the selector panel', ->
# Dispatch create command
atom.commands.dispatch workspaceView, 'auto-create-files:license'
waitsForPromise -> activatedPromise
# Run tests
panels = atom.workspace.getModalPanels()
expect(panels.length).toBeGreaterThan 0
selectorView = panels[0].getItem()
expect(selectorView.classList.contains 'select-list').toBeTruthy()
expect(selectorView.classList.contains 'auto-create-files').toBeTruthy()
# When selector view is open
describe 'When selector view is open', ->
# Describe cancel command
describe 'core:cancel', ->
it 'Closes the selecor panel', (done) ->
# Dispatch create command
atom.commands.dispatch workspaceView, 'auto-create-files:license'
waitsForPromise -> activatedPromise
# Get selector view
panels = atom.workspace.getModalPanels()
selectorView = panels[0].getItem()
# Dispath cancel command
atom.commands.dispatch selectorView, 'core:cancel'
atom.commands.onDidDispatch ->
panels = atom.workspace.getModalPanels()
expect(panels.length).toEqual 0
done()
# Describe confirm command
describe 'core:confirm', ->
it 'Closes the selector panel', (done) ->
# Dispatch create command
atom.commands.dispatch workspaceView, 'auto-create-files:license'
waitsForPromise -> activatedPromise
# Get selector view
panels = atom.workspace.getModalPanels()
selectorView = panels[0].getItem()
# Dispath cancel command
atom.commands.dispatch selectorView, 'core:cancel'
atom.commands.onDidDispatch ->
# Check if selector view is gone
panels = atom.workspace.getModalPanels()
expect(panels.length).toEqual 0
done()
it 'Closes the selector panel', (done) ->
# Dispatch create command
atom.commands.dispatch workspaceView, 'auto-create-files:license'
waitsForPromise -> activatedPromise
# Get selector view
panels = atom.workspace.getModalPanels()
selectorView = panels[0].getItem()
# Dispath cancel command
atom.commands.dispatch selectorView, 'core:cancel'
atom.commands.onDidDispatch ->
# Check if file has been written
filepath = path.join atom.project.path, 'LICENSE'
expect(fs.existsSync filepath).toBeTruthy()
done()
| 11540 | # Auto Create Files
#
# Automatically creates project files
#
# Author: <NAME>
# Created: 10 - 20 - 2017
# Describe Gitignore
describe 'License', ->
# Variables
activatedPromise = null
workspaceView = null
# Do before each
beforeEach ->
activatedPromise = atom.packages.activatePackage 'auto-create-files'
workspaceView = atom.views.getView atom.workspace
jasmine.attachToDOM workspaceView
# Describe create command
describe 'auto-create-files:license', ->
it 'Shows the selector panel', ->
# Dispatch create command
atom.commands.dispatch workspaceView, 'auto-create-files:license'
waitsForPromise -> activatedPromise
# Run tests
panels = atom.workspace.getModalPanels()
expect(panels.length).toBeGreaterThan 0
selectorView = panels[0].getItem()
expect(selectorView.classList.contains 'select-list').toBeTruthy()
expect(selectorView.classList.contains 'auto-create-files').toBeTruthy()
# When selector view is open
describe 'When selector view is open', ->
# Describe cancel command
describe 'core:cancel', ->
it 'Closes the selecor panel', (done) ->
# Dispatch create command
atom.commands.dispatch workspaceView, 'auto-create-files:license'
waitsForPromise -> activatedPromise
# Get selector view
panels = atom.workspace.getModalPanels()
selectorView = panels[0].getItem()
# Dispath cancel command
atom.commands.dispatch selectorView, 'core:cancel'
atom.commands.onDidDispatch ->
panels = atom.workspace.getModalPanels()
expect(panels.length).toEqual 0
done()
# Describe confirm command
describe 'core:confirm', ->
it 'Closes the selector panel', (done) ->
# Dispatch create command
atom.commands.dispatch workspaceView, 'auto-create-files:license'
waitsForPromise -> activatedPromise
# Get selector view
panels = atom.workspace.getModalPanels()
selectorView = panels[0].getItem()
# Dispath cancel command
atom.commands.dispatch selectorView, 'core:cancel'
atom.commands.onDidDispatch ->
# Check if selector view is gone
panels = atom.workspace.getModalPanels()
expect(panels.length).toEqual 0
done()
it 'Closes the selector panel', (done) ->
# Dispatch create command
atom.commands.dispatch workspaceView, 'auto-create-files:license'
waitsForPromise -> activatedPromise
# Get selector view
panels = atom.workspace.getModalPanels()
selectorView = panels[0].getItem()
# Dispath cancel command
atom.commands.dispatch selectorView, 'core:cancel'
atom.commands.onDidDispatch ->
# Check if file has been written
filepath = path.join atom.project.path, 'LICENSE'
expect(fs.existsSync filepath).toBeTruthy()
done()
| true | # Auto Create Files
#
# Automatically creates project files
#
# Author: PI:NAME:<NAME>END_PI
# Created: 10 - 20 - 2017
# Describe Gitignore
describe 'License', ->
# Variables
activatedPromise = null
workspaceView = null
# Do before each
beforeEach ->
activatedPromise = atom.packages.activatePackage 'auto-create-files'
workspaceView = atom.views.getView atom.workspace
jasmine.attachToDOM workspaceView
# Describe create command
describe 'auto-create-files:license', ->
it 'Shows the selector panel', ->
# Dispatch create command
atom.commands.dispatch workspaceView, 'auto-create-files:license'
waitsForPromise -> activatedPromise
# Run tests
panels = atom.workspace.getModalPanels()
expect(panels.length).toBeGreaterThan 0
selectorView = panels[0].getItem()
expect(selectorView.classList.contains 'select-list').toBeTruthy()
expect(selectorView.classList.contains 'auto-create-files').toBeTruthy()
# When selector view is open
describe 'When selector view is open', ->
# Describe cancel command
describe 'core:cancel', ->
it 'Closes the selecor panel', (done) ->
# Dispatch create command
atom.commands.dispatch workspaceView, 'auto-create-files:license'
waitsForPromise -> activatedPromise
# Get selector view
panels = atom.workspace.getModalPanels()
selectorView = panels[0].getItem()
# Dispath cancel command
atom.commands.dispatch selectorView, 'core:cancel'
atom.commands.onDidDispatch ->
panels = atom.workspace.getModalPanels()
expect(panels.length).toEqual 0
done()
# Describe confirm command
describe 'core:confirm', ->
it 'Closes the selector panel', (done) ->
# Dispatch create command
atom.commands.dispatch workspaceView, 'auto-create-files:license'
waitsForPromise -> activatedPromise
# Get selector view
panels = atom.workspace.getModalPanels()
selectorView = panels[0].getItem()
# Dispath cancel command
atom.commands.dispatch selectorView, 'core:cancel'
atom.commands.onDidDispatch ->
# Check if selector view is gone
panels = atom.workspace.getModalPanels()
expect(panels.length).toEqual 0
done()
it 'Closes the selector panel', (done) ->
# Dispatch create command
atom.commands.dispatch workspaceView, 'auto-create-files:license'
waitsForPromise -> activatedPromise
# Get selector view
panels = atom.workspace.getModalPanels()
selectorView = panels[0].getItem()
# Dispath cancel command
atom.commands.dispatch selectorView, 'core:cancel'
atom.commands.onDidDispatch ->
# Check if file has been written
filepath = path.join atom.project.path, 'LICENSE'
expect(fs.existsSync filepath).toBeTruthy()
done()
|
[
{
"context": "tMonday: '2015-12-07'}\n\t\t\tgroup_users_ = [{name: 'Elin'}, {name: 'Victor'}]\n\t\t\tres = editGroup_edit grou",
"end": 6361,
"score": 0.9980871677398682,
"start": 6357,
"tag": "NAME",
"value": "Elin"
},
{
"context": "2-07'}\n\t\t\tgroup_users_ = [{name: 'Elin'}, {nam... | super-glue/client/src/base/test__lifters.coffee | Cottin/react-coffee-boilerplates | 0 | assert = require 'assert'
moment = require 'moment'
util = require 'util'
{add, always, empty, flip, has, isNil, join, last, length, sort} = require 'ramda' #auto_require:ramda
{cc} = require 'ramda-extras'
{page_, topBarData_, dateData_, profile_, groups_} = lifters = require './lifters'
{editGroup_create, editGroup_edit, joinData_} = lifters
{url__query__date, user_, group_, group_users, group_users_, activities, ui, workouts} = mock = require '../mock/mock'
{ui__currentDate, groups} = mock
{sify} = require 'sometools'
eq = flip assert.strictEqual
deepEq = flip assert.deepEqual
moment.locale('sv')
describe 'lifters:', ->
describe 'user_', ->
it 'should handle empty cases', ->
eq true, isNil(lifters.user_(null))
eq true, isNil(lifters.user_({}))
describe 'group_users_', ->
it 'should handle empty cases', ->
deepEq [], lifters.group_users_(null)
deepEq [], lifters.group_users_({})
it 'shoud add ids correctly and sort by date joined group', ->
data = {1: {created: 12345}, 2: {created: 12344}}
res = lifters.group_users_(data)
eq '2', res[0].id
eq '1', res[1].id
describe 'weeks_', ->
it 'should handle loading cases', ->
eq 'Laddar...', lifters.weeks_(null, group_users, group_users_, activities, ui.mondays, workouts, ui__currentDate)[0].text
eq 'Laddar...', lifters.weeks_(group_, null, group_users_, activities, ui.mondays, workouts, ui__currentDate)[0].text
it 'should handle empty cases', ->
# eq 'Laddar...', lifters.weeks_(group_, group_users, null, activities, ui.mondays, workouts, ui__currentDate)[0].text
# eq 'Laddar...', lifters.weeks_(group_, group_users, group_users_, null, ui.mondays, workouts, ui__currentDate)[0].text
# eq 'Laddar...', lifters.weeks_(group_, group_users, group_users_, activities, null, workouts, ui__currentDate)[0].text
res = lifters.weeks_(group_, group_users, group_users_, activities, ui.mondays, workouts, null)
eq 'Laddar...', res[0].text
it 'empty workouts', ->
res = lifters.weeks_(group_, group_users, group_users_, activities, ui.mondays, null, ui__currentDate)
eq 5, res[1].days[0].workouts.length # filled with null's
eq null, res[0].days[2].workouts[1]
it 'should start on last monday', ->
res = lifters.weeks_(group_, group_users, group_users_, activities, ui.mondays, workouts, '2016-01-20')
eq 'Må', res[0].days[6].text
res = lifters.weeks_(group_, group_users, group_users_, activities, ui.mondays, workouts, ui__currentDate)
it 'text', -> eq 'Vecka 24', res[0].text
it 'days always 7', -> eq 7, length(res[1].days)
it 'Sö, Lö, Fr', -> eq 'Sö', res[1].days[0].text
it 'dateText', -> eq '21 jun', res[1].days[0].dateText
it 'day.key = YYYY-MM-DD', -> eq '2015-06-21', res[1].days[0].key
it 'workouts always same number as users', ->
eq 5, res[1].days[0].workouts.length
it 'workouts ordered correctly', ->
eq 4, res[0].days[6].workouts[3].activity.id
eq 1, res[0].days[6].workouts[4].activity.id
it 'dont show weeks earlier than startMonday', ->
earlyMondays = ['2015-01-05', '2015-01-12', '2015-01-19']
res = lifters.weeks_(group_, group_users, group_users_, activities, earlyMondays, workouts, ui__currentDate)
deepEq [], res
describe 'dateData_', ->
it 'should handle empty cases', ->
eq null, dateData_(null, user_, workouts, activities)
eq null, dateData_(url__query__date, null, workouts, activities)
eq null, dateData_(url__query__date, user_, null, activities)
eq null, dateData_(url__query__date, user_, workouts, null)
res = dateData_(url__query__date, user_, workouts, activities)
it 'text', -> eq 'Fredag 5 juni', res.text
it 'activity selected', -> eq 1, res.activities[2].selectedColor
it 'date', -> eq '2015-06-05', res.date
it 'userId', -> eq 3, res.userId
describe 'topBarData_', ->
currentDate = '2015-06-18'
it 'should handle empty cases', ->
eq null, topBarData_(null, workouts, group_, currentDate)
eq null, topBarData_(group_users_, null, group_, currentDate)
eq null, topBarData_(group_users_, workouts, null, currentDate)
eq null, topBarData_(group_users_, workouts, group_, null)
res = topBarData_(group_users_, workouts, group_, currentDate, user_)
it 'ordered by join date', -> eq 1, res[4].user.id
it 'average is correct from start monday', ->
eq '1.3', res[4].average
it "average when date before startMonday should behave
as if date was first sunday of groups first week", ->
res = topBarData_(group_users_, workouts, group_, '2013-01-01', user_)
eq '4.0', res[4].average
it 'average when user with workouts prior to startMonday', ->
res = topBarData_(group_users_, workouts, group_, '2013-01-01', user_)
eq '2.0', res[3].average
describe 'groups_', ->
it 'should handle empty cases', ->
eq null, groups_(null)
res = groups_(groups)
it 'correct order', -> eq '2', res[0].id
describe 'profile_', ->
it 'should handle empty case', ->
eq null, profile_(groups_, null)
it 'no groups', ->
res = profile_(null, user_)
eq 'Aktiv sedan maj 2015', res.user.activeSince
eq 0, length(res.groups)
currentDate = '2015-06-27'
res = profile_(mock.groups_, mock.user_, currentDate)
it 'activeSince', ->
eq 'Aktiv sedan maj 2015', res.user.activeSince
it 'groups text', ->
eq '3 medlemmar, startade 1 jun (3 veckor sen)', res.groups[0].text
it 'groups text not yet started', ->
res = profile_(mock.groups_, mock.user_, '2015-02-27')
eq '3 medlemmar, startar om 13 veckor den 1 jun', res.groups[0].text
describe 'editGroup_create', ->
it 'empty case', ->
eq null, editGroup_create(null)
user = {id: 1}
it 'happy case', ->
res = editGroup_create {name: 'abc', startMonday: '2015-12-07'}, user
eq 'abc', res.group.name
eq '2015-12-07', res.group.startMonday
eq true, res.validation.isMonday
it 'invalid monday', ->
res = editGroup_create {startMonday: '2015-12-08'}, user
eq false, res.validation.isMonday
it 'isValid', ->
res = editGroup_create {name: '', startMonday: ''}, user
eq false, res.validation.isValid
it 'isValid happy', ->
res = editGroup_create {name: 'abc', startMonday: '2015-12-07'}, user
eq true, res.validation.isValid
describe 'editGroup_edit', ->
it 'has members', ->
group_ = {name: 'abc', startMonday: '2015-12-07'}
group_users_ = [{name: 'Elin'}, {name: 'Victor'}]
res = editGroup_edit group_, group_users_
deepEq group_users_, res.members
describe 'joinData_', ->
it 'empty case', ->
eq true, isNil(joinData_(null, {}))
it 'happy case', ->
res = joinData_ {name: 'a'}, {name: 'Elin'}
deepEq {name: 'a'}, res.group
deepEq {name: 'Elin'}, res.user
it 'no authenticated user', ->
res = joinData_ {name: 'a'}, null
deepEq {name: 'a'}, res.group
deepEq null, res.user
| 214939 | assert = require 'assert'
moment = require 'moment'
util = require 'util'
{add, always, empty, flip, has, isNil, join, last, length, sort} = require 'ramda' #auto_require:ramda
{cc} = require 'ramda-extras'
{page_, topBarData_, dateData_, profile_, groups_} = lifters = require './lifters'
{editGroup_create, editGroup_edit, joinData_} = lifters
{url__query__date, user_, group_, group_users, group_users_, activities, ui, workouts} = mock = require '../mock/mock'
{ui__currentDate, groups} = mock
{sify} = require 'sometools'
eq = flip assert.strictEqual
deepEq = flip assert.deepEqual
moment.locale('sv')
describe 'lifters:', ->
describe 'user_', ->
it 'should handle empty cases', ->
eq true, isNil(lifters.user_(null))
eq true, isNil(lifters.user_({}))
describe 'group_users_', ->
it 'should handle empty cases', ->
deepEq [], lifters.group_users_(null)
deepEq [], lifters.group_users_({})
it 'shoud add ids correctly and sort by date joined group', ->
data = {1: {created: 12345}, 2: {created: 12344}}
res = lifters.group_users_(data)
eq '2', res[0].id
eq '1', res[1].id
describe 'weeks_', ->
it 'should handle loading cases', ->
eq 'Laddar...', lifters.weeks_(null, group_users, group_users_, activities, ui.mondays, workouts, ui__currentDate)[0].text
eq 'Laddar...', lifters.weeks_(group_, null, group_users_, activities, ui.mondays, workouts, ui__currentDate)[0].text
it 'should handle empty cases', ->
# eq 'Laddar...', lifters.weeks_(group_, group_users, null, activities, ui.mondays, workouts, ui__currentDate)[0].text
# eq 'Laddar...', lifters.weeks_(group_, group_users, group_users_, null, ui.mondays, workouts, ui__currentDate)[0].text
# eq 'Laddar...', lifters.weeks_(group_, group_users, group_users_, activities, null, workouts, ui__currentDate)[0].text
res = lifters.weeks_(group_, group_users, group_users_, activities, ui.mondays, workouts, null)
eq 'Laddar...', res[0].text
it 'empty workouts', ->
res = lifters.weeks_(group_, group_users, group_users_, activities, ui.mondays, null, ui__currentDate)
eq 5, res[1].days[0].workouts.length # filled with null's
eq null, res[0].days[2].workouts[1]
it 'should start on last monday', ->
res = lifters.weeks_(group_, group_users, group_users_, activities, ui.mondays, workouts, '2016-01-20')
eq 'Må', res[0].days[6].text
res = lifters.weeks_(group_, group_users, group_users_, activities, ui.mondays, workouts, ui__currentDate)
it 'text', -> eq 'Vecka 24', res[0].text
it 'days always 7', -> eq 7, length(res[1].days)
it 'Sö, Lö, Fr', -> eq 'Sö', res[1].days[0].text
it 'dateText', -> eq '21 jun', res[1].days[0].dateText
it 'day.key = YYYY-MM-DD', -> eq '2015-06-21', res[1].days[0].key
it 'workouts always same number as users', ->
eq 5, res[1].days[0].workouts.length
it 'workouts ordered correctly', ->
eq 4, res[0].days[6].workouts[3].activity.id
eq 1, res[0].days[6].workouts[4].activity.id
it 'dont show weeks earlier than startMonday', ->
earlyMondays = ['2015-01-05', '2015-01-12', '2015-01-19']
res = lifters.weeks_(group_, group_users, group_users_, activities, earlyMondays, workouts, ui__currentDate)
deepEq [], res
describe 'dateData_', ->
it 'should handle empty cases', ->
eq null, dateData_(null, user_, workouts, activities)
eq null, dateData_(url__query__date, null, workouts, activities)
eq null, dateData_(url__query__date, user_, null, activities)
eq null, dateData_(url__query__date, user_, workouts, null)
res = dateData_(url__query__date, user_, workouts, activities)
it 'text', -> eq 'Fredag 5 juni', res.text
it 'activity selected', -> eq 1, res.activities[2].selectedColor
it 'date', -> eq '2015-06-05', res.date
it 'userId', -> eq 3, res.userId
describe 'topBarData_', ->
currentDate = '2015-06-18'
it 'should handle empty cases', ->
eq null, topBarData_(null, workouts, group_, currentDate)
eq null, topBarData_(group_users_, null, group_, currentDate)
eq null, topBarData_(group_users_, workouts, null, currentDate)
eq null, topBarData_(group_users_, workouts, group_, null)
res = topBarData_(group_users_, workouts, group_, currentDate, user_)
it 'ordered by join date', -> eq 1, res[4].user.id
it 'average is correct from start monday', ->
eq '1.3', res[4].average
it "average when date before startMonday should behave
as if date was first sunday of groups first week", ->
res = topBarData_(group_users_, workouts, group_, '2013-01-01', user_)
eq '4.0', res[4].average
it 'average when user with workouts prior to startMonday', ->
res = topBarData_(group_users_, workouts, group_, '2013-01-01', user_)
eq '2.0', res[3].average
describe 'groups_', ->
it 'should handle empty cases', ->
eq null, groups_(null)
res = groups_(groups)
it 'correct order', -> eq '2', res[0].id
describe 'profile_', ->
it 'should handle empty case', ->
eq null, profile_(groups_, null)
it 'no groups', ->
res = profile_(null, user_)
eq 'Aktiv sedan maj 2015', res.user.activeSince
eq 0, length(res.groups)
currentDate = '2015-06-27'
res = profile_(mock.groups_, mock.user_, currentDate)
it 'activeSince', ->
eq 'Aktiv sedan maj 2015', res.user.activeSince
it 'groups text', ->
eq '3 medlemmar, startade 1 jun (3 veckor sen)', res.groups[0].text
it 'groups text not yet started', ->
res = profile_(mock.groups_, mock.user_, '2015-02-27')
eq '3 medlemmar, startar om 13 veckor den 1 jun', res.groups[0].text
describe 'editGroup_create', ->
it 'empty case', ->
eq null, editGroup_create(null)
user = {id: 1}
it 'happy case', ->
res = editGroup_create {name: 'abc', startMonday: '2015-12-07'}, user
eq 'abc', res.group.name
eq '2015-12-07', res.group.startMonday
eq true, res.validation.isMonday
it 'invalid monday', ->
res = editGroup_create {startMonday: '2015-12-08'}, user
eq false, res.validation.isMonday
it 'isValid', ->
res = editGroup_create {name: '', startMonday: ''}, user
eq false, res.validation.isValid
it 'isValid happy', ->
res = editGroup_create {name: 'abc', startMonday: '2015-12-07'}, user
eq true, res.validation.isValid
describe 'editGroup_edit', ->
it 'has members', ->
group_ = {name: 'abc', startMonday: '2015-12-07'}
group_users_ = [{name: '<NAME>'}, {name: '<NAME>'}]
res = editGroup_edit group_, group_users_
deepEq group_users_, res.members
describe 'joinData_', ->
it 'empty case', ->
eq true, isNil(joinData_(null, {}))
it 'happy case', ->
res = joinData_ {name: 'a'}, {name: '<NAME>'}
deepEq {name: 'a'}, res.group
deepEq {name: '<NAME>'}, res.user
it 'no authenticated user', ->
res = joinData_ {name: 'a'}, null
deepEq {name: 'a'}, res.group
deepEq null, res.user
| true | assert = require 'assert'
moment = require 'moment'
util = require 'util'
{add, always, empty, flip, has, isNil, join, last, length, sort} = require 'ramda' #auto_require:ramda
{cc} = require 'ramda-extras'
{page_, topBarData_, dateData_, profile_, groups_} = lifters = require './lifters'
{editGroup_create, editGroup_edit, joinData_} = lifters
{url__query__date, user_, group_, group_users, group_users_, activities, ui, workouts} = mock = require '../mock/mock'
{ui__currentDate, groups} = mock
{sify} = require 'sometools'
eq = flip assert.strictEqual
deepEq = flip assert.deepEqual
moment.locale('sv')
describe 'lifters:', ->
describe 'user_', ->
it 'should handle empty cases', ->
eq true, isNil(lifters.user_(null))
eq true, isNil(lifters.user_({}))
describe 'group_users_', ->
it 'should handle empty cases', ->
deepEq [], lifters.group_users_(null)
deepEq [], lifters.group_users_({})
it 'shoud add ids correctly and sort by date joined group', ->
data = {1: {created: 12345}, 2: {created: 12344}}
res = lifters.group_users_(data)
eq '2', res[0].id
eq '1', res[1].id
describe 'weeks_', ->
it 'should handle loading cases', ->
eq 'Laddar...', lifters.weeks_(null, group_users, group_users_, activities, ui.mondays, workouts, ui__currentDate)[0].text
eq 'Laddar...', lifters.weeks_(group_, null, group_users_, activities, ui.mondays, workouts, ui__currentDate)[0].text
it 'should handle empty cases', ->
# eq 'Laddar...', lifters.weeks_(group_, group_users, null, activities, ui.mondays, workouts, ui__currentDate)[0].text
# eq 'Laddar...', lifters.weeks_(group_, group_users, group_users_, null, ui.mondays, workouts, ui__currentDate)[0].text
# eq 'Laddar...', lifters.weeks_(group_, group_users, group_users_, activities, null, workouts, ui__currentDate)[0].text
res = lifters.weeks_(group_, group_users, group_users_, activities, ui.mondays, workouts, null)
eq 'Laddar...', res[0].text
it 'empty workouts', ->
res = lifters.weeks_(group_, group_users, group_users_, activities, ui.mondays, null, ui__currentDate)
eq 5, res[1].days[0].workouts.length # filled with null's
eq null, res[0].days[2].workouts[1]
it 'should start on last monday', ->
res = lifters.weeks_(group_, group_users, group_users_, activities, ui.mondays, workouts, '2016-01-20')
eq 'Må', res[0].days[6].text
res = lifters.weeks_(group_, group_users, group_users_, activities, ui.mondays, workouts, ui__currentDate)
it 'text', -> eq 'Vecka 24', res[0].text
it 'days always 7', -> eq 7, length(res[1].days)
it 'Sö, Lö, Fr', -> eq 'Sö', res[1].days[0].text
it 'dateText', -> eq '21 jun', res[1].days[0].dateText
it 'day.key = YYYY-MM-DD', -> eq '2015-06-21', res[1].days[0].key
it 'workouts always same number as users', ->
eq 5, res[1].days[0].workouts.length
it 'workouts ordered correctly', ->
eq 4, res[0].days[6].workouts[3].activity.id
eq 1, res[0].days[6].workouts[4].activity.id
it 'dont show weeks earlier than startMonday', ->
earlyMondays = ['2015-01-05', '2015-01-12', '2015-01-19']
res = lifters.weeks_(group_, group_users, group_users_, activities, earlyMondays, workouts, ui__currentDate)
deepEq [], res
describe 'dateData_', ->
it 'should handle empty cases', ->
eq null, dateData_(null, user_, workouts, activities)
eq null, dateData_(url__query__date, null, workouts, activities)
eq null, dateData_(url__query__date, user_, null, activities)
eq null, dateData_(url__query__date, user_, workouts, null)
res = dateData_(url__query__date, user_, workouts, activities)
it 'text', -> eq 'Fredag 5 juni', res.text
it 'activity selected', -> eq 1, res.activities[2].selectedColor
it 'date', -> eq '2015-06-05', res.date
it 'userId', -> eq 3, res.userId
describe 'topBarData_', ->
currentDate = '2015-06-18'
it 'should handle empty cases', ->
eq null, topBarData_(null, workouts, group_, currentDate)
eq null, topBarData_(group_users_, null, group_, currentDate)
eq null, topBarData_(group_users_, workouts, null, currentDate)
eq null, topBarData_(group_users_, workouts, group_, null)
res = topBarData_(group_users_, workouts, group_, currentDate, user_)
it 'ordered by join date', -> eq 1, res[4].user.id
it 'average is correct from start monday', ->
eq '1.3', res[4].average
it "average when date before startMonday should behave
as if date was first sunday of groups first week", ->
res = topBarData_(group_users_, workouts, group_, '2013-01-01', user_)
eq '4.0', res[4].average
it 'average when user with workouts prior to startMonday', ->
res = topBarData_(group_users_, workouts, group_, '2013-01-01', user_)
eq '2.0', res[3].average
describe 'groups_', ->
it 'should handle empty cases', ->
eq null, groups_(null)
res = groups_(groups)
it 'correct order', -> eq '2', res[0].id
describe 'profile_', ->
it 'should handle empty case', ->
eq null, profile_(groups_, null)
it 'no groups', ->
res = profile_(null, user_)
eq 'Aktiv sedan maj 2015', res.user.activeSince
eq 0, length(res.groups)
currentDate = '2015-06-27'
res = profile_(mock.groups_, mock.user_, currentDate)
it 'activeSince', ->
eq 'Aktiv sedan maj 2015', res.user.activeSince
it 'groups text', ->
eq '3 medlemmar, startade 1 jun (3 veckor sen)', res.groups[0].text
it 'groups text not yet started', ->
res = profile_(mock.groups_, mock.user_, '2015-02-27')
eq '3 medlemmar, startar om 13 veckor den 1 jun', res.groups[0].text
describe 'editGroup_create', ->
it 'empty case', ->
eq null, editGroup_create(null)
user = {id: 1}
it 'happy case', ->
res = editGroup_create {name: 'abc', startMonday: '2015-12-07'}, user
eq 'abc', res.group.name
eq '2015-12-07', res.group.startMonday
eq true, res.validation.isMonday
it 'invalid monday', ->
res = editGroup_create {startMonday: '2015-12-08'}, user
eq false, res.validation.isMonday
it 'isValid', ->
res = editGroup_create {name: '', startMonday: ''}, user
eq false, res.validation.isValid
it 'isValid happy', ->
res = editGroup_create {name: 'abc', startMonday: '2015-12-07'}, user
eq true, res.validation.isValid
describe 'editGroup_edit', ->
it 'has members', ->
group_ = {name: 'abc', startMonday: '2015-12-07'}
group_users_ = [{name: 'PI:NAME:<NAME>END_PI'}, {name: 'PI:NAME:<NAME>END_PI'}]
res = editGroup_edit group_, group_users_
deepEq group_users_, res.members
describe 'joinData_', ->
it 'empty case', ->
eq true, isNil(joinData_(null, {}))
it 'happy case', ->
res = joinData_ {name: 'a'}, {name: 'PI:NAME:<NAME>END_PI'}
deepEq {name: 'a'}, res.group
deepEq {name: 'PI:NAME:<NAME>END_PI'}, res.user
it 'no authenticated user', ->
res = joinData_ {name: 'a'}, null
deepEq {name: 'a'}, res.group
deepEq null, res.user
|
[
{
"context": "### ^\nBSD 3-Clause License\n\nCopyright (c) 2017, Stephan Jorek\nAll rights reserved.\n\nRedistribution and use in s",
"end": 61,
"score": 0.9998393058776855,
"start": 48,
"tag": "NAME",
"value": "Stephan Jorek"
}
] | src/Runtime.coffee | sjorek/goatee-script.js | 0 | ### ^
BSD 3-Clause License
Copyright (c) 2017, Stephan Jorek
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
Expression = require './Expression'
{
arraySlice,
bindFunction,
isString,
isArray,
isNumber,
isFunction,
isExpression,
parse
} = require './Utility'
###
# Runtime
# -------
#
# Implements several expression-runtime related methods.
#
###
###*
# -------------
# @class Runtime
# @namepace GoateeScript
###
class Runtime
_operations = Expression.operations
###*
# -------------
# @method aliases
# @return {Array}
# @static
###
Runtime.aliases = _aliases = do ->
index = null
() ->
index ? index = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'.split('')
###*
# -------------
# @method generate
# @param {Boolean} [compress=true]
# @return {String}
# @static
###
Runtime.generate = do ->
aliases = []
for alias in _aliases().reverse() when not _operations[alias]?
aliases.push alias
index = aliases.length
return if index is 0
for key, value of _operations when value.name? and not value.alias?
_operations[value.alias = aliases[--index]] = key
if index is 0
break
_operations['()'].code = """
function(){
var a,f;
f=arguments[0],a=2<=arguments.length?aS(arguments,1):[];
return f.apply(this,a);
}
"""
runtime =
global :
name : 'global'
alias : if index is 0 then '_g' else aliases[--index]
code : 'null'
local :
name : 'local'
alias : if index is 0 then '_l' else aliases[--index]
code : 'null'
stack :
name : 'stack'
alias : if index is 0 then 'st' else aliases[--index]
code : '[]'
scope :
name : 'scope'
alias : if index is 0 then 'sc' else aliases[--index]
code : '[]'
evaluate :
name : 'evaluate'
alias : if index is 0 then '_e' else aliases[--index]
code : """
function(c,e,v,_,$) {
var g,r;
if(!(isFunction(e) && e.name)){return e;}
g = _global === null ? _evaluate : false;
if (g) {
_global = c||{};
_local = v||{};
_scope = _||_scope.length = 0||_scope;
_stack = $||_stack.length = 0||_stack;
_evaluate = _execute;
};
r = _execute(c,e);
if (g) {
_global = null;
_evaluate = g;
};
return r;
}
"""
evaluate : Expression.evaluate
execute :
name : 'execute'
alias : if index is 0 then '_x' else aliases[--index]
code : """
function(c,e) {
var r,f;
if(!(isFunction(e) && e.name)){return e;};
_scope.push(c);
_stack.push(e);
try {
r = _process(c,e); /* ?!?!?!?! */
} catch(f) {};
_scope.pop();
_stack.pop();
return r;
}
"""
evaluate : Expression.execute
call :
name : 'call'
alias : if index is 0 then 'ca' else aliases[--index]
code : 'Function.prototype.call'
slice :
name : 'slice'
alias : if index is 0 then 'sl' else aliases[--index]
code : 'Array.prototype.slice'
toString :
name : 'toString'
alias : if index is 0 then 'tS' else aliases[--index]
code : 'Object.prototype.toString'
booleanize :
name : 'booleanize'
alias : if index is 0 then '_b' else aliases[--index]
evaluate : Expression.booleanize
isFunction :
name : 'isFunction'
alias : if index is 0 then 'iF' else aliases[--index]
evaluate : isFunction
bindFunction :
name : 'bindFunction'
alias : if index is 0 then 'bF' else aliases[--index]
code : """
(function(bindFunction) {
return bindFunction ? function() {
return bindFunction.apply(arguments);
} : function() {
var f, c, a;
f = arguments[0];
c = arguments[1];
a = 3 <= arguments.length ? arraySlice(arguments, 2) : [];
return a.length === 0
? function() { return f.call(c); }
: function() { return f.apply(c, a); };
}
})(Function.prototype.bind)
"""
evaluate : bindFunction
isArray :
name : 'isArray'
alias : if index is 0 then 'iA' else aliases[--index]
code : """
(function(isArray) {
return isArray || function(o){return _toString.call(o)==='[object Array]';};
})(Array.isArray)
"""
evaluate : isArray
arraySlice :
name : 'arraySlice'
alias : if index is 0 then 'aS' else aliases[--index]
#code : '[].slice'
evaluate : arraySlice
hasProperty :
name : 'hasProperty'
alias : if index is 0 then 'hP' else aliases[--index]
code : """
(function(hasProperty) {
return function() {
hasProperty.apply(arguments);
};
})({}.hasOwnProperty)
"""
isProperty :
name : 'isProperty'
alias : if index is 0 then 'iP' else aliases[--index]
code : """
function() {
if(_stack.length < 2){return false;}
var p = _stack.length > 1 ? _stack[_stack.length-2] : void(0),
c = _stack.length > 0 ? _stack[_stack.length-1] : void(0);
return p.toString() === '#{_operations['.'].alias}' && p[1] === c;
}
"""
# Number :
# name : 'Number'
# alias : if index is 0 then 'Nu' else aliases[--index]
# code : "Number"
# evaluate : Number
unwrap = /^function\s*\(([^\)]*)\)\s*\{\s*(\S[\s\S]*[;|\}])\s*\}$/
pattern = [
/(\s|\n)+/g , ' '
/_assignment/g , _operations['='].alias
/_reference/g , _operations.reference.alias
/_global/g , runtime.global.alias
/_local/g , runtime.local.alias
/_scope/g , runtime.scope.alias
/_stack/g , runtime.stack.alias
/_evaluate/g , runtime.evaluate.alias
/_execute/g , runtime.execute.alias
/_booleanize/g , runtime.booleanize.alias
/__slice\.call|arraySlice/g , runtime.arraySlice.alias
/_slice/g , runtime.slice.alias
/_call/g , runtime.call.alias
/([^\.])isArray/g , "$1#{runtime.isArray.alias}"
/_toString/g , runtime.toString.alias
/isNumber/g , runtime.global.alias
# /(Nu)mber/g , runtime.Number.alias
/isFunction/g , runtime.isFunction.alias
/bindFunction/g , runtime.bindFunction.alias
/_isProperty/g , runtime.isProperty.alias
/hasProperty/g , runtime.hasProperty.alias
///
([a-zA-Z]+)\.hasOwnProperty\(
///g , "#{runtime.hasProperty.alias}($1,"
/(_l)en/g , if index is 0 then "$1" else aliases[--index]
/obj([^e])|item/g , 'o$1'
/value/g , 'v'
/\(array,start,end\)/g , '()'
/([a-z0-9])\s([^a-z0-9])/gi , '$1$2'
/([^a-z0-9])\s([a-z0-9])/gi , '$1$2'
/([^a-z0-9])\s([^a-z0-9])/gi, '$1$2'
/([a-z0-9])\s([^a-z0-9])/gi , '$1$2'
/([^a-z0-9])\s([a-z0-9])/gi , '$1$2'
/([^a-z0-9])\s([^a-z0-9])/gi, '$1$2'
/return(\S)/gi , 'return $1'
]
clean = (key, value, code) ->
for search, index in pattern by 2
code = code.replace(search, pattern[index+1])
if key.length > 1 and key[key.length-1] is '='
alias = _operations[key.substring(0,key.length-1)].alias
code = code.replace('_op', alias)
code
vars = []
body = []
assemble = (object) ->
for key, value of object when value.name?
code = clean(
key, value,
if value.code? then value.code else value.evaluate.toString()
)
vars.push [
'/* ', key, ' */ ',
value.alias
].join ''
body.push [
'/* ', key, ' */ ',
value.alias, '=', code
].join ''
assemble runtime
assemble _operations
code = "var #{vars.join ',\n'};\n#{body.join ';\n'};"
# remove comments and linebreaks
js = code
.replace( /\/\*(?:.|[\r\n])*?\*\/\s*|/g , '' )
.replace( /\s*[;]\s*[\}]/g , '}' )
.replace( /([,;])[\r\n]/g , '$1')
(compress=on) ->
if compress is on then js else code
module.exports = Runtime
| 12026 | ### ^
BSD 3-Clause License
Copyright (c) 2017, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
Expression = require './Expression'
{
arraySlice,
bindFunction,
isString,
isArray,
isNumber,
isFunction,
isExpression,
parse
} = require './Utility'
###
# Runtime
# -------
#
# Implements several expression-runtime related methods.
#
###
###*
# -------------
# @class Runtime
# @namepace GoateeScript
###
class Runtime
_operations = Expression.operations
###*
# -------------
# @method aliases
# @return {Array}
# @static
###
Runtime.aliases = _aliases = do ->
index = null
() ->
index ? index = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'.split('')
###*
# -------------
# @method generate
# @param {Boolean} [compress=true]
# @return {String}
# @static
###
Runtime.generate = do ->
aliases = []
for alias in _aliases().reverse() when not _operations[alias]?
aliases.push alias
index = aliases.length
return if index is 0
for key, value of _operations when value.name? and not value.alias?
_operations[value.alias = aliases[--index]] = key
if index is 0
break
_operations['()'].code = """
function(){
var a,f;
f=arguments[0],a=2<=arguments.length?aS(arguments,1):[];
return f.apply(this,a);
}
"""
runtime =
global :
name : 'global'
alias : if index is 0 then '_g' else aliases[--index]
code : 'null'
local :
name : 'local'
alias : if index is 0 then '_l' else aliases[--index]
code : 'null'
stack :
name : 'stack'
alias : if index is 0 then 'st' else aliases[--index]
code : '[]'
scope :
name : 'scope'
alias : if index is 0 then 'sc' else aliases[--index]
code : '[]'
evaluate :
name : 'evaluate'
alias : if index is 0 then '_e' else aliases[--index]
code : """
function(c,e,v,_,$) {
var g,r;
if(!(isFunction(e) && e.name)){return e;}
g = _global === null ? _evaluate : false;
if (g) {
_global = c||{};
_local = v||{};
_scope = _||_scope.length = 0||_scope;
_stack = $||_stack.length = 0||_stack;
_evaluate = _execute;
};
r = _execute(c,e);
if (g) {
_global = null;
_evaluate = g;
};
return r;
}
"""
evaluate : Expression.evaluate
execute :
name : 'execute'
alias : if index is 0 then '_x' else aliases[--index]
code : """
function(c,e) {
var r,f;
if(!(isFunction(e) && e.name)){return e;};
_scope.push(c);
_stack.push(e);
try {
r = _process(c,e); /* ?!?!?!?! */
} catch(f) {};
_scope.pop();
_stack.pop();
return r;
}
"""
evaluate : Expression.execute
call :
name : 'call'
alias : if index is 0 then 'ca' else aliases[--index]
code : 'Function.prototype.call'
slice :
name : 'slice'
alias : if index is 0 then 'sl' else aliases[--index]
code : 'Array.prototype.slice'
toString :
name : 'toString'
alias : if index is 0 then 'tS' else aliases[--index]
code : 'Object.prototype.toString'
booleanize :
name : 'booleanize'
alias : if index is 0 then '_b' else aliases[--index]
evaluate : Expression.booleanize
isFunction :
name : 'isFunction'
alias : if index is 0 then 'iF' else aliases[--index]
evaluate : isFunction
bindFunction :
name : 'bindFunction'
alias : if index is 0 then 'bF' else aliases[--index]
code : """
(function(bindFunction) {
return bindFunction ? function() {
return bindFunction.apply(arguments);
} : function() {
var f, c, a;
f = arguments[0];
c = arguments[1];
a = 3 <= arguments.length ? arraySlice(arguments, 2) : [];
return a.length === 0
? function() { return f.call(c); }
: function() { return f.apply(c, a); };
}
})(Function.prototype.bind)
"""
evaluate : bindFunction
isArray :
name : 'isArray'
alias : if index is 0 then 'iA' else aliases[--index]
code : """
(function(isArray) {
return isArray || function(o){return _toString.call(o)==='[object Array]';};
})(Array.isArray)
"""
evaluate : isArray
arraySlice :
name : 'arraySlice'
alias : if index is 0 then 'aS' else aliases[--index]
#code : '[].slice'
evaluate : arraySlice
hasProperty :
name : 'hasProperty'
alias : if index is 0 then 'hP' else aliases[--index]
code : """
(function(hasProperty) {
return function() {
hasProperty.apply(arguments);
};
})({}.hasOwnProperty)
"""
isProperty :
name : 'isProperty'
alias : if index is 0 then 'iP' else aliases[--index]
code : """
function() {
if(_stack.length < 2){return false;}
var p = _stack.length > 1 ? _stack[_stack.length-2] : void(0),
c = _stack.length > 0 ? _stack[_stack.length-1] : void(0);
return p.toString() === '#{_operations['.'].alias}' && p[1] === c;
}
"""
# Number :
# name : 'Number'
# alias : if index is 0 then 'Nu' else aliases[--index]
# code : "Number"
# evaluate : Number
unwrap = /^function\s*\(([^\)]*)\)\s*\{\s*(\S[\s\S]*[;|\}])\s*\}$/
pattern = [
/(\s|\n)+/g , ' '
/_assignment/g , _operations['='].alias
/_reference/g , _operations.reference.alias
/_global/g , runtime.global.alias
/_local/g , runtime.local.alias
/_scope/g , runtime.scope.alias
/_stack/g , runtime.stack.alias
/_evaluate/g , runtime.evaluate.alias
/_execute/g , runtime.execute.alias
/_booleanize/g , runtime.booleanize.alias
/__slice\.call|arraySlice/g , runtime.arraySlice.alias
/_slice/g , runtime.slice.alias
/_call/g , runtime.call.alias
/([^\.])isArray/g , "$1#{runtime.isArray.alias}"
/_toString/g , runtime.toString.alias
/isNumber/g , runtime.global.alias
# /(Nu)mber/g , runtime.Number.alias
/isFunction/g , runtime.isFunction.alias
/bindFunction/g , runtime.bindFunction.alias
/_isProperty/g , runtime.isProperty.alias
/hasProperty/g , runtime.hasProperty.alias
///
([a-zA-Z]+)\.hasOwnProperty\(
///g , "#{runtime.hasProperty.alias}($1,"
/(_l)en/g , if index is 0 then "$1" else aliases[--index]
/obj([^e])|item/g , 'o$1'
/value/g , 'v'
/\(array,start,end\)/g , '()'
/([a-z0-9])\s([^a-z0-9])/gi , '$1$2'
/([^a-z0-9])\s([a-z0-9])/gi , '$1$2'
/([^a-z0-9])\s([^a-z0-9])/gi, '$1$2'
/([a-z0-9])\s([^a-z0-9])/gi , '$1$2'
/([^a-z0-9])\s([a-z0-9])/gi , '$1$2'
/([^a-z0-9])\s([^a-z0-9])/gi, '$1$2'
/return(\S)/gi , 'return $1'
]
clean = (key, value, code) ->
for search, index in pattern by 2
code = code.replace(search, pattern[index+1])
if key.length > 1 and key[key.length-1] is '='
alias = _operations[key.substring(0,key.length-1)].alias
code = code.replace('_op', alias)
code
vars = []
body = []
assemble = (object) ->
for key, value of object when value.name?
code = clean(
key, value,
if value.code? then value.code else value.evaluate.toString()
)
vars.push [
'/* ', key, ' */ ',
value.alias
].join ''
body.push [
'/* ', key, ' */ ',
value.alias, '=', code
].join ''
assemble runtime
assemble _operations
code = "var #{vars.join ',\n'};\n#{body.join ';\n'};"
# remove comments and linebreaks
js = code
.replace( /\/\*(?:.|[\r\n])*?\*\/\s*|/g , '' )
.replace( /\s*[;]\s*[\}]/g , '}' )
.replace( /([,;])[\r\n]/g , '$1')
(compress=on) ->
if compress is on then js else code
module.exports = Runtime
| true | ### ^
BSD 3-Clause License
Copyright (c) 2017, PI:NAME:<NAME>END_PI
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
Expression = require './Expression'
{
arraySlice,
bindFunction,
isString,
isArray,
isNumber,
isFunction,
isExpression,
parse
} = require './Utility'
###
# Runtime
# -------
#
# Implements several expression-runtime related methods.
#
###
###*
# -------------
# @class Runtime
# @namepace GoateeScript
###
class Runtime
_operations = Expression.operations
###*
# -------------
# @method aliases
# @return {Array}
# @static
###
Runtime.aliases = _aliases = do ->
index = null
() ->
index ? index = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'.split('')
###*
# -------------
# @method generate
# @param {Boolean} [compress=true]
# @return {String}
# @static
###
Runtime.generate = do ->
aliases = []
for alias in _aliases().reverse() when not _operations[alias]?
aliases.push alias
index = aliases.length
return if index is 0
for key, value of _operations when value.name? and not value.alias?
_operations[value.alias = aliases[--index]] = key
if index is 0
break
_operations['()'].code = """
function(){
var a,f;
f=arguments[0],a=2<=arguments.length?aS(arguments,1):[];
return f.apply(this,a);
}
"""
runtime =
global :
name : 'global'
alias : if index is 0 then '_g' else aliases[--index]
code : 'null'
local :
name : 'local'
alias : if index is 0 then '_l' else aliases[--index]
code : 'null'
stack :
name : 'stack'
alias : if index is 0 then 'st' else aliases[--index]
code : '[]'
scope :
name : 'scope'
alias : if index is 0 then 'sc' else aliases[--index]
code : '[]'
evaluate :
name : 'evaluate'
alias : if index is 0 then '_e' else aliases[--index]
code : """
function(c,e,v,_,$) {
var g,r;
if(!(isFunction(e) && e.name)){return e;}
g = _global === null ? _evaluate : false;
if (g) {
_global = c||{};
_local = v||{};
_scope = _||_scope.length = 0||_scope;
_stack = $||_stack.length = 0||_stack;
_evaluate = _execute;
};
r = _execute(c,e);
if (g) {
_global = null;
_evaluate = g;
};
return r;
}
"""
evaluate : Expression.evaluate
execute :
name : 'execute'
alias : if index is 0 then '_x' else aliases[--index]
code : """
function(c,e) {
var r,f;
if(!(isFunction(e) && e.name)){return e;};
_scope.push(c);
_stack.push(e);
try {
r = _process(c,e); /* ?!?!?!?! */
} catch(f) {};
_scope.pop();
_stack.pop();
return r;
}
"""
evaluate : Expression.execute
call :
name : 'call'
alias : if index is 0 then 'ca' else aliases[--index]
code : 'Function.prototype.call'
slice :
name : 'slice'
alias : if index is 0 then 'sl' else aliases[--index]
code : 'Array.prototype.slice'
toString :
name : 'toString'
alias : if index is 0 then 'tS' else aliases[--index]
code : 'Object.prototype.toString'
booleanize :
name : 'booleanize'
alias : if index is 0 then '_b' else aliases[--index]
evaluate : Expression.booleanize
isFunction :
name : 'isFunction'
alias : if index is 0 then 'iF' else aliases[--index]
evaluate : isFunction
bindFunction :
name : 'bindFunction'
alias : if index is 0 then 'bF' else aliases[--index]
code : """
(function(bindFunction) {
return bindFunction ? function() {
return bindFunction.apply(arguments);
} : function() {
var f, c, a;
f = arguments[0];
c = arguments[1];
a = 3 <= arguments.length ? arraySlice(arguments, 2) : [];
return a.length === 0
? function() { return f.call(c); }
: function() { return f.apply(c, a); };
}
})(Function.prototype.bind)
"""
evaluate : bindFunction
isArray :
name : 'isArray'
alias : if index is 0 then 'iA' else aliases[--index]
code : """
(function(isArray) {
return isArray || function(o){return _toString.call(o)==='[object Array]';};
})(Array.isArray)
"""
evaluate : isArray
arraySlice :
name : 'arraySlice'
alias : if index is 0 then 'aS' else aliases[--index]
#code : '[].slice'
evaluate : arraySlice
hasProperty :
name : 'hasProperty'
alias : if index is 0 then 'hP' else aliases[--index]
code : """
(function(hasProperty) {
return function() {
hasProperty.apply(arguments);
};
})({}.hasOwnProperty)
"""
isProperty :
name : 'isProperty'
alias : if index is 0 then 'iP' else aliases[--index]
code : """
function() {
if(_stack.length < 2){return false;}
var p = _stack.length > 1 ? _stack[_stack.length-2] : void(0),
c = _stack.length > 0 ? _stack[_stack.length-1] : void(0);
return p.toString() === '#{_operations['.'].alias}' && p[1] === c;
}
"""
# Number :
# name : 'Number'
# alias : if index is 0 then 'Nu' else aliases[--index]
# code : "Number"
# evaluate : Number
unwrap = /^function\s*\(([^\)]*)\)\s*\{\s*(\S[\s\S]*[;|\}])\s*\}$/
pattern = [
/(\s|\n)+/g , ' '
/_assignment/g , _operations['='].alias
/_reference/g , _operations.reference.alias
/_global/g , runtime.global.alias
/_local/g , runtime.local.alias
/_scope/g , runtime.scope.alias
/_stack/g , runtime.stack.alias
/_evaluate/g , runtime.evaluate.alias
/_execute/g , runtime.execute.alias
/_booleanize/g , runtime.booleanize.alias
/__slice\.call|arraySlice/g , runtime.arraySlice.alias
/_slice/g , runtime.slice.alias
/_call/g , runtime.call.alias
/([^\.])isArray/g , "$1#{runtime.isArray.alias}"
/_toString/g , runtime.toString.alias
/isNumber/g , runtime.global.alias
# /(Nu)mber/g , runtime.Number.alias
/isFunction/g , runtime.isFunction.alias
/bindFunction/g , runtime.bindFunction.alias
/_isProperty/g , runtime.isProperty.alias
/hasProperty/g , runtime.hasProperty.alias
///
([a-zA-Z]+)\.hasOwnProperty\(
///g , "#{runtime.hasProperty.alias}($1,"
/(_l)en/g , if index is 0 then "$1" else aliases[--index]
/obj([^e])|item/g , 'o$1'
/value/g , 'v'
/\(array,start,end\)/g , '()'
/([a-z0-9])\s([^a-z0-9])/gi , '$1$2'
/([^a-z0-9])\s([a-z0-9])/gi , '$1$2'
/([^a-z0-9])\s([^a-z0-9])/gi, '$1$2'
/([a-z0-9])\s([^a-z0-9])/gi , '$1$2'
/([^a-z0-9])\s([a-z0-9])/gi , '$1$2'
/([^a-z0-9])\s([^a-z0-9])/gi, '$1$2'
/return(\S)/gi , 'return $1'
]
clean = (key, value, code) ->
for search, index in pattern by 2
code = code.replace(search, pattern[index+1])
if key.length > 1 and key[key.length-1] is '='
alias = _operations[key.substring(0,key.length-1)].alias
code = code.replace('_op', alias)
code
vars = []
body = []
assemble = (object) ->
for key, value of object when value.name?
code = clean(
key, value,
if value.code? then value.code else value.evaluate.toString()
)
vars.push [
'/* ', key, ' */ ',
value.alias
].join ''
body.push [
'/* ', key, ' */ ',
value.alias, '=', code
].join ''
assemble runtime
assemble _operations
code = "var #{vars.join ',\n'};\n#{body.join ';\n'};"
# remove comments and linebreaks
js = code
.replace( /\/\*(?:.|[\r\n])*?\*\/\s*|/g , '' )
.replace( /\s*[;]\s*[\}]/g , '}' )
.replace( /([,;])[\r\n]/g , '$1')
(compress=on) ->
if compress is on then js else code
module.exports = Runtime
|
[
{
"context": "http://kevin.vanzonneveld.net\n # + original by: Waldo Malqui Silva\n # + input by: Steve Hilder\n # + improve",
"end": 198,
"score": 0.9998957514762878,
"start": 180,
"tag": "NAME",
"value": "Waldo Malqui Silva"
},
{
"context": "iginal by: Waldo Malqui Silv... | node_modules/algebrite/runtime/otherCFunctions.coffee | geometor/geometor-explorer | 4 |
# The C library function int isspace(int c) checks
# whether the passed character is white-space.
strcmp = (str1, str2) ->
# http://kevin.vanzonneveld.net
# + original by: Waldo Malqui Silva
# + input by: Steve Hilder
# + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
# + revised by: gorthaur
# * example 1: strcmp( 'waldo', 'owald' )
# * returns 1: 1
# * example 2: strcmp( 'owald', 'waldo' )
# * returns 2: -1
if str1 == str2 then 0 else if str1 > str2 then 1 else -1
doubleToReasonableString = (d) ->
# when generating code, print out
# with the maximum possible precision
if codeGen
return d + ""
# remove trailing zeroes beyond decimal point and
# gives at most 6 digits after the point
stringRepresentation = "" + parseFloat(d.toPrecision(6))
# we actually want to give a hint to user that
# it's a double, so add a trailing ".0" if there
# is no decimal point
if stringRepresentation.indexOf(".") == -1
stringRepresentation += ".0"
return stringRepresentation
# does nothing
clear_term = ->
# s is a string here anyways
isspace = (s) ->
if !s? then return false
return s == ' ' or s == '\t' or s == '\n' or s == '\v' or s == '\f' or s == '\r'
isdigit = (str) ->
if !str? then return false
return /^\d+$/.test(str)
isalpha = (str) ->
if !str? then return false
#Check for non-alphabetic characters and space
return (str.search(/[^A-Za-z]/) == -1)
isalphaOrUnderscore = (str) ->
if !str? then return false
#Check for non-alphabetic characters and space
return (str.search(/[^A-Za-z_]/) == -1)
isunderscore = (str) ->
if !str? then return false
return (str.search(/_/) == -1)
isalnumorunderscore = (str) ->
if !str? then return false
return (isalphaOrUnderscore(str) or isdigit(str))
| 208258 |
# The C library function int isspace(int c) checks
# whether the passed character is white-space.
strcmp = (str1, str2) ->
# http://kevin.vanzonneveld.net
# + original by: <NAME>
# + input by: <NAME>
# + improved by: <NAME> (http://kevin.vanzonneveld.net)
# + revised by: gorthaur
# * example 1: strcmp( 'waldo', 'owald' )
# * returns 1: 1
# * example 2: strcmp( 'owald', 'waldo' )
# * returns 2: -1
if str1 == str2 then 0 else if str1 > str2 then 1 else -1
doubleToReasonableString = (d) ->
# when generating code, print out
# with the maximum possible precision
if codeGen
return d + ""
# remove trailing zeroes beyond decimal point and
# gives at most 6 digits after the point
stringRepresentation = "" + parseFloat(d.toPrecision(6))
# we actually want to give a hint to user that
# it's a double, so add a trailing ".0" if there
# is no decimal point
if stringRepresentation.indexOf(".") == -1
stringRepresentation += ".0"
return stringRepresentation
# does nothing
clear_term = ->
# s is a string here anyways
isspace = (s) ->
if !s? then return false
return s == ' ' or s == '\t' or s == '\n' or s == '\v' or s == '\f' or s == '\r'
isdigit = (str) ->
if !str? then return false
return /^\d+$/.test(str)
isalpha = (str) ->
if !str? then return false
#Check for non-alphabetic characters and space
return (str.search(/[^A-Za-z]/) == -1)
isalphaOrUnderscore = (str) ->
if !str? then return false
#Check for non-alphabetic characters and space
return (str.search(/[^A-Za-z_]/) == -1)
isunderscore = (str) ->
if !str? then return false
return (str.search(/_/) == -1)
isalnumorunderscore = (str) ->
if !str? then return false
return (isalphaOrUnderscore(str) or isdigit(str))
| true |
# The C library function int isspace(int c) checks
# whether the passed character is white-space.
strcmp = (str1, str2) ->
# http://kevin.vanzonneveld.net
# + original by: PI:NAME:<NAME>END_PI
# + input by: PI:NAME:<NAME>END_PI
# + improved by: PI:NAME:<NAME>END_PI (http://kevin.vanzonneveld.net)
# + revised by: gorthaur
# * example 1: strcmp( 'waldo', 'owald' )
# * returns 1: 1
# * example 2: strcmp( 'owald', 'waldo' )
# * returns 2: -1
if str1 == str2 then 0 else if str1 > str2 then 1 else -1
doubleToReasonableString = (d) ->
# when generating code, print out
# with the maximum possible precision
if codeGen
return d + ""
# remove trailing zeroes beyond decimal point and
# gives at most 6 digits after the point
stringRepresentation = "" + parseFloat(d.toPrecision(6))
# we actually want to give a hint to user that
# it's a double, so add a trailing ".0" if there
# is no decimal point
if stringRepresentation.indexOf(".") == -1
stringRepresentation += ".0"
return stringRepresentation
# does nothing
clear_term = ->
# s is a string here anyways
isspace = (s) ->
if !s? then return false
return s == ' ' or s == '\t' or s == '\n' or s == '\v' or s == '\f' or s == '\r'
isdigit = (str) ->
if !str? then return false
return /^\d+$/.test(str)
isalpha = (str) ->
if !str? then return false
#Check for non-alphabetic characters and space
return (str.search(/[^A-Za-z]/) == -1)
isalphaOrUnderscore = (str) ->
if !str? then return false
#Check for non-alphabetic characters and space
return (str.search(/[^A-Za-z_]/) == -1)
isunderscore = (str) ->
if !str? then return false
return (str.search(/_/) == -1)
isalnumorunderscore = (str) ->
if !str? then return false
return (isalphaOrUnderscore(str) or isdigit(str))
|
[
{
"context": "st, @last].join(' ')\n\n me = new Name(first: \"Jack\", last: \"Harkness\")\n me\n .on('change'",
"end": 1238,
"score": 0.9998613595962524,
"start": 1234,
"tag": "NAME",
"value": "Jack"
},
{
"context": "n(' ')\n\n me = new Name(first: \"Jack\", las... | test/computed_test.coffee | rstacruz/ento | 11 | require './setup'
Name = null
me = null
describe 'computed properties', ->
describe 'definition', ->
it '.attr(name, deps, fn) syntax', ->
Name = Ento()
.attr('full', ['first','last'], ->)
expect(Name.attributes.full.via).be.like ['first', 'last']
it '.attr(name, fn, deps) syntax', ->
Name = Ento()
.attr('full', (->), ['first','last'])
expect(Name.attributes.full.via).be.like ['first', 'last']
it '.attr(name, fn, via: deps) syntax', ->
Name = Ento()
.attr('full', (->), via: ['first','last'])
expect(Name.attributes.full.via).be.like ['first', 'last']
it '.attr(name, via: deps, fn) syntax', ->
Name = Ento()
.attr('full', via: ['first','last'], ->)
expect(Name.attributes.full.via).be.like ['first', 'last']
it 'normalize cases', ->
Name = Ento()
.attr('full_name', ['first_name', 'lastName'], ->)
expect(Name.attributes.fullName.via).be.like ['firstName', 'lastName']
describe 'in practice', ->
beforeEach ->
Name = Ento()
.attr('first')
.attr('last')
.attr 'full', via: ['first', 'last'], ->
[@first, @last].join(' ')
me = new Name(first: "Jack", last: "Harkness")
me
.on('change', spy('change'))
.on('change:last', spy('change:last'))
.on('change:full', spy('change:full'))
it 'works', ->
expect(me.full).eql "Jack Harkness"
it 'Model.attributes', ->
expect(Name.attributes.full.via).be.like ['first', 'last']
it 'responds to change', ->
me.last = "Johnson"
expect(me.full).eql "Jack Johnson"
it 'change event', ->
me.last = "Skelington"
expect(spy('change')).calledOnce
it 'change event tells us what changed', ->
me.last = "Skelington"
expect(spy('change').firstCall.args[0]).like ['last', 'full']
it 'change:attr event', ->
me.last = "Skelington"
expect(spy('change:last')).calledOnce
it 'change:attr event of the dynamic attr', ->
me.last = "Skelington"
expect(spy('change:full')).calledOnce
describe 'deep dependencies', ->
beforeEach ->
Name = Ento()
.attr('first')
.attr('surname')
.attr('suffix')
.attr 'last', ['surname', 'suffix'], ->
[@surname, @suffix].join(' ')
.attr 'full', via: ['first', 'last'], ->
[@first, @last].join(' ')
me = new Name(first: "Jack", surname: "Harkness", suffix: 'III')
it 'should work', ->
expect(me.last).eql "Harkness III"
it 'should work, deep', ->
expect(me.full).eql "Jack Harkness III"
it 'should trigger change', ->
me.on('change:suffix', spy('suffix'))
me.on('change:last', spy('last'))
me.on('change:full', spy('full'))
me.suffix = "Sr."
expect(spy('suffix')).calledOnce
expect(spy('last')).calledOnce
expect(spy('full')).calledOnce
it 'change attrs', ->
me.on('change', spy('change'))
me.suffix = "Sr."
expect(spy('change').firstCall.args[0]).be.like ['suffix', 'full', 'last']
| 132431 | require './setup'
Name = null
me = null
describe 'computed properties', ->
describe 'definition', ->
it '.attr(name, deps, fn) syntax', ->
Name = Ento()
.attr('full', ['first','last'], ->)
expect(Name.attributes.full.via).be.like ['first', 'last']
it '.attr(name, fn, deps) syntax', ->
Name = Ento()
.attr('full', (->), ['first','last'])
expect(Name.attributes.full.via).be.like ['first', 'last']
it '.attr(name, fn, via: deps) syntax', ->
Name = Ento()
.attr('full', (->), via: ['first','last'])
expect(Name.attributes.full.via).be.like ['first', 'last']
it '.attr(name, via: deps, fn) syntax', ->
Name = Ento()
.attr('full', via: ['first','last'], ->)
expect(Name.attributes.full.via).be.like ['first', 'last']
it 'normalize cases', ->
Name = Ento()
.attr('full_name', ['first_name', 'lastName'], ->)
expect(Name.attributes.fullName.via).be.like ['firstName', 'lastName']
describe 'in practice', ->
beforeEach ->
Name = Ento()
.attr('first')
.attr('last')
.attr 'full', via: ['first', 'last'], ->
[@first, @last].join(' ')
me = new Name(first: "<NAME>", last: "<NAME>")
me
.on('change', spy('change'))
.on('change:last', spy('change:last'))
.on('change:full', spy('change:full'))
it 'works', ->
expect(me.full).eql "<NAME>"
it 'Model.attributes', ->
expect(Name.attributes.full.via).be.like ['first', 'last']
it 'responds to change', ->
me.last = "<NAME>"
expect(me.full).eql "<NAME>"
it 'change event', ->
me.last = "<NAME>"
expect(spy('change')).calledOnce
it 'change event tells us what changed', ->
me.last = "<NAME>"
expect(spy('change').firstCall.args[0]).like ['last', 'full']
it 'change:attr event', ->
me.last = "<NAME>"
expect(spy('change:last')).calledOnce
it 'change:attr event of the dynamic attr', ->
me.last = "<NAME>"
expect(spy('change:full')).calledOnce
describe 'deep dependencies', ->
beforeEach ->
Name = Ento()
.attr('first')
.attr('surname')
.attr('suffix')
.attr 'last', ['surname', 'suffix'], ->
[@surname, @suffix].join(' ')
.attr 'full', via: ['first', 'last'], ->
[@first, @last].join(' ')
me = new Name(first: "<NAME>", surname: "<NAME>", suffix: 'III')
it 'should work', ->
expect(me.last).eql "<NAME>"
it 'should work, deep', ->
expect(me.full).eql "<NAME>"
it 'should trigger change', ->
me.on('change:suffix', spy('suffix'))
me.on('change:last', spy('last'))
me.on('change:full', spy('full'))
me.suffix = "Sr."
expect(spy('suffix')).calledOnce
expect(spy('last')).calledOnce
expect(spy('full')).calledOnce
it 'change attrs', ->
me.on('change', spy('change'))
me.suffix = "Sr."
expect(spy('change').firstCall.args[0]).be.like ['suffix', 'full', 'last']
| true | require './setup'
Name = null
me = null
describe 'computed properties', ->
describe 'definition', ->
it '.attr(name, deps, fn) syntax', ->
Name = Ento()
.attr('full', ['first','last'], ->)
expect(Name.attributes.full.via).be.like ['first', 'last']
it '.attr(name, fn, deps) syntax', ->
Name = Ento()
.attr('full', (->), ['first','last'])
expect(Name.attributes.full.via).be.like ['first', 'last']
it '.attr(name, fn, via: deps) syntax', ->
Name = Ento()
.attr('full', (->), via: ['first','last'])
expect(Name.attributes.full.via).be.like ['first', 'last']
it '.attr(name, via: deps, fn) syntax', ->
Name = Ento()
.attr('full', via: ['first','last'], ->)
expect(Name.attributes.full.via).be.like ['first', 'last']
it 'normalize cases', ->
Name = Ento()
.attr('full_name', ['first_name', 'lastName'], ->)
expect(Name.attributes.fullName.via).be.like ['firstName', 'lastName']
describe 'in practice', ->
beforeEach ->
Name = Ento()
.attr('first')
.attr('last')
.attr 'full', via: ['first', 'last'], ->
[@first, @last].join(' ')
me = new Name(first: "PI:NAME:<NAME>END_PI", last: "PI:NAME:<NAME>END_PI")
me
.on('change', spy('change'))
.on('change:last', spy('change:last'))
.on('change:full', spy('change:full'))
it 'works', ->
expect(me.full).eql "PI:NAME:<NAME>END_PI"
it 'Model.attributes', ->
expect(Name.attributes.full.via).be.like ['first', 'last']
it 'responds to change', ->
me.last = "PI:NAME:<NAME>END_PI"
expect(me.full).eql "PI:NAME:<NAME>END_PI"
it 'change event', ->
me.last = "PI:NAME:<NAME>END_PI"
expect(spy('change')).calledOnce
it 'change event tells us what changed', ->
me.last = "PI:NAME:<NAME>END_PI"
expect(spy('change').firstCall.args[0]).like ['last', 'full']
it 'change:attr event', ->
me.last = "PI:NAME:<NAME>END_PI"
expect(spy('change:last')).calledOnce
it 'change:attr event of the dynamic attr', ->
me.last = "PI:NAME:<NAME>END_PI"
expect(spy('change:full')).calledOnce
describe 'deep dependencies', ->
beforeEach ->
Name = Ento()
.attr('first')
.attr('surname')
.attr('suffix')
.attr 'last', ['surname', 'suffix'], ->
[@surname, @suffix].join(' ')
.attr 'full', via: ['first', 'last'], ->
[@first, @last].join(' ')
me = new Name(first: "PI:NAME:<NAME>END_PI", surname: "PI:NAME:<NAME>END_PI", suffix: 'III')
it 'should work', ->
expect(me.last).eql "PI:NAME:<NAME>END_PI"
it 'should work, deep', ->
expect(me.full).eql "PI:NAME:<NAME>END_PI"
it 'should trigger change', ->
me.on('change:suffix', spy('suffix'))
me.on('change:last', spy('last'))
me.on('change:full', spy('full'))
me.suffix = "Sr."
expect(spy('suffix')).calledOnce
expect(spy('last')).calledOnce
expect(spy('full')).calledOnce
it 'change attrs', ->
me.on('change', spy('change'))
me.suffix = "Sr."
expect(spy('change').firstCall.args[0]).be.like ['suffix', 'full', 'last']
|
[
{
"context": "\"\"\"\n\n@author: Nino P. Cocchiarella\n(c) 2016\n\nGeneral site-wide plerping-system\n-star",
"end": 34,
"score": 0.999866783618927,
"start": 14,
"tag": "NAME",
"value": "Nino P. Cocchiarella"
}
] | src/static/site/coffeescript/iframe.coffee | nino-c/plerp.org | 0 | """
@author: Nino P. Cocchiarella
(c) 2016
General site-wide plerping-system
-startup routines
"""
# globals
window.artboard = null
window.ctx = null
class ArtBoard
constructor: () ->
@canvas = document.createElement 'canvas'
document.body.appendChild @canvas
@adjust_size();
window.ctx = @canvas.getContext("2d")
adjust_size: () ->
console.log("adjust artboard sizes")
@canvas.width = $(window).width()
@canvas.height = $(window).height()
$(document).ready ->
console.log("start iframe js app");
window.artboard = new ArtBoard();
window.start()
| 52976 | """
@author: <NAME>
(c) 2016
General site-wide plerping-system
-startup routines
"""
# globals
window.artboard = null
window.ctx = null
class ArtBoard
constructor: () ->
@canvas = document.createElement 'canvas'
document.body.appendChild @canvas
@adjust_size();
window.ctx = @canvas.getContext("2d")
adjust_size: () ->
console.log("adjust artboard sizes")
@canvas.width = $(window).width()
@canvas.height = $(window).height()
$(document).ready ->
console.log("start iframe js app");
window.artboard = new ArtBoard();
window.start()
| true | """
@author: PI:NAME:<NAME>END_PI
(c) 2016
General site-wide plerping-system
-startup routines
"""
# globals
window.artboard = null
window.ctx = null
class ArtBoard
constructor: () ->
@canvas = document.createElement 'canvas'
document.body.appendChild @canvas
@adjust_size();
window.ctx = @canvas.getContext("2d")
adjust_size: () ->
console.log("adjust artboard sizes")
@canvas.width = $(window).width()
@canvas.height = $(window).height()
$(document).ready ->
console.log("start iframe js app");
window.artboard = new ArtBoard();
window.start()
|
[
{
"context": "->\n\t\tDom.style textAlign: 'center'\n\t\tDom.text tr \"Best Hunters\"\n\n\tmeInTop3 = false\n\tDom.div !->\n\t\tDom.st",
"end": 1117,
"score": 0.7387544512748718,
"start": 1113,
"tag": "NAME",
"value": "Best"
},
{
"context": "\tDom.style textAlign: 'center'\n\t\tDom.t... | client.coffee | wwolbers/Photohunt | 0 | Db = require 'db'
Dom = require 'dom'
Modal = require 'modal'
Icon = require 'icon'
Loglist = require 'loglist'
Obs = require 'obs'
Plugin = require 'plugin'
Page = require 'page'
Server = require 'server'
Ui = require 'ui'
Form = require 'form'
Time = require 'time'
Colors = Plugin.colors()
Photo = require 'photo'
Social = require 'social'
{tr} = require 'i18n'
exports.render = !->
if Page.state.get(0)
renderHunt Page.state.get(0), Page.state.get(1)
# when a second id is passed along that photo is rendered without other stuff around it
return
rankings = Obs.create()
Db.shared.ref('hunts').observeEach (hunt) !->
if hunt.get('winner')
userWon = hunt.get('photos', hunt.get('winner'), 'userId')
rankings.incr userWon, 10
Obs.onClean !->
rankings.incr userWon, -10
hunt.observeEach 'photos', (photo) !->
return if photo.get('userId') is userWon or !+photo.key()
rankings.incr photo.get('userId'), 2
Obs.onClean !->
rankings.incr photo.get('userId'), -2
Obs.observe !->
log 'rankings', rankings.get()
Dom.h1 !->
Dom.style textAlign: 'center'
Dom.text tr "Best Hunters"
meInTop3 = false
Dom.div !->
Dom.style Box: true, padding: '4px 12px'
sorted = (+k for k, v of rankings.get()).sort (a, b) -> rankings.get(b) - rankings.get(a)
if !rankings.get(sorted[0])
Dom.div !->
Dom.style Flex: 1, textAlign: 'center', padding: '10px'
Dom.text tr("No photos have been submitted yet")
else
for i in [0..Math.min(2, sorted.length-1)] then do (i) !->
Dom.div !->
Dom.style Box: 'center vertical', Flex: 1
Ui.avatar Plugin.userAvatar(sorted[i]), null, 80
Dom.div !->
Dom.style margin: '4px', textAlign: 'center'
meInTop3 = true if Plugin.userId() is sorted[i]
Dom.text Plugin.userName(sorted[i])
Dom.div !->
Dom.style fontSize: '75%'
Dom.text tr("%1 points", rankings.get(sorted[i]))
if !meInTop3
Dom.div !->
Dom.style fontSize: '75%', fontStyle: 'italic', paddingBottom: '8px', textAlign: 'center'
Dom.text tr("(You have %1 point|s)", rankings.get(Plugin.userId())||0)
Ui.list !->
# next hunt
Ui.item !->
Dom.div !->
Dom.style width: '70px', height: '70px', marginRight: '10px', Box: 'center middle'
Icon.render data: 'clock2', color: '#aaa', style: { display: 'block' }, size: 34
Dom.div !->
Dom.div tr("A new Hunt will start")
Dom.div !->
Dom.style fontSize: '120%', fontWeight: 'bold'
Time.deltaText Db.shared.get('next')
Dom.onTap !->
requestNewHunt = !->
Server.call 'newHunt', 1, (done) !->
if (done)
require('modal').show tr("No more hunts"), tr("All hunts have taken place, contact the Happening makers about adding new hunts!")
if Plugin.userId() is Plugin.ownerId()
require('modal').show tr("New Hunt"), tr("Every day a new Hunt wil start somewhere between 10am and 10pm. You however (and admins), can trigger a new hunt manually (you added the Photo Hunt)."), (option) !->
if option is 'new'
requestNewHunt()
, ['cancel', tr("Cancel"), 'new', tr("New Hunt")]
else if Plugin.userIsAdmin()
require('modal').show tr("New Hunt"), tr("Every day a new Hunt wil start somewhere between 10am and 10pm. Admins however (and %1, who added the Photo Hunt), can trigger a new hunt manually.", Plugin.userName(Plugin.ownerId())), (option) !->
if option is 'new'
requestNewHunt()
, ['cancel', tr("Cancel"), 'new', tr("New Hunt")]
else
require('modal').show tr("New Hunt"), tr("Every day a new Hunt wil start somewhere between 10am and 10pm, unless an admin or %1 (who added the Photo Hunt) trigger a new hunt manually.", Plugin.userName(Plugin.ownerId()))
Db.shared.observeEach 'hunts', (hunt) !->
Ui.item !->
log 'hunt', hunt.get()
winningPhoto = hunt.ref('photos', hunt.get('winner'))
if key = winningPhoto.get('key')
Dom.div !->
Dom.style
width: '70px'
height: '70px'
marginRight: '10px'
background: "url(#{Photo.url key, 200}) 50% 50% no-repeat"
backgroundSize: 'cover'
Dom.div !->
Dom.style Flex: 1, fontSize: '120%'
Dom.text hunt.get('subject')
if hunt.get('winner')
Dom.div !->
Dom.style fontSize: '75%', marginTop: '6px'
Dom.text tr("%1 won!", Plugin.userName(hunt.get('photos', hunt.get('winner'), 'userId')))
if (cnt = hunt.count('photos').get()-2)
Dom.text ' (' + tr("%1 |runner-up|runners-up", cnt) + ')'
if unread = Social.newComments(hunt.key())
Dom.div !->
Ui.unread unread, null, {marginLeft: '4px'}
else
showAsNewest = +hunt.key() is +Db.shared.get('hunts', 'maxId') and Plugin.created() isnt hunt.get('time')
Dom.div !->
Dom.style width: '70px', height: '70px', marginRight: '10px', Box: 'center middle'
Icon.render
data: (if showAsNewest then 'new' else 'warn')
style: { display: 'block' }
size: 34
color: (if showAsNewest then null else '#aaa')
Dom.div !->
Dom.style Flex: 1, fontSize: '120%'
if showAsNewest
Dom.text tr "Take a photo of you.."
Dom.div !->
Dom.style fontSize: '120%', fontWeight: 'bold', color: Colors.highlight
Dom.text hunt.get('subject')
else
Dom.text hunt.get('subject')
Dom.div !->
Dom.style fontSize: '75%', marginTop: '6px'
Dom.text tr("Winner gets %1 points", 10)
if (cnt = hunt.count('photos').get()-1) > 0
Dom.text ' (' + tr("%1 disqualified |runner-up|runners-up", cnt) + ')'
if unread = Social.newComments(hunt.key())
Dom.div !->
Ui.unread unread, null, {marginLeft: '4px'}
Dom.onTap !->
Page.nav [hunt.key()]
, (hunt) -> # skip the maxId key
if +hunt.key()
-hunt.key()
renderHunt = (huntId, photoId) !->
Dom.style padding: 0
Page.setTitle Db.shared.get('hunts', huntId, 'subject')
winnerId = Db.shared.get 'hunts', huntId, 'winner'
photos = Db.shared.ref 'hunts', huntId, 'photos'
if photoId
mainPhoto = photos.ref photoId
else
mainPhoto = photos.ref winnerId
# remove button
if mainPhoto.get('userId') is Plugin.userId() or Plugin.userIsAdmin()
showDisqualify = Plugin.userIsAdmin() and mainPhoto.key() is winnerId
Page.setActions
icon: if showDisqualify then Plugin.resourceUri('icon-report-48.png') else Plugin.resourceUri('icon-trash-48.png')
action: !->
if showDisqualify
question = tr "Remove, or disqualify photo?"
options = ['cancel', tr("Cancel"), 'remove', tr("Remove"), 'disqualify', tr("Disqualify")]
else
question = tr "Remove photo?"
options = ['cancel', tr("Cancel"), 'ok', tr("OK")]
require('modal').show null, question, (option) !->
if option isnt 'cancel'
Server.sync 'removePhoto', huntId, mainPhoto.key(), (option is 'disqualify'), !->
Db.shared.remove 'hunts', huntId, 'winner'
if option is 'disqualify'
photos.set mainPhoto.key(), 'disqualified', true
else
photos.remove(mainPhoto.key())
if photoId # don't navigate back from winner page
Page.back()
, options
boxSize = Obs.create()
Obs.observe !->
width = Dom.viewport.get('width')
cnt = (0|(width / 100)) || 1
boxSize.set(0|(width-((cnt+1)*4))/cnt)
if !photoId
allowUpload = Obs.create(true) # when the current use has no photos yet, allow upload
Db.shared.observeEach 'hunts', huntId, 'photos', (photo) !->
return if +photo.get('userId') isnt Plugin.userId()
allowUpload.set false
Obs.onClean !->
allowUpload.set true
Dom.div !->
Dom.style backgroundColor: '#fff', paddingBottom: '2px', borderBottom: '2px solid #ccc'
# main photo
contain = Obs.create false
if mainPhoto and mainPhoto.key()
(require 'photoview').render
key: mainPhoto.get('key')
content: !->
Ui.avatar Plugin.userAvatar(mainPhoto.get('userId')), !->
Dom.style position: 'absolute', bottom: '4px', right: '4px', margin: 0
Dom.div !->
Dom.style
position: 'absolute'
textAlign: 'right'
bottom: '10px'
right: '50px'
textShadow: '0 1px 0 #000'
color: '#fff'
if photoId
Dom.text tr("Runner-up by %1", Plugin.userName(mainPhoto.get('userId')))
else
Dom.text tr("Won by %1", Plugin.userName(mainPhoto.get('userId')))
Dom.div !->
Dom.style fontSize: '75%'
Dom.text tr("%1 point|s", if photoId then 2 else 10)
else if !photoId
Dom.div !->
Dom.style textAlign: 'center', padding: '16px'
if allowUpload.get()
addPhoto boxSize.get()-4, huntId
Dom.div !->
Dom.style textAlign: 'center', marginBottom: '16px'
Dom.text tr 'The first one wins 10 points!'
else
Dom.text tr "You have already submitted a photo for this Hunt..."
# we're only rendering other submissions and comments when it's the winner being displayed
if !photoId
photos = Db.shared.ref 'hunts', huntId, 'photos'
# do we have a winner, or runner-ups?
if winnerId or photos.count().get()>(1 + if winnerId then 1 else 0)
Dom.div !->
Dom.style padding: '2px'
Dom.h2 !->
Dom.style margin: '8px 2px 4px 2px'
Dom.text tr "Runners-up (2 points)"
photos.observeEach (photo) !->
return if +photo.key() is winnerId
Dom.div !->
Dom.cls 'photo'
Dom.style
display: 'inline-block'
position: 'relative'
margin: '2px'
height: (boxSize.get()) + 'px'
width: (boxSize.get()) + 'px'
backgroundImage: Photo.css photo.get('key'), 200
backgroundSize: 'cover'
backgroundPosition: '50% 50%'
backgroundRepeat: 'no-repeat'
Ui.avatar Plugin.userAvatar(photo.get('userId')), !->
Dom.style position: 'absolute', bottom: '4px', right: '4px', margin: 0
Dom.onTap !->
Page.nav [huntId, photo.key()]
, (photo) ->
if +photo.key()
photo.key()
if allowUpload.get() and winnerId
addPhoto boxSize.get()-4, huntId
else if photos.count().get()<=(1 + if winnerId then 1 else 0) # maxId is also counted
Dom.div !->
Dom.style padding: '2px', color: '#aaa'
Dom.text tr "No runners-up submitted"
if !photoId
log 'comments >>> '+huntId
Social.renderComments huntId, render: (comment) ->
if comment.s and comment.u
comment.c = Plugin.userName(comment.u) + ' ' + comment.c
Dom.div !->
Dom.style margin: '6px 0 6px 56px', fontSize: '70%'
Dom.span !->
Dom.style color: '#999'
Time.deltaText comment.t
Dom.text " • "
Dom.text comment.c
true # We're rendering these type of comments
addPhoto = (size, huntId) !->
Dom.div !->
Dom.cls 'add'
Dom.style
display: 'inline-block'
position: 'relative'
verticalAlign: 'top'
margin: '2px'
background: "url(#{Plugin.resourceUri('addphoto.png')}) 50% 50% no-repeat"
backgroundSize: '32px'
border: 'dashed 2px #aaa'
height: size + 'px'
width: size + 'px'
Dom.onTap !->
Photo.pick 'camera', [huntId]
Dom.css
'.add.tap::after, .photo.tap::after':
content: '""'
display: 'block'
position: 'absolute'
left: 0
right: 0
top: 0
bottom: 0
backgroundColor: 'rgba(0, 0, 0, 0.2)'
| 189364 | Db = require 'db'
Dom = require 'dom'
Modal = require 'modal'
Icon = require 'icon'
Loglist = require 'loglist'
Obs = require 'obs'
Plugin = require 'plugin'
Page = require 'page'
Server = require 'server'
Ui = require 'ui'
Form = require 'form'
Time = require 'time'
Colors = Plugin.colors()
Photo = require 'photo'
Social = require 'social'
{tr} = require 'i18n'
exports.render = !->
if Page.state.get(0)
renderHunt Page.state.get(0), Page.state.get(1)
# when a second id is passed along that photo is rendered without other stuff around it
return
rankings = Obs.create()
Db.shared.ref('hunts').observeEach (hunt) !->
if hunt.get('winner')
userWon = hunt.get('photos', hunt.get('winner'), 'userId')
rankings.incr userWon, 10
Obs.onClean !->
rankings.incr userWon, -10
hunt.observeEach 'photos', (photo) !->
return if photo.get('userId') is userWon or !+photo.key()
rankings.incr photo.get('userId'), 2
Obs.onClean !->
rankings.incr photo.get('userId'), -2
Obs.observe !->
log 'rankings', rankings.get()
Dom.h1 !->
Dom.style textAlign: 'center'
Dom.text tr "<NAME> <NAME>unters"
meInTop3 = false
Dom.div !->
Dom.style Box: true, padding: '4px 12px'
sorted = (+k for k, v of rankings.get()).sort (a, b) -> rankings.get(b) - rankings.get(a)
if !rankings.get(sorted[0])
Dom.div !->
Dom.style Flex: 1, textAlign: 'center', padding: '10px'
Dom.text tr("No photos have been submitted yet")
else
for i in [0..Math.min(2, sorted.length-1)] then do (i) !->
Dom.div !->
Dom.style Box: 'center vertical', Flex: 1
Ui.avatar Plugin.userAvatar(sorted[i]), null, 80
Dom.div !->
Dom.style margin: '4px', textAlign: 'center'
meInTop3 = true if Plugin.userId() is sorted[i]
Dom.text Plugin.userName(sorted[i])
Dom.div !->
Dom.style fontSize: '75%'
Dom.text tr("%1 points", rankings.get(sorted[i]))
if !meInTop3
Dom.div !->
Dom.style fontSize: '75%', fontStyle: 'italic', paddingBottom: '8px', textAlign: 'center'
Dom.text tr("(You have %1 point|s)", rankings.get(Plugin.userId())||0)
Ui.list !->
# next hunt
Ui.item !->
Dom.div !->
Dom.style width: '70px', height: '70px', marginRight: '10px', Box: 'center middle'
Icon.render data: 'clock2', color: '#aaa', style: { display: 'block' }, size: 34
Dom.div !->
Dom.div tr("A new Hunt will start")
Dom.div !->
Dom.style fontSize: '120%', fontWeight: 'bold'
Time.deltaText Db.shared.get('next')
Dom.onTap !->
requestNewHunt = !->
Server.call 'newHunt', 1, (done) !->
if (done)
require('modal').show tr("No more hunts"), tr("All hunts have taken place, contact the Happening makers about adding new hunts!")
if Plugin.userId() is Plugin.ownerId()
require('modal').show tr("New Hunt"), tr("Every day a new Hunt wil start somewhere between 10am and 10pm. You however (and admins), can trigger a new hunt manually (you added the Photo Hunt)."), (option) !->
if option is 'new'
requestNewHunt()
, ['cancel', tr("Cancel"), 'new', tr("New Hunt")]
else if Plugin.userIsAdmin()
require('modal').show tr("New Hunt"), tr("Every day a new Hunt wil start somewhere between 10am and 10pm. Admins however (and %1, who added the Photo Hunt), can trigger a new hunt manually.", Plugin.userName(Plugin.ownerId())), (option) !->
if option is 'new'
requestNewHunt()
, ['cancel', tr("Cancel"), 'new', tr("New Hunt")]
else
require('modal').show tr("New Hunt"), tr("Every day a new Hunt wil start somewhere between 10am and 10pm, unless an admin or %1 (who added the Photo Hunt) trigger a new hunt manually.", Plugin.userName(Plugin.ownerId()))
Db.shared.observeEach 'hunts', (hunt) !->
Ui.item !->
log 'hunt', hunt.get()
winningPhoto = hunt.ref('photos', hunt.get('winner'))
if key = winningPhoto.get('key')
Dom.div !->
Dom.style
width: '70px'
height: '70px'
marginRight: '10px'
background: "url(#{Photo.url key, 200}) 50% 50% no-repeat"
backgroundSize: 'cover'
Dom.div !->
Dom.style Flex: 1, fontSize: '120%'
Dom.text hunt.get('subject')
if hunt.get('winner')
Dom.div !->
Dom.style fontSize: '75%', marginTop: '6px'
Dom.text tr("%1 won!", Plugin.userName(hunt.get('photos', hunt.get('winner'), 'userId')))
if (cnt = hunt.count('photos').get()-2)
Dom.text ' (' + tr("%1 |runner-up|runners-up", cnt) + ')'
if unread = Social.newComments(hunt.key())
Dom.div !->
Ui.unread unread, null, {marginLeft: '4px'}
else
showAsNewest = +hunt.key() is +Db.shared.get('hunts', 'maxId') and Plugin.created() isnt hunt.get('time')
Dom.div !->
Dom.style width: '70px', height: '70px', marginRight: '10px', Box: 'center middle'
Icon.render
data: (if showAsNewest then 'new' else 'warn')
style: { display: 'block' }
size: 34
color: (if showAsNewest then null else '#aaa')
Dom.div !->
Dom.style Flex: 1, fontSize: '120%'
if showAsNewest
Dom.text tr "Take a photo of you.."
Dom.div !->
Dom.style fontSize: '120%', fontWeight: 'bold', color: Colors.highlight
Dom.text hunt.get('subject')
else
Dom.text hunt.get('subject')
Dom.div !->
Dom.style fontSize: '75%', marginTop: '6px'
Dom.text tr("Winner gets %1 points", 10)
if (cnt = hunt.count('photos').get()-1) > 0
Dom.text ' (' + tr("%1 disqualified |runner-up|runners-up", cnt) + ')'
if unread = Social.newComments(hunt.key())
Dom.div !->
Ui.unread unread, null, {marginLeft: '4px'}
Dom.onTap !->
Page.nav [hunt.key()]
, (hunt) -> # skip the maxId key
if +hunt.key()
-hunt.key()
renderHunt = (huntId, photoId) !->
Dom.style padding: 0
Page.setTitle Db.shared.get('hunts', huntId, 'subject')
winnerId = Db.shared.get 'hunts', huntId, 'winner'
photos = Db.shared.ref 'hunts', huntId, 'photos'
if photoId
mainPhoto = photos.ref photoId
else
mainPhoto = photos.ref winnerId
# remove button
if mainPhoto.get('userId') is Plugin.userId() or Plugin.userIsAdmin()
showDisqualify = Plugin.userIsAdmin() and mainPhoto.key() is winnerId
Page.setActions
icon: if showDisqualify then Plugin.resourceUri('icon-report-48.png') else Plugin.resourceUri('icon-trash-48.png')
action: !->
if showDisqualify
question = tr "Remove, or disqualify photo?"
options = ['cancel', tr("Cancel"), 'remove', tr("Remove"), 'disqualify', tr("Disqualify")]
else
question = tr "Remove photo?"
options = ['cancel', tr("Cancel"), 'ok', tr("OK")]
require('modal').show null, question, (option) !->
if option isnt 'cancel'
Server.sync 'removePhoto', huntId, mainPhoto.key(), (option is 'disqualify'), !->
Db.shared.remove 'hunts', huntId, 'winner'
if option is 'disqualify'
photos.set mainPhoto.key(), 'disqualified', true
else
photos.remove(mainPhoto.key())
if photoId # don't navigate back from winner page
Page.back()
, options
boxSize = Obs.create()
Obs.observe !->
width = Dom.viewport.get('width')
cnt = (0|(width / 100)) || 1
boxSize.set(0|(width-((cnt+1)*4))/cnt)
if !photoId
allowUpload = Obs.create(true) # when the current use has no photos yet, allow upload
Db.shared.observeEach 'hunts', huntId, 'photos', (photo) !->
return if +photo.get('userId') isnt Plugin.userId()
allowUpload.set false
Obs.onClean !->
allowUpload.set true
Dom.div !->
Dom.style backgroundColor: '#fff', paddingBottom: '2px', borderBottom: '2px solid #ccc'
# main photo
contain = Obs.create false
if mainPhoto and mainPhoto.key()
(require 'photoview').render
key: mainPhoto.get('key')
content: !->
Ui.avatar Plugin.userAvatar(mainPhoto.get('userId')), !->
Dom.style position: 'absolute', bottom: '4px', right: '4px', margin: 0
Dom.div !->
Dom.style
position: 'absolute'
textAlign: 'right'
bottom: '10px'
right: '50px'
textShadow: '0 1px 0 #000'
color: '#fff'
if photoId
Dom.text tr("Runner-up by %1", Plugin.userName(mainPhoto.get('userId')))
else
Dom.text tr("Won by %1", Plugin.userName(mainPhoto.get('userId')))
Dom.div !->
Dom.style fontSize: '75%'
Dom.text tr("%1 point|s", if photoId then 2 else 10)
else if !photoId
Dom.div !->
Dom.style textAlign: 'center', padding: '16px'
if allowUpload.get()
addPhoto boxSize.get()-4, huntId
Dom.div !->
Dom.style textAlign: 'center', marginBottom: '16px'
Dom.text tr 'The first one wins 10 points!'
else
Dom.text tr "You have already submitted a photo for this Hunt..."
# we're only rendering other submissions and comments when it's the winner being displayed
if !photoId
photos = Db.shared.ref 'hunts', huntId, 'photos'
# do we have a winner, or runner-ups?
if winnerId or photos.count().get()>(1 + if winnerId then 1 else 0)
Dom.div !->
Dom.style padding: '2px'
Dom.h2 !->
Dom.style margin: '8px 2px 4px 2px'
Dom.text tr "Runners-up (2 points)"
photos.observeEach (photo) !->
return if +photo.key() is winnerId
Dom.div !->
Dom.cls 'photo'
Dom.style
display: 'inline-block'
position: 'relative'
margin: '2px'
height: (boxSize.get()) + 'px'
width: (boxSize.get()) + 'px'
backgroundImage: Photo.css photo.get('key'), 200
backgroundSize: 'cover'
backgroundPosition: '50% 50%'
backgroundRepeat: 'no-repeat'
Ui.avatar Plugin.userAvatar(photo.get('userId')), !->
Dom.style position: 'absolute', bottom: '4px', right: '4px', margin: 0
Dom.onTap !->
Page.nav [huntId, photo.key()]
, (photo) ->
if +photo.key()
photo.key()
if allowUpload.get() and winnerId
addPhoto boxSize.get()-4, huntId
else if photos.count().get()<=(1 + if winnerId then 1 else 0) # maxId is also counted
Dom.div !->
Dom.style padding: '2px', color: '#aaa'
Dom.text tr "No runners-up submitted"
if !photoId
log 'comments >>> '+huntId
Social.renderComments huntId, render: (comment) ->
if comment.s and comment.u
comment.c = Plugin.userName(comment.u) + ' ' + comment.c
Dom.div !->
Dom.style margin: '6px 0 6px 56px', fontSize: '70%'
Dom.span !->
Dom.style color: '#999'
Time.deltaText comment.t
Dom.text " • "
Dom.text comment.c
true # We're rendering these type of comments
addPhoto = (size, huntId) !->
Dom.div !->
Dom.cls 'add'
Dom.style
display: 'inline-block'
position: 'relative'
verticalAlign: 'top'
margin: '2px'
background: "url(#{Plugin.resourceUri('addphoto.png')}) 50% 50% no-repeat"
backgroundSize: '32px'
border: 'dashed 2px #aaa'
height: size + 'px'
width: size + 'px'
Dom.onTap !->
Photo.pick 'camera', [huntId]
Dom.css
'.add.tap::after, .photo.tap::after':
content: '""'
display: 'block'
position: 'absolute'
left: 0
right: 0
top: 0
bottom: 0
backgroundColor: 'rgba(0, 0, 0, 0.2)'
| true | Db = require 'db'
Dom = require 'dom'
Modal = require 'modal'
Icon = require 'icon'
Loglist = require 'loglist'
Obs = require 'obs'
Plugin = require 'plugin'
Page = require 'page'
Server = require 'server'
Ui = require 'ui'
Form = require 'form'
Time = require 'time'
Colors = Plugin.colors()
Photo = require 'photo'
Social = require 'social'
{tr} = require 'i18n'
exports.render = !->
if Page.state.get(0)
renderHunt Page.state.get(0), Page.state.get(1)
# when a second id is passed along that photo is rendered without other stuff around it
return
rankings = Obs.create()
Db.shared.ref('hunts').observeEach (hunt) !->
if hunt.get('winner')
userWon = hunt.get('photos', hunt.get('winner'), 'userId')
rankings.incr userWon, 10
Obs.onClean !->
rankings.incr userWon, -10
hunt.observeEach 'photos', (photo) !->
return if photo.get('userId') is userWon or !+photo.key()
rankings.incr photo.get('userId'), 2
Obs.onClean !->
rankings.incr photo.get('userId'), -2
Obs.observe !->
log 'rankings', rankings.get()
Dom.h1 !->
Dom.style textAlign: 'center'
Dom.text tr "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PIunters"
meInTop3 = false
Dom.div !->
Dom.style Box: true, padding: '4px 12px'
sorted = (+k for k, v of rankings.get()).sort (a, b) -> rankings.get(b) - rankings.get(a)
if !rankings.get(sorted[0])
Dom.div !->
Dom.style Flex: 1, textAlign: 'center', padding: '10px'
Dom.text tr("No photos have been submitted yet")
else
for i in [0..Math.min(2, sorted.length-1)] then do (i) !->
Dom.div !->
Dom.style Box: 'center vertical', Flex: 1
Ui.avatar Plugin.userAvatar(sorted[i]), null, 80
Dom.div !->
Dom.style margin: '4px', textAlign: 'center'
meInTop3 = true if Plugin.userId() is sorted[i]
Dom.text Plugin.userName(sorted[i])
Dom.div !->
Dom.style fontSize: '75%'
Dom.text tr("%1 points", rankings.get(sorted[i]))
if !meInTop3
Dom.div !->
Dom.style fontSize: '75%', fontStyle: 'italic', paddingBottom: '8px', textAlign: 'center'
Dom.text tr("(You have %1 point|s)", rankings.get(Plugin.userId())||0)
Ui.list !->
# next hunt
Ui.item !->
Dom.div !->
Dom.style width: '70px', height: '70px', marginRight: '10px', Box: 'center middle'
Icon.render data: 'clock2', color: '#aaa', style: { display: 'block' }, size: 34
Dom.div !->
Dom.div tr("A new Hunt will start")
Dom.div !->
Dom.style fontSize: '120%', fontWeight: 'bold'
Time.deltaText Db.shared.get('next')
Dom.onTap !->
requestNewHunt = !->
Server.call 'newHunt', 1, (done) !->
if (done)
require('modal').show tr("No more hunts"), tr("All hunts have taken place, contact the Happening makers about adding new hunts!")
if Plugin.userId() is Plugin.ownerId()
require('modal').show tr("New Hunt"), tr("Every day a new Hunt wil start somewhere between 10am and 10pm. You however (and admins), can trigger a new hunt manually (you added the Photo Hunt)."), (option) !->
if option is 'new'
requestNewHunt()
, ['cancel', tr("Cancel"), 'new', tr("New Hunt")]
else if Plugin.userIsAdmin()
require('modal').show tr("New Hunt"), tr("Every day a new Hunt wil start somewhere between 10am and 10pm. Admins however (and %1, who added the Photo Hunt), can trigger a new hunt manually.", Plugin.userName(Plugin.ownerId())), (option) !->
if option is 'new'
requestNewHunt()
, ['cancel', tr("Cancel"), 'new', tr("New Hunt")]
else
require('modal').show tr("New Hunt"), tr("Every day a new Hunt wil start somewhere between 10am and 10pm, unless an admin or %1 (who added the Photo Hunt) trigger a new hunt manually.", Plugin.userName(Plugin.ownerId()))
Db.shared.observeEach 'hunts', (hunt) !->
Ui.item !->
log 'hunt', hunt.get()
winningPhoto = hunt.ref('photos', hunt.get('winner'))
if key = winningPhoto.get('key')
Dom.div !->
Dom.style
width: '70px'
height: '70px'
marginRight: '10px'
background: "url(#{Photo.url key, 200}) 50% 50% no-repeat"
backgroundSize: 'cover'
Dom.div !->
Dom.style Flex: 1, fontSize: '120%'
Dom.text hunt.get('subject')
if hunt.get('winner')
Dom.div !->
Dom.style fontSize: '75%', marginTop: '6px'
Dom.text tr("%1 won!", Plugin.userName(hunt.get('photos', hunt.get('winner'), 'userId')))
if (cnt = hunt.count('photos').get()-2)
Dom.text ' (' + tr("%1 |runner-up|runners-up", cnt) + ')'
if unread = Social.newComments(hunt.key())
Dom.div !->
Ui.unread unread, null, {marginLeft: '4px'}
else
showAsNewest = +hunt.key() is +Db.shared.get('hunts', 'maxId') and Plugin.created() isnt hunt.get('time')
Dom.div !->
Dom.style width: '70px', height: '70px', marginRight: '10px', Box: 'center middle'
Icon.render
data: (if showAsNewest then 'new' else 'warn')
style: { display: 'block' }
size: 34
color: (if showAsNewest then null else '#aaa')
Dom.div !->
Dom.style Flex: 1, fontSize: '120%'
if showAsNewest
Dom.text tr "Take a photo of you.."
Dom.div !->
Dom.style fontSize: '120%', fontWeight: 'bold', color: Colors.highlight
Dom.text hunt.get('subject')
else
Dom.text hunt.get('subject')
Dom.div !->
Dom.style fontSize: '75%', marginTop: '6px'
Dom.text tr("Winner gets %1 points", 10)
if (cnt = hunt.count('photos').get()-1) > 0
Dom.text ' (' + tr("%1 disqualified |runner-up|runners-up", cnt) + ')'
if unread = Social.newComments(hunt.key())
Dom.div !->
Ui.unread unread, null, {marginLeft: '4px'}
Dom.onTap !->
Page.nav [hunt.key()]
, (hunt) -> # skip the maxId key
if +hunt.key()
-hunt.key()
renderHunt = (huntId, photoId) !->
Dom.style padding: 0
Page.setTitle Db.shared.get('hunts', huntId, 'subject')
winnerId = Db.shared.get 'hunts', huntId, 'winner'
photos = Db.shared.ref 'hunts', huntId, 'photos'
if photoId
mainPhoto = photos.ref photoId
else
mainPhoto = photos.ref winnerId
# remove button
if mainPhoto.get('userId') is Plugin.userId() or Plugin.userIsAdmin()
showDisqualify = Plugin.userIsAdmin() and mainPhoto.key() is winnerId
Page.setActions
icon: if showDisqualify then Plugin.resourceUri('icon-report-48.png') else Plugin.resourceUri('icon-trash-48.png')
action: !->
if showDisqualify
question = tr "Remove, or disqualify photo?"
options = ['cancel', tr("Cancel"), 'remove', tr("Remove"), 'disqualify', tr("Disqualify")]
else
question = tr "Remove photo?"
options = ['cancel', tr("Cancel"), 'ok', tr("OK")]
require('modal').show null, question, (option) !->
if option isnt 'cancel'
Server.sync 'removePhoto', huntId, mainPhoto.key(), (option is 'disqualify'), !->
Db.shared.remove 'hunts', huntId, 'winner'
if option is 'disqualify'
photos.set mainPhoto.key(), 'disqualified', true
else
photos.remove(mainPhoto.key())
if photoId # don't navigate back from winner page
Page.back()
, options
boxSize = Obs.create()
Obs.observe !->
width = Dom.viewport.get('width')
cnt = (0|(width / 100)) || 1
boxSize.set(0|(width-((cnt+1)*4))/cnt)
if !photoId
allowUpload = Obs.create(true) # when the current use has no photos yet, allow upload
Db.shared.observeEach 'hunts', huntId, 'photos', (photo) !->
return if +photo.get('userId') isnt Plugin.userId()
allowUpload.set false
Obs.onClean !->
allowUpload.set true
Dom.div !->
Dom.style backgroundColor: '#fff', paddingBottom: '2px', borderBottom: '2px solid #ccc'
# main photo
contain = Obs.create false
if mainPhoto and mainPhoto.key()
(require 'photoview').render
key: mainPhoto.get('key')
content: !->
Ui.avatar Plugin.userAvatar(mainPhoto.get('userId')), !->
Dom.style position: 'absolute', bottom: '4px', right: '4px', margin: 0
Dom.div !->
Dom.style
position: 'absolute'
textAlign: 'right'
bottom: '10px'
right: '50px'
textShadow: '0 1px 0 #000'
color: '#fff'
if photoId
Dom.text tr("Runner-up by %1", Plugin.userName(mainPhoto.get('userId')))
else
Dom.text tr("Won by %1", Plugin.userName(mainPhoto.get('userId')))
Dom.div !->
Dom.style fontSize: '75%'
Dom.text tr("%1 point|s", if photoId then 2 else 10)
else if !photoId
Dom.div !->
Dom.style textAlign: 'center', padding: '16px'
if allowUpload.get()
addPhoto boxSize.get()-4, huntId
Dom.div !->
Dom.style textAlign: 'center', marginBottom: '16px'
Dom.text tr 'The first one wins 10 points!'
else
Dom.text tr "You have already submitted a photo for this Hunt..."
# we're only rendering other submissions and comments when it's the winner being displayed
if !photoId
photos = Db.shared.ref 'hunts', huntId, 'photos'
# do we have a winner, or runner-ups?
if winnerId or photos.count().get()>(1 + if winnerId then 1 else 0)
Dom.div !->
Dom.style padding: '2px'
Dom.h2 !->
Dom.style margin: '8px 2px 4px 2px'
Dom.text tr "Runners-up (2 points)"
photos.observeEach (photo) !->
return if +photo.key() is winnerId
Dom.div !->
Dom.cls 'photo'
Dom.style
display: 'inline-block'
position: 'relative'
margin: '2px'
height: (boxSize.get()) + 'px'
width: (boxSize.get()) + 'px'
backgroundImage: Photo.css photo.get('key'), 200
backgroundSize: 'cover'
backgroundPosition: '50% 50%'
backgroundRepeat: 'no-repeat'
Ui.avatar Plugin.userAvatar(photo.get('userId')), !->
Dom.style position: 'absolute', bottom: '4px', right: '4px', margin: 0
Dom.onTap !->
Page.nav [huntId, photo.key()]
, (photo) ->
if +photo.key()
photo.key()
if allowUpload.get() and winnerId
addPhoto boxSize.get()-4, huntId
else if photos.count().get()<=(1 + if winnerId then 1 else 0) # maxId is also counted
Dom.div !->
Dom.style padding: '2px', color: '#aaa'
Dom.text tr "No runners-up submitted"
if !photoId
log 'comments >>> '+huntId
Social.renderComments huntId, render: (comment) ->
if comment.s and comment.u
comment.c = Plugin.userName(comment.u) + ' ' + comment.c
Dom.div !->
Dom.style margin: '6px 0 6px 56px', fontSize: '70%'
Dom.span !->
Dom.style color: '#999'
Time.deltaText comment.t
Dom.text " • "
Dom.text comment.c
true # We're rendering these type of comments
addPhoto = (size, huntId) !->
Dom.div !->
Dom.cls 'add'
Dom.style
display: 'inline-block'
position: 'relative'
verticalAlign: 'top'
margin: '2px'
background: "url(#{Plugin.resourceUri('addphoto.png')}) 50% 50% no-repeat"
backgroundSize: '32px'
border: 'dashed 2px #aaa'
height: size + 'px'
width: size + 'px'
Dom.onTap !->
Photo.pick 'camera', [huntId]
Dom.css
'.add.tap::after, .photo.tap::after':
content: '""'
display: 'block'
position: 'absolute'
left: 0
right: 0
top: 0
bottom: 0
backgroundColor: 'rgba(0, 0, 0, 0.2)'
|
[
{
"context": "\n else \n key = fuzzyMatches[index] || \"__$!SCALAR\" + originals.__next++\n originals[key] ",
"end": 2461,
"score": 0.4890611171722412,
"start": 2461,
"tag": "KEY",
"value": ""
},
{
"context": "else \n key = fuzzyMatches[index] || \"__$!SCALAR\" + or... | old-coffee-lib/index.coffee | luckygerbils/json-diff | 658 | { SequenceMatcher } = require 'difflib'
{ extendedTypeOf } = require './util'
{ colorize } = require './colorize'
isScalar = (obj) -> (typeof obj isnt 'object' || obj == null)
objectDiff = (obj1, obj2, options = {}) ->
result = {}
score = 0
for own key, value1 of obj1 when !(key of obj2)
result["#{key}__deleted"] = value1
score -= 30
for own key, value2 of obj2 when !(key of obj1)
result["#{key}__added"] = value2
score -= 30
for own key, value1 of obj1 when key of obj2
score += 20
value2 = obj2[key]
[subscore, change] = diffWithScore(value1, value2, options)
if change
result[key] = change
else
result[key] = value1
# console.log "key #{key} subscore=#{subscore} #{value1}"
score += Math.min(20, Math.max(-10, subscore / 5)) # BATMAN!
if Object.keys(result).length is 0
[score, result] = [100 * Math.max(Object.keys(obj1).length, 0.5), undefined]
else
score = Math.max(0, score)
# console.log "objectDiff(#{JSON.stringify(obj1, null, 2)} <=> #{JSON.stringify(obj2, null, 2)}) == #{JSON.stringify([score, result])}"
return [score, result]
findMatchingObject = (item, index, fuzzyOriginals) ->
# console.log "findMatchingObject: " + JSON.stringify({item, fuzzyOriginals}, null, 2)
bestMatch = null
matchIndex = 0
for own key, candidate of fuzzyOriginals when key isnt '__next'
indexDistance = Math.abs(matchIndex - index)
if extendedTypeOf(item) == extendedTypeOf(candidate)
score = diffScore(item, candidate)
if !bestMatch || score > bestMatch.score || (score == bestMatch.score && indexDistance < bestMatch.indexDistance)
bestMatch = { score, key, indexDistance }
matchIndex++
# console.log "findMatchingObject result = " + JSON.stringify(bestMatch, null, 2)
bestMatch
scalarize = (array, originals, fuzzyOriginals) ->
fuzzyMatches = []
if fuzzyOriginals
# Find best fuzzy match for each object in the array
keyScores = {}
for item, index in array
if isScalar item
continue
bestMatch = findMatchingObject(item, index, fuzzyOriginals)
if !keyScores[bestMatch.key] || bestMatch.score > keyScores[bestMatch.key].score
keyScores[bestMatch.key] = {score: bestMatch.score, index}
for key, match of keyScores
fuzzyMatches[match.index] = key
for item, index in array
if isScalar item
item
else
key = fuzzyMatches[index] || "__$!SCALAR" + originals.__next++
originals[key] = item
key
isScalarized = (item, originals) ->
(typeof item is 'string') && (item of originals)
descalarize = (item, originals) ->
if isScalarized(item, originals)
originals[item]
else
item
arrayDiff = (obj1, obj2, options = {}) ->
originals1 = { __next: 1 }
seq1 = scalarize(obj1, originals1)
originals2 = { __next: originals1.__next }
seq2 = scalarize(obj2, originals2, originals1)
opcodes = new SequenceMatcher(null, seq1, seq2).getOpcodes()
# console.log "arrayDiff:\nobj1 = #{JSON.stringify(obj1, null, 2)}\nobj2 = #{JSON.stringify(obj2, null, 2)}\nseq1 = #{JSON.stringify(seq1, null, 2)}\nseq2 = #{JSON.stringify(seq2, null, 2)}\nopcodes = #{JSON.stringify(opcodes, null, 2)}"
result = []
score = 0
allEqual = yes
for [op, i1, i2, j1, j2] in opcodes
if !(op is 'equal' or (options.keysOnly and op is 'replace'))
allEqual = no
switch op
when 'equal'
for i in [i1 ... i2]
item = seq1[i]
if isScalarized(item, originals1)
unless isScalarized(item, originals2)
throw new AssertionError("internal bug: isScalarized(item, originals1) != isScalarized(item, originals2) for item #{JSON.stringify(item)}")
item1 = descalarize(item, originals1)
item2 = descalarize(item, originals2)
change = diff(item1, item2, options)
if change
result.push ['~', change]
allEqual = no
else
result.push [' ', item1]
else
result.push [' ', item]
score += 10
when 'delete'
for i in [i1 ... i2]
result.push ['-', descalarize(seq1[i], originals1)]
score -= 5
when 'insert'
for j in [j1 ... j2]
result.push ['+', descalarize(seq2[j], originals2)]
score -= 5
when 'replace'
if !options.keysOnly
for i in [i1 ... i2]
result.push ['-', descalarize(seq1[i], originals1)]
score -= 5
for j in [j1 ... j2]
result.push ['+', descalarize(seq2[j], originals2)]
score -= 5
else
for i in [i1 ... i2]
change = diff(descalarize(seq1[i], originals1), descalarize(seq2[i - i1 + j1], originals2), options)
if change
result.push ['~', change]
allEqual = no
else
result.push [' ']
if allEqual or (opcodes.length is 0)
# result = undefined
score = 100
else
score = Math.max(0, score)
return [score, result]
diffWithScore = (obj1, obj2, options = {}) ->
type1 = extendedTypeOf obj1
type2 = extendedTypeOf obj2
if type1 == type2
switch type1
when 'object'
return objectDiff(obj1, obj2, options)
when 'array'
return arrayDiff(obj1, obj2, options)
if !options.keysOnly
if obj1 != obj2
[0, { __old: obj1, __new: obj2 }]
else
[100, obj1]
else
[100, undefined]
diff = (obj1, obj2, options = {}) ->
[score, change] = diffWithScore(obj1, obj2, options)
return change
diffScore = (obj1, obj2, options = {}) ->
[score, change] = diffWithScore(obj1, obj2, options)
return score
diffString = (obj1, obj2, colorizeOptions, diffOptions = {}) ->
return colorize(diff(obj1, obj2, diffOptions), colorizeOptions)
module.exports = { diff, diffString }
| 72173 | { SequenceMatcher } = require 'difflib'
{ extendedTypeOf } = require './util'
{ colorize } = require './colorize'
isScalar = (obj) -> (typeof obj isnt 'object' || obj == null)
objectDiff = (obj1, obj2, options = {}) ->
result = {}
score = 0
for own key, value1 of obj1 when !(key of obj2)
result["#{key}__deleted"] = value1
score -= 30
for own key, value2 of obj2 when !(key of obj1)
result["#{key}__added"] = value2
score -= 30
for own key, value1 of obj1 when key of obj2
score += 20
value2 = obj2[key]
[subscore, change] = diffWithScore(value1, value2, options)
if change
result[key] = change
else
result[key] = value1
# console.log "key #{key} subscore=#{subscore} #{value1}"
score += Math.min(20, Math.max(-10, subscore / 5)) # BATMAN!
if Object.keys(result).length is 0
[score, result] = [100 * Math.max(Object.keys(obj1).length, 0.5), undefined]
else
score = Math.max(0, score)
# console.log "objectDiff(#{JSON.stringify(obj1, null, 2)} <=> #{JSON.stringify(obj2, null, 2)}) == #{JSON.stringify([score, result])}"
return [score, result]
findMatchingObject = (item, index, fuzzyOriginals) ->
# console.log "findMatchingObject: " + JSON.stringify({item, fuzzyOriginals}, null, 2)
bestMatch = null
matchIndex = 0
for own key, candidate of fuzzyOriginals when key isnt '__next'
indexDistance = Math.abs(matchIndex - index)
if extendedTypeOf(item) == extendedTypeOf(candidate)
score = diffScore(item, candidate)
if !bestMatch || score > bestMatch.score || (score == bestMatch.score && indexDistance < bestMatch.indexDistance)
bestMatch = { score, key, indexDistance }
matchIndex++
# console.log "findMatchingObject result = " + JSON.stringify(bestMatch, null, 2)
bestMatch
scalarize = (array, originals, fuzzyOriginals) ->
fuzzyMatches = []
if fuzzyOriginals
# Find best fuzzy match for each object in the array
keyScores = {}
for item, index in array
if isScalar item
continue
bestMatch = findMatchingObject(item, index, fuzzyOriginals)
if !keyScores[bestMatch.key] || bestMatch.score > keyScores[bestMatch.key].score
keyScores[bestMatch.key] = {score: bestMatch.score, index}
for key, match of keyScores
fuzzyMatches[match.index] = key
for item, index in array
if isScalar item
item
else
key = fuzzyMatches[index] || "__$<KEY>!SCAL<KEY>" + originals.__next++
originals[key] = item
key
isScalarized = (item, originals) ->
(typeof item is 'string') && (item of originals)
descalarize = (item, originals) ->
if isScalarized(item, originals)
originals[item]
else
item
arrayDiff = (obj1, obj2, options = {}) ->
originals1 = { __next: 1 }
seq1 = scalarize(obj1, originals1)
originals2 = { __next: originals1.__next }
seq2 = scalarize(obj2, originals2, originals1)
opcodes = new SequenceMatcher(null, seq1, seq2).getOpcodes()
# console.log "arrayDiff:\nobj1 = #{JSON.stringify(obj1, null, 2)}\nobj2 = #{JSON.stringify(obj2, null, 2)}\nseq1 = #{JSON.stringify(seq1, null, 2)}\nseq2 = #{JSON.stringify(seq2, null, 2)}\nopcodes = #{JSON.stringify(opcodes, null, 2)}"
result = []
score = 0
allEqual = yes
for [op, i1, i2, j1, j2] in opcodes
if !(op is 'equal' or (options.keysOnly and op is 'replace'))
allEqual = no
switch op
when 'equal'
for i in [i1 ... i2]
item = seq1[i]
if isScalarized(item, originals1)
unless isScalarized(item, originals2)
throw new AssertionError("internal bug: isScalarized(item, originals1) != isScalarized(item, originals2) for item #{JSON.stringify(item)}")
item1 = descalarize(item, originals1)
item2 = descalarize(item, originals2)
change = diff(item1, item2, options)
if change
result.push ['~', change]
allEqual = no
else
result.push [' ', item1]
else
result.push [' ', item]
score += 10
when 'delete'
for i in [i1 ... i2]
result.push ['-', descalarize(seq1[i], originals1)]
score -= 5
when 'insert'
for j in [j1 ... j2]
result.push ['+', descalarize(seq2[j], originals2)]
score -= 5
when 'replace'
if !options.keysOnly
for i in [i1 ... i2]
result.push ['-', descalarize(seq1[i], originals1)]
score -= 5
for j in [j1 ... j2]
result.push ['+', descalarize(seq2[j], originals2)]
score -= 5
else
for i in [i1 ... i2]
change = diff(descalarize(seq1[i], originals1), descalarize(seq2[i - i1 + j1], originals2), options)
if change
result.push ['~', change]
allEqual = no
else
result.push [' ']
if allEqual or (opcodes.length is 0)
# result = undefined
score = 100
else
score = Math.max(0, score)
return [score, result]
diffWithScore = (obj1, obj2, options = {}) ->
type1 = extendedTypeOf obj1
type2 = extendedTypeOf obj2
if type1 == type2
switch type1
when 'object'
return objectDiff(obj1, obj2, options)
when 'array'
return arrayDiff(obj1, obj2, options)
if !options.keysOnly
if obj1 != obj2
[0, { __old: obj1, __new: obj2 }]
else
[100, obj1]
else
[100, undefined]
diff = (obj1, obj2, options = {}) ->
[score, change] = diffWithScore(obj1, obj2, options)
return change
diffScore = (obj1, obj2, options = {}) ->
[score, change] = diffWithScore(obj1, obj2, options)
return score
diffString = (obj1, obj2, colorizeOptions, diffOptions = {}) ->
return colorize(diff(obj1, obj2, diffOptions), colorizeOptions)
module.exports = { diff, diffString }
| true | { SequenceMatcher } = require 'difflib'
{ extendedTypeOf } = require './util'
{ colorize } = require './colorize'
isScalar = (obj) -> (typeof obj isnt 'object' || obj == null)
objectDiff = (obj1, obj2, options = {}) ->
result = {}
score = 0
for own key, value1 of obj1 when !(key of obj2)
result["#{key}__deleted"] = value1
score -= 30
for own key, value2 of obj2 when !(key of obj1)
result["#{key}__added"] = value2
score -= 30
for own key, value1 of obj1 when key of obj2
score += 20
value2 = obj2[key]
[subscore, change] = diffWithScore(value1, value2, options)
if change
result[key] = change
else
result[key] = value1
# console.log "key #{key} subscore=#{subscore} #{value1}"
score += Math.min(20, Math.max(-10, subscore / 5)) # BATMAN!
if Object.keys(result).length is 0
[score, result] = [100 * Math.max(Object.keys(obj1).length, 0.5), undefined]
else
score = Math.max(0, score)
# console.log "objectDiff(#{JSON.stringify(obj1, null, 2)} <=> #{JSON.stringify(obj2, null, 2)}) == #{JSON.stringify([score, result])}"
return [score, result]
findMatchingObject = (item, index, fuzzyOriginals) ->
# console.log "findMatchingObject: " + JSON.stringify({item, fuzzyOriginals}, null, 2)
bestMatch = null
matchIndex = 0
for own key, candidate of fuzzyOriginals when key isnt '__next'
indexDistance = Math.abs(matchIndex - index)
if extendedTypeOf(item) == extendedTypeOf(candidate)
score = diffScore(item, candidate)
if !bestMatch || score > bestMatch.score || (score == bestMatch.score && indexDistance < bestMatch.indexDistance)
bestMatch = { score, key, indexDistance }
matchIndex++
# console.log "findMatchingObject result = " + JSON.stringify(bestMatch, null, 2)
bestMatch
scalarize = (array, originals, fuzzyOriginals) ->
fuzzyMatches = []
if fuzzyOriginals
# Find best fuzzy match for each object in the array
keyScores = {}
for item, index in array
if isScalar item
continue
bestMatch = findMatchingObject(item, index, fuzzyOriginals)
if !keyScores[bestMatch.key] || bestMatch.score > keyScores[bestMatch.key].score
keyScores[bestMatch.key] = {score: bestMatch.score, index}
for key, match of keyScores
fuzzyMatches[match.index] = key
for item, index in array
if isScalar item
item
else
key = fuzzyMatches[index] || "__$PI:KEY:<KEY>END_PI!SCALPI:KEY:<KEY>END_PI" + originals.__next++
originals[key] = item
key
isScalarized = (item, originals) ->
(typeof item is 'string') && (item of originals)
descalarize = (item, originals) ->
if isScalarized(item, originals)
originals[item]
else
item
arrayDiff = (obj1, obj2, options = {}) ->
originals1 = { __next: 1 }
seq1 = scalarize(obj1, originals1)
originals2 = { __next: originals1.__next }
seq2 = scalarize(obj2, originals2, originals1)
opcodes = new SequenceMatcher(null, seq1, seq2).getOpcodes()
# console.log "arrayDiff:\nobj1 = #{JSON.stringify(obj1, null, 2)}\nobj2 = #{JSON.stringify(obj2, null, 2)}\nseq1 = #{JSON.stringify(seq1, null, 2)}\nseq2 = #{JSON.stringify(seq2, null, 2)}\nopcodes = #{JSON.stringify(opcodes, null, 2)}"
result = []
score = 0
allEqual = yes
for [op, i1, i2, j1, j2] in opcodes
if !(op is 'equal' or (options.keysOnly and op is 'replace'))
allEqual = no
switch op
when 'equal'
for i in [i1 ... i2]
item = seq1[i]
if isScalarized(item, originals1)
unless isScalarized(item, originals2)
throw new AssertionError("internal bug: isScalarized(item, originals1) != isScalarized(item, originals2) for item #{JSON.stringify(item)}")
item1 = descalarize(item, originals1)
item2 = descalarize(item, originals2)
change = diff(item1, item2, options)
if change
result.push ['~', change]
allEqual = no
else
result.push [' ', item1]
else
result.push [' ', item]
score += 10
when 'delete'
for i in [i1 ... i2]
result.push ['-', descalarize(seq1[i], originals1)]
score -= 5
when 'insert'
for j in [j1 ... j2]
result.push ['+', descalarize(seq2[j], originals2)]
score -= 5
when 'replace'
if !options.keysOnly
for i in [i1 ... i2]
result.push ['-', descalarize(seq1[i], originals1)]
score -= 5
for j in [j1 ... j2]
result.push ['+', descalarize(seq2[j], originals2)]
score -= 5
else
for i in [i1 ... i2]
change = diff(descalarize(seq1[i], originals1), descalarize(seq2[i - i1 + j1], originals2), options)
if change
result.push ['~', change]
allEqual = no
else
result.push [' ']
if allEqual or (opcodes.length is 0)
# result = undefined
score = 100
else
score = Math.max(0, score)
return [score, result]
diffWithScore = (obj1, obj2, options = {}) ->
type1 = extendedTypeOf obj1
type2 = extendedTypeOf obj2
if type1 == type2
switch type1
when 'object'
return objectDiff(obj1, obj2, options)
when 'array'
return arrayDiff(obj1, obj2, options)
if !options.keysOnly
if obj1 != obj2
[0, { __old: obj1, __new: obj2 }]
else
[100, obj1]
else
[100, undefined]
diff = (obj1, obj2, options = {}) ->
[score, change] = diffWithScore(obj1, obj2, options)
return change
diffScore = (obj1, obj2, options = {}) ->
[score, change] = diffWithScore(obj1, obj2, options)
return score
diffString = (obj1, obj2, colorizeOptions, diffOptions = {}) ->
return colorize(diff(obj1, obj2, diffOptions), colorizeOptions)
module.exports = { diff, diffString }
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9994344115257263,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | lib/fs.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.
# Maintainers, keep in mind that octal literals are not allowed
# in strict mode. Use the decimal value and add a comment with
# the octal value. Example:
#
# var mode = 438; /* mode=0666 */
rethrow = ->
# Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
# is fairly slow to generate.
if DEBUG
backtrace = new Error
return (err) ->
if err
backtrace.stack = err.name + ": " + err.message + backtrace.stack.substr(backtrace.name.length)
err = backtrace
throw err
return
(err) ->
throw err if err # Forgot a callback but don't know where? Use NODE_DEBUG=fs
return
maybeCallback = (cb) ->
(if util.isFunction(cb) then cb else rethrow())
# Ensure that callbacks run in the global context. Only use this function
# for callbacks that are passed to the binding layer, callbacks that are
# invoked from JS already run in the proper scope.
makeCallback = (cb) ->
return rethrow() unless util.isFunction(cb)
->
cb.apply null, arguments
assertEncoding = (encoding) ->
throw new Error("Unknown encoding: " + encoding) if encoding and not Buffer.isEncoding(encoding)
return
nullCheck = (path, callback) ->
if ("" + path).indexOf("\u0000") isnt -1
er = new Error("Path must be a string without null bytes.")
throw er unless callback
process.nextTick ->
callback er
return
return false
true
# Static method to set the stats properties on a Stats object.
# Create a C++ binding to the function which creates a Stats object.
# first, stat the file, so we know the size.
# single buffer with file data
# list for when size is unknown
#=0666
# the kernel lies about many files.
# Go ahead and try to read some bytes.
# unknown size, just read until we don't get bytes.
# collected the data into the buffers list.
#=0666
# single buffer with file data
# list for when size is unknown
# the kernel lies about many files.
# Go ahead and try to read some bytes.
# data was collected into the buffers list.
# Used by binding.open and friends
stringToFlags = (flag) ->
# Only mess with strings
return flag unless util.isString(flag)
switch flag
when "r"
return O_RDONLY
# fall through
when "rs", "sr"
return O_RDONLY | O_SYNC
when "r+"
return O_RDWR
# fall through
when "rs+", "sr+"
return O_RDWR | O_SYNC
when "w"
return O_TRUNC | O_CREAT | O_WRONLY
# fall through
when "wx", "xw"
return O_TRUNC | O_CREAT | O_WRONLY | O_EXCL
when "w+"
return O_TRUNC | O_CREAT | O_RDWR
# fall through
when "wx+", "xw+"
return O_TRUNC | O_CREAT | O_RDWR | O_EXCL
when "a"
return O_APPEND | O_CREAT | O_WRONLY
# fall through
when "ax", "xa"
return O_APPEND | O_CREAT | O_WRONLY | O_EXCL
when "a+"
return O_APPEND | O_CREAT | O_RDWR
# fall through
when "ax+", "xa+"
return O_APPEND | O_CREAT | O_RDWR | O_EXCL
throw new Error("Unknown file open flag: " + flag)return
# exported but hidden, only used by test/simple/test-fs-open-flags.js
# Yes, the follow could be easily DRYed up but I provide the explicit
# list to make the arguments clear.
modeNum = (m, def) ->
return m if util.isNumber(m)
return parseInt(m, 8) if util.isString(m)
return modeNum(def) if def
`undefined`
#=0666
#=0666
# legacy string interface (fd, length, position, encoding, callback)
# Retain a reference to buffer so that it can't be GC'ed too soon.
# legacy string interface (fd, length, position, encoding, callback)
# usage:
# fs.write(fd, buffer, offset, length[, position], callback);
# OR
# fs.write(fd, string[, position[, encoding]], callback);
# Retain a reference to buffer so that it can't be GC'ed too soon.
# retain reference to string in case it's external
# if no position is passed then assume null
# usage:
# fs.writeSync(fd, buffer, offset, length[, position]);
# OR
# fs.writeSync(fd, string[, position[, encoding]]);
# legacy
# allow error to be thrown, but still close fd.
#=0777
#=0777
preprocessSymlinkDestination = (path, type, linkPath) ->
unless isWindows
# No preprocessing is needed on Unix.
path
else if type is "junction"
# Junctions paths need to be absolute and \\?\-prefixed.
# A relative target is relative to the link's parent directory.
path = pathModule.resolve(linkPath, "..", path)
pathModule._makeLong path
else
# Windows symlinks don't tolerate forward slashes.
("" + path).replace /\//g, "\\"
# prefer to return the chmod error, if one occurs,
# but still try to close, and report closing errors if they occur.
# prefer to return the chmod error, if one occurs,
# but still try to close, and report closing errors if they occur.
# converts Date or number to a fractional UNIX timestamp
toUnixTimestamp = (time) ->
return time if util.isNumber(time)
# convert to 123.456 UNIX timestamp
return time.getTime() / 1000 if util.isDate(time)
throw new Error("Cannot parse time: " + time)return
# exported for unit tests, not for public consumption
writeAll = (fd, buffer, offset, length, position, callback) ->
callback = maybeCallback(arguments[arguments.length - 1])
# write(fd, buffer, offset, length, position, callback)
fs.write fd, buffer, offset, length, position, (writeErr, written) ->
if writeErr
fs.close fd, ->
callback writeErr if callback
return
else
if written is length
fs.close fd, callback
else
offset += written
length -= written
position += written
writeAll fd, buffer, offset, length, position, callback
return
return
#=0666
#=0666
#=0666
#=0666
FSWatcher = ->
EventEmitter.call this
self = this
FSEvent = process.binding("fs_event_wrap").FSEvent
@_handle = new FSEvent()
@_handle.owner = this
@_handle.onchange = (status, event, filename) ->
if status < 0
self._handle.close()
self.emit "error", errnoException(status, "watch")
else
self.emit "change", event, filename
return
return
# Stat Change Watchers
StatWatcher = ->
EventEmitter.call this
self = this
@_handle = new binding.StatWatcher()
# uv_fs_poll is a little more powerful than ev_stat but we curb it for
# the sake of backwards compatibility
oldStatus = -1
@_handle.onchange = (current, previous, newStatus) ->
return if oldStatus is -1 and newStatus is -1 and current.nlink is previous.nlink
oldStatus = newStatus
self.emit "change", current, previous
return
@_handle.onstop = ->
self.emit "stop"
return
return
inStatWatchers = (filename) ->
Object::hasOwnProperty.call(statWatchers, filename) and statWatchers[filename]
# Poll interval in milliseconds. 5007 is what libev used to use. It's
# a little on the slow side but let's stick with it for now to keep
# behavioral changes to a minimum.
# Regexp that finds the next partion of a (partial) path
# result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
# Regex to find the device root, including trailing slash. E.g. 'c:\\'.
# make p is absolute
# current character position in p
# the partial path so far, including a trailing slash if any
# the partial path without a trailing slash (except when pointing at a root)
# the partial path scanned in the previous round, with slash
# Skip over roots
# On windows, check that the root exists. On unix there is no need.
# walk down the path, swapping out linked pathparts for their real
# values
# NB: p.length changes.
# find the next part
# continue if not a symlink
# some known symbolic link. no need to stat again.
# read the link if it wasn't read before
# dev/ino always return 0 on windows, so skip the check.
# track this, if given a cache.
# resolve the link, then start over
# make p is absolute
# current character position in p
# the partial path so far, including a trailing slash if any
# the partial path without a trailing slash (except when pointing at a root)
# the partial path scanned in the previous round, with slash
# Skip over roots
# On windows, check that the root exists. On unix there is no need.
# walk down the path, swapping out linked pathparts for their real
# values
# stop if scanned past end of path
# find the next part
# continue if not a symlink
# known symbolic link. no need to stat again.
# if not a symlink, skip to the next path part
# stat & read the link if not read before
# call gotTarget as soon as the link target is known
# dev/ino always return 0 on windows, so skip the check.
# resolve the link, then start over
allocNewPool = (poolSize) ->
pool = new Buffer(poolSize)
pool.used = 0
return
ReadStream = (path, options) ->
return new ReadStream(path, options) unless this instanceof ReadStream
# a little bit bigger buffer and water marks by default
options = util._extend(
highWaterMark: 64 * 1024
, options or {})
Readable.call this, options
@path = path
@fd = (if options.hasOwnProperty("fd") then options.fd else null)
@flags = (if options.hasOwnProperty("flags") then options.flags else "r")
@mode = (if options.hasOwnProperty("mode") then options.mode else 438) #=0666
@start = (if options.hasOwnProperty("start") then options.start else `undefined`)
@end = (if options.hasOwnProperty("end") then options.end else `undefined`)
@autoClose = (if options.hasOwnProperty("autoClose") then options.autoClose else true)
@pos = `undefined`
unless util.isUndefined(@start)
throw TypeError("start must be a Number") unless util.isNumber(@start)
if util.isUndefined(@end)
@end = Infinity
else throw TypeError("end must be a Number") unless util.isNumber(@end)
throw new Error("start must be <= end") if @start > @end
@pos = @start
@open() unless util.isNumber(@fd)
@on "end", ->
@destroy() if @autoClose
return
return
# support the legacy name
# start the flow of data.
# discard the old pool.
# Grab another reference to the pool in the case that while we're
# in the thread pool another read() finishes up the pool, and
# allocates a new one.
# already read everything we were supposed to read!
# treat as EOF.
# the actual read.
# move the pool positions, and internal position for reading.
WriteStream = (path, options) ->
return new WriteStream(path, options) unless this instanceof WriteStream
options = options or {}
Writable.call this, options
@path = path
@fd = null
@fd = (if options.hasOwnProperty("fd") then options.fd else null)
@flags = (if options.hasOwnProperty("flags") then options.flags else "w")
@mode = (if options.hasOwnProperty("mode") then options.mode else 438) #=0666
@start = (if options.hasOwnProperty("start") then options.start else `undefined`)
@pos = `undefined`
@bytesWritten = 0
unless util.isUndefined(@start)
throw TypeError("start must be a Number") unless util.isNumber(@start)
throw new Error("start must be >= zero") if @start < 0
@pos = @start
@open() unless util.isNumber(@fd)
# dispose on finish.
@once "finish", @close
return
# support the legacy name
# There is no shutdown() for files.
# SyncWriteStream is internal. DO NOT USE.
# Temporary hack for process.stdout and process.stderr when piped to files.
SyncWriteStream = (fd, options) ->
Stream.call this
options = options or {}
@fd = fd
@writable = true
@readable = false
@autoClose = (if options.hasOwnProperty("autoClose") then options.autoClose else true)
return
"use strict"
util = require("util")
pathModule = require("path")
binding = process.binding("fs")
constants = process.binding("constants")
fs = exports
Stream = require("stream").Stream
EventEmitter = require("events").EventEmitter
FSReqWrap = binding.FSReqWrap
Readable = Stream.Readable
Writable = Stream.Writable
kMinPoolSpace = 128
kMaxLength = require("smalloc").kMaxLength
O_APPEND = constants.O_APPEND or 0
O_CREAT = constants.O_CREAT or 0
O_EXCL = constants.O_EXCL or 0
O_RDONLY = constants.O_RDONLY or 0
O_RDWR = constants.O_RDWR or 0
O_SYNC = constants.O_SYNC or 0
O_TRUNC = constants.O_TRUNC or 0
O_WRONLY = constants.O_WRONLY or 0
F_OK = constants.F_OK or 0
R_OK = constants.R_OK or 0
W_OK = constants.W_OK or 0
X_OK = constants.X_OK or 0
isWindows = process.platform is "win32"
DEBUG = process.env.NODE_DEBUG and /fs/.test(process.env.NODE_DEBUG)
errnoException = util._errnoException
fs.Stats = (dev, mode, nlink, uid, gid, rdev, blksize, ino, size, blocks, atim_msec, mtim_msec, ctim_msec, birthtim_msec) ->
@dev = dev
@mode = mode
@nlink = nlink
@uid = uid
@gid = gid
@rdev = rdev
@blksize = blksize
@ino = ino
@size = size
@blocks = blocks
@atime = new Date(atim_msec)
@mtime = new Date(mtim_msec)
@ctime = new Date(ctim_msec)
@birthtime = new Date(birthtim_msec)
return
binding.FSInitialize fs.Stats
fs.Stats::_checkModeProperty = (property) ->
(@mode & constants.S_IFMT) is property
fs.Stats::isDirectory = ->
@_checkModeProperty constants.S_IFDIR
fs.Stats::isFile = ->
@_checkModeProperty constants.S_IFREG
fs.Stats::isBlockDevice = ->
@_checkModeProperty constants.S_IFBLK
fs.Stats::isCharacterDevice = ->
@_checkModeProperty constants.S_IFCHR
fs.Stats::isSymbolicLink = ->
@_checkModeProperty constants.S_IFLNK
fs.Stats::isFIFO = ->
@_checkModeProperty constants.S_IFIFO
fs.Stats::isSocket = ->
@_checkModeProperty constants.S_IFSOCK
fs.F_OK = F_OK
fs.R_OK = R_OK
fs.W_OK = W_OK
fs.X_OK = X_OK
fs.access = (path, mode, callback) ->
return unless nullCheck(path, callback)
if typeof mode is "function"
callback = mode
mode = F_OK
else throw new TypeError("callback must be a function") if typeof callback isnt "function"
mode = mode | 0
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.access pathModule._makeLong(path), mode, req
return
fs.accessSync = (path, mode) ->
nullCheck path
if mode is `undefined`
mode = F_OK
else
mode = mode | 0
binding.access pathModule._makeLong(path), mode
return
fs.exists = (path, callback) ->
cb = (err, stats) ->
callback (if err then false else true) if callback
return
return unless nullCheck(path, cb)
req = new FSReqWrap()
req.oncomplete = cb
binding.stat pathModule._makeLong(path), req
return
fs.existsSync = (path) ->
try
nullCheck path
binding.stat pathModule._makeLong(path)
return true
catch e
return false
return
fs.readFile = (path, options, callback_) ->
read = ->
if size is 0
buffer = new Buffer(8192)
fs.read fd, buffer, 0, 8192, -1, afterRead
else
fs.read fd, buffer, pos, size - pos, -1, afterRead
return
afterRead = (er, bytesRead) ->
if er
return fs.close(fd, (er2) ->
callback er
)
return close() if bytesRead is 0
pos += bytesRead
if size isnt 0
if pos is size
close()
else
read()
else
buffers.push buffer.slice(0, bytesRead)
read()
return
close = ->
fs.close fd, (er) ->
if size is 0
buffer = Buffer.concat(buffers, pos)
else buffer = buffer.slice(0, pos) if pos < size
buffer = buffer.toString(encoding) if encoding
callback er, buffer
return
callback = maybeCallback(arguments[arguments.length - 1])
if util.isFunction(options) or not options
options =
encoding: null
flag: "r"
else if util.isString(options)
options =
encoding: options
flag: "r"
else throw new TypeError("Bad arguments") unless util.isObject(options)
encoding = options.encoding
assertEncoding encoding
size = undefined
buffer = undefined
buffers = undefined
pos = 0
fd = undefined
flag = options.flag or "r"
fs.open path, flag, 438, (er, fd_) ->
return callback(er) if er
fd = fd_
fs.fstat fd, (er, st) ->
if er
return fs.close(fd, ->
callback er
return
)
size = st.size
if size is 0
buffers = []
return read()
if size > kMaxLength
err = new RangeError("File size is greater than possible Buffer: " + "0x3FFFFFFF bytes")
return fs.close(fd, ->
callback err
return
)
buffer = new Buffer(size)
read()
return
return
return
fs.readFileSync = (path, options) ->
unless options
options =
encoding: null
flag: "r"
else if util.isString(options)
options =
encoding: options
flag: "r"
else throw new TypeError("Bad arguments") unless util.isObject(options)
encoding = options.encoding
assertEncoding encoding
flag = options.flag or "r"
fd = fs.openSync(path, flag, 438)
size = undefined
threw = true
try
size = fs.fstatSync(fd).size
threw = false
finally
fs.closeSync fd if threw
pos = 0
buffer = undefined
buffers = undefined
if size is 0
buffers = []
else
threw = true
try
buffer = new Buffer(size)
threw = false
finally
fs.closeSync fd if threw
done = false
until done
threw = true
try
if size isnt 0
bytesRead = fs.readSync(fd, buffer, pos, size - pos)
else
buffer = new Buffer(8192)
bytesRead = fs.readSync(fd, buffer, 0, 8192)
buffers.push buffer.slice(0, bytesRead) if bytesRead
threw = false
finally
fs.closeSync fd if threw
pos += bytesRead
done = (bytesRead is 0) or (size isnt 0 and pos >= size)
fs.closeSync fd
if size is 0
buffer = Buffer.concat(buffers, pos)
else buffer = buffer.slice(0, pos) if pos < size
buffer = buffer.toString(encoding) if encoding
buffer
Object.defineProperty exports, "_stringToFlags",
enumerable: false
value: stringToFlags
fs.close = (fd, callback) ->
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.close fd, req
return
fs.closeSync = (fd) ->
binding.close fd
fs.open = (path, flags, mode, callback) ->
callback = makeCallback(arguments[arguments.length - 1])
mode = modeNum(mode, 438)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.open pathModule._makeLong(path), stringToFlags(flags), mode, req
return
fs.openSync = (path, flags, mode) ->
mode = modeNum(mode, 438)
nullCheck path
binding.open pathModule._makeLong(path), stringToFlags(flags), mode
fs.read = (fd, buffer, offset, length, position, callback) ->
wrapper = (err, bytesRead) ->
callback and callback(err, bytesRead or 0, buffer)
return
unless util.isBuffer(buffer)
cb = arguments[4]
encoding = arguments[3]
assertEncoding encoding
position = arguments[2]
length = arguments[1]
buffer = new Buffer(length)
offset = 0
callback = (err, bytesRead) ->
return unless cb
str = (if (bytesRead > 0) then buffer.toString(encoding, 0, bytesRead) else "")
(cb) err, str, bytesRead
return
req = new FSReqWrap()
req.oncomplete = wrapper
binding.read fd, buffer, offset, length, position, req
return
fs.readSync = (fd, buffer, offset, length, position) ->
legacy = false
unless util.isBuffer(buffer)
legacy = true
encoding = arguments[3]
assertEncoding encoding
position = arguments[2]
length = arguments[1]
buffer = new Buffer(length)
offset = 0
r = binding.read(fd, buffer, offset, length, position)
return r unless legacy
str = (if (r > 0) then buffer.toString(encoding, 0, r) else "")
[
str
r
]
fs.write = (fd, buffer, offset, length, position, callback) ->
strWrapper = (err, written) ->
callback err, written or 0, buffer
return
bufWrapper = (err, written) ->
callback err, written or 0, buffer
return
if util.isBuffer(buffer)
if util.isFunction(position)
callback = position
position = null
callback = maybeCallback(callback)
req = new FSReqWrap()
req.oncomplete = strWrapper
return binding.writeBuffer(fd, buffer, offset, length, position, req)
buffer += "" if util.isString(buffer)
unless util.isFunction(position)
if util.isFunction(offset)
position = offset
offset = null
else
position = length
length = "utf8"
callback = maybeCallback(position)
req = new FSReqWrap()
req.oncomplete = bufWrapper
binding.writeString fd, buffer, offset, length, req
fs.writeSync = (fd, buffer, offset, length, position) ->
if util.isBuffer(buffer)
position = null if util.isUndefined(position)
return binding.writeBuffer(fd, buffer, offset, length, position)
buffer += "" unless util.isString(buffer)
offset = null if util.isUndefined(offset)
binding.writeString fd, buffer, offset, length, position
fs.rename = (oldPath, newPath, callback) ->
callback = makeCallback(callback)
return unless nullCheck(oldPath, callback)
return unless nullCheck(newPath, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.rename pathModule._makeLong(oldPath), pathModule._makeLong(newPath), req
return
fs.renameSync = (oldPath, newPath) ->
nullCheck oldPath
nullCheck newPath
binding.rename pathModule._makeLong(oldPath), pathModule._makeLong(newPath)
fs.truncate = (path, len, callback) ->
if util.isNumber(path)
req = new FSReqWrap()
req.oncomplete = callback
return fs.ftruncate(path, len, req)
if util.isFunction(len)
callback = len
len = 0
else len = 0 if util.isUndefined(len)
callback = maybeCallback(callback)
fs.open path, "r+", (er, fd) ->
return callback(er) if er
req = new FSReqWrap()
req.oncomplete = ftruncateCb = (er) ->
fs.close fd, (er2) ->
callback er or er2
return
return
binding.ftruncate fd, len, req
return
return
fs.truncateSync = (path, len) ->
return fs.ftruncateSync(path, len) if util.isNumber(path)
len = 0 if util.isUndefined(len)
fd = fs.openSync(path, "r+")
try
ret = fs.ftruncateSync(fd, len)
finally
fs.closeSync fd
ret
fs.ftruncate = (fd, len, callback) ->
if util.isFunction(len)
callback = len
len = 0
else len = 0 if util.isUndefined(len)
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.ftruncate fd, len, req
return
fs.ftruncateSync = (fd, len) ->
len = 0 if util.isUndefined(len)
binding.ftruncate fd, len
fs.rmdir = (path, callback) ->
callback = maybeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.rmdir pathModule._makeLong(path), req
return
fs.rmdirSync = (path) ->
nullCheck path
binding.rmdir pathModule._makeLong(path)
fs.fdatasync = (fd, callback) ->
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.fdatasync fd, req
return
fs.fdatasyncSync = (fd) ->
binding.fdatasync fd
fs.fsync = (fd, callback) ->
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.fsync fd, req
return
fs.fsyncSync = (fd) ->
binding.fsync fd
fs.mkdir = (path, mode, callback) ->
callback = mode if util.isFunction(mode)
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.mkdir pathModule._makeLong(path), modeNum(mode, 511), req
return
fs.mkdirSync = (path, mode) ->
nullCheck path
binding.mkdir pathModule._makeLong(path), modeNum(mode, 511)
fs.readdir = (path, callback) ->
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.readdir pathModule._makeLong(path), req
return
fs.readdirSync = (path) ->
nullCheck path
binding.readdir pathModule._makeLong(path)
fs.fstat = (fd, callback) ->
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.fstat fd, req
return
fs.lstat = (path, callback) ->
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.lstat pathModule._makeLong(path), req
return
fs.stat = (path, callback) ->
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.stat pathModule._makeLong(path), req
return
fs.fstatSync = (fd) ->
binding.fstat fd
fs.lstatSync = (path) ->
nullCheck path
binding.lstat pathModule._makeLong(path)
fs.statSync = (path) ->
nullCheck path
binding.stat pathModule._makeLong(path)
fs.readlink = (path, callback) ->
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.readlink pathModule._makeLong(path), req
return
fs.readlinkSync = (path) ->
nullCheck path
binding.readlink pathModule._makeLong(path)
fs.symlink = (destination, path, type_, callback) ->
type = ((if util.isString(type_) then type_ else null))
callback = makeCallback(arguments[arguments.length - 1])
return unless nullCheck(destination, callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.symlink preprocessSymlinkDestination(destination, type, path), pathModule._makeLong(path), type, req
return
fs.symlinkSync = (destination, path, type) ->
type = ((if util.isString(type) then type else null))
nullCheck destination
nullCheck path
binding.symlink preprocessSymlinkDestination(destination, type, path), pathModule._makeLong(path), type
fs.link = (srcpath, dstpath, callback) ->
callback = makeCallback(callback)
return unless nullCheck(srcpath, callback)
return unless nullCheck(dstpath, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.link pathModule._makeLong(srcpath), pathModule._makeLong(dstpath), req
return
fs.linkSync = (srcpath, dstpath) ->
nullCheck srcpath
nullCheck dstpath
binding.link pathModule._makeLong(srcpath), pathModule._makeLong(dstpath)
fs.unlink = (path, callback) ->
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.unlink pathModule._makeLong(path), req
return
fs.unlinkSync = (path) ->
nullCheck path
binding.unlink pathModule._makeLong(path)
fs.fchmod = (fd, mode, callback) ->
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.fchmod fd, modeNum(mode), req
return
fs.fchmodSync = (fd, mode) ->
binding.fchmod fd, modeNum(mode)
if constants.hasOwnProperty("O_SYMLINK")
fs.lchmod = (path, mode, callback) ->
callback = maybeCallback(callback)
fs.open path, constants.O_WRONLY | constants.O_SYMLINK, (err, fd) ->
if err
callback err
return
fs.fchmod fd, mode, (err) ->
fs.close fd, (err2) ->
callback err or err2
return
return
return
return
fs.lchmodSync = (path, mode) ->
fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK)
err = undefined
err2 = undefined
try
ret = fs.fchmodSync(fd, mode)
catch er
err = er
try
fs.closeSync fd
catch er
err2 = er
throw (err or err2) if err or err2
ret
fs.chmod = (path, mode, callback) ->
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.chmod pathModule._makeLong(path), modeNum(mode), req
return
fs.chmodSync = (path, mode) ->
nullCheck path
binding.chmod pathModule._makeLong(path), modeNum(mode)
if constants.hasOwnProperty("O_SYMLINK")
fs.lchown = (path, uid, gid, callback) ->
callback = maybeCallback(callback)
fs.open path, constants.O_WRONLY | constants.O_SYMLINK, (err, fd) ->
if err
callback err
return
fs.fchown fd, uid, gid, callback
return
return
fs.lchownSync = (path, uid, gid) ->
fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK)
fs.fchownSync fd, uid, gid
fs.fchown = (fd, uid, gid, callback) ->
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.fchown fd, uid, gid, req
return
fs.fchownSync = (fd, uid, gid) ->
binding.fchown fd, uid, gid
fs.chown = (path, uid, gid, callback) ->
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.chown pathModule._makeLong(path), uid, gid, req
return
fs.chownSync = (path, uid, gid) ->
nullCheck path
binding.chown pathModule._makeLong(path), uid, gid
fs._toUnixTimestamp = toUnixTimestamp
fs.utimes = (path, atime, mtime, callback) ->
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.utimes pathModule._makeLong(path), toUnixTimestamp(atime), toUnixTimestamp(mtime), req
return
fs.utimesSync = (path, atime, mtime) ->
nullCheck path
atime = toUnixTimestamp(atime)
mtime = toUnixTimestamp(mtime)
binding.utimes pathModule._makeLong(path), atime, mtime
return
fs.futimes = (fd, atime, mtime, callback) ->
atime = toUnixTimestamp(atime)
mtime = toUnixTimestamp(mtime)
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.futimes fd, atime, mtime, req
return
fs.futimesSync = (fd, atime, mtime) ->
atime = toUnixTimestamp(atime)
mtime = toUnixTimestamp(mtime)
binding.futimes fd, atime, mtime
return
fs.writeFile = (path, data, options, callback) ->
callback = maybeCallback(arguments[arguments.length - 1])
if util.isFunction(options) or not options
options =
encoding: "utf8"
mode: 438
flag: "w"
else if util.isString(options)
options =
encoding: options
mode: 438
flag: "w"
else throw new TypeError("Bad arguments") unless util.isObject(options)
assertEncoding options.encoding
flag = options.flag or "w"
fs.open path, flag, options.mode, (openErr, fd) ->
if openErr
callback openErr if callback
else
buffer = (if util.isBuffer(data) then data else new Buffer("" + data, options.encoding or "utf8"))
position = (if /a/.test(flag) then null else 0)
writeAll fd, buffer, 0, buffer.length, position, callback
return
return
fs.writeFileSync = (path, data, options) ->
unless options
options =
encoding: "utf8"
mode: 438
flag: "w"
else if util.isString(options)
options =
encoding: options
mode: 438
flag: "w"
else throw new TypeError("Bad arguments") unless util.isObject(options)
assertEncoding options.encoding
flag = options.flag or "w"
fd = fs.openSync(path, flag, options.mode)
data = new Buffer("" + data, options.encoding or "utf8") unless util.isBuffer(data)
written = 0
length = data.length
position = (if /a/.test(flag) then null else 0)
try
while written < length
written += fs.writeSync(fd, data, written, length - written, position)
position += written
finally
fs.closeSync fd
return
fs.appendFile = (path, data, options, callback_) ->
callback = maybeCallback(arguments[arguments.length - 1])
if util.isFunction(options) or not options
options =
encoding: "utf8"
mode: 438
flag: "a"
else if util.isString(options)
options =
encoding: options
mode: 438
flag: "a"
else throw new TypeError("Bad arguments") unless util.isObject(options)
unless options.flag
options = util._extend(
flag: "a"
, options)
fs.writeFile path, data, options, callback
return
fs.appendFileSync = (path, data, options) ->
unless options
options =
encoding: "utf8"
mode: 438
flag: "a"
else if util.isString(options)
options =
encoding: options
mode: 438
flag: "a"
else throw new TypeError("Bad arguments") unless util.isObject(options)
unless options.flag
options = util._extend(
flag: "a"
, options)
fs.writeFileSync path, data, options
return
util.inherits FSWatcher, EventEmitter
FSWatcher::start = (filename, persistent, recursive) ->
nullCheck filename
err = @_handle.start(pathModule._makeLong(filename), persistent, recursive)
if err
@_handle.close()
throw errnoException(err, "watch")
return
FSWatcher::close = ->
@_handle.close()
return
fs.watch = (filename) ->
nullCheck filename
watcher = undefined
options = undefined
listener = undefined
if util.isObject(arguments[1])
options = arguments[1]
listener = arguments[2]
else
options = {}
listener = arguments[1]
options.persistent = true if util.isUndefined(options.persistent)
options.recursive = false if util.isUndefined(options.recursive)
watcher = new FSWatcher()
watcher.start filename, options.persistent, options.recursive
watcher.addListener "change", listener if listener
watcher
util.inherits StatWatcher, EventEmitter
StatWatcher::start = (filename, persistent, interval) ->
nullCheck filename
@_handle.start pathModule._makeLong(filename), persistent, interval
return
StatWatcher::stop = ->
@_handle.stop()
return
statWatchers = {}
fs.watchFile = (filename) ->
nullCheck filename
filename = pathModule.resolve(filename)
stat = undefined
listener = undefined
options =
interval: 5007
persistent: true
if util.isObject(arguments[1])
options = util._extend(options, arguments[1])
listener = arguments[2]
else
listener = arguments[1]
throw new Error("watchFile requires a listener function") unless listener
if inStatWatchers(filename)
stat = statWatchers[filename]
else
stat = statWatchers[filename] = new StatWatcher()
stat.start filename, options.persistent, options.interval
stat.addListener "change", listener
stat
fs.unwatchFile = (filename, listener) ->
nullCheck filename
filename = pathModule.resolve(filename)
return unless inStatWatchers(filename)
stat = statWatchers[filename]
if util.isFunction(listener)
stat.removeListener "change", listener
else
stat.removeAllListeners "change"
if EventEmitter.listenerCount(stat, "change") is 0
stat.stop()
statWatchers[filename] = `undefined`
return
if isWindows
nextPartRe = /(.*?)(?:[\/\\]+|$)/g
else
nextPartRe = /(.*?)(?:[\/]+|$)/g
if isWindows
splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/
else
splitRootRe = /^[\/]*/
fs.realpathSync = realpathSync = (p, cache) ->
start = ->
m = splitRootRe.exec(p)
pos = m[0].length
current = m[0]
base = m[0]
previous = ""
if isWindows and not knownHard[base]
fs.lstatSync base
knownHard[base] = true
return
p = pathModule.resolve(p)
return cache[p] if cache and Object::hasOwnProperty.call(cache, p)
original = p
seenLinks = {}
knownHard = {}
pos = undefined
current = undefined
base = undefined
previous = undefined
start()
while pos < p.length
nextPartRe.lastIndex = pos
result = nextPartRe.exec(p)
previous = current
current += result[0]
base = previous + result[1]
pos = nextPartRe.lastIndex
continue if knownHard[base] or (cache and cache[base] is base)
resolvedLink = undefined
if cache and Object::hasOwnProperty.call(cache, base)
resolvedLink = cache[base]
else
stat = fs.lstatSync(base)
unless stat.isSymbolicLink()
knownHard[base] = true
cache[base] = base if cache
continue
linkTarget = null
unless isWindows
id = stat.dev.toString(32) + ":" + stat.ino.toString(32)
linkTarget = seenLinks[id] if seenLinks.hasOwnProperty(id)
if util.isNull(linkTarget)
fs.statSync base
linkTarget = fs.readlinkSync(base)
resolvedLink = pathModule.resolve(previous, linkTarget)
cache[base] = resolvedLink if cache
seenLinks[id] = linkTarget unless isWindows
p = pathModule.resolve(resolvedLink, p.slice(pos))
start()
cache[original] = p if cache
p
fs.realpath = realpath = (p, cache, cb) ->
start = ->
m = splitRootRe.exec(p)
pos = m[0].length
current = m[0]
base = m[0]
previous = ""
if isWindows and not knownHard[base]
fs.lstat base, (err) ->
return cb(err) if err
knownHard[base] = true
LOOP()
return
else
process.nextTick LOOP
return
LOOP = ->
if pos >= p.length
cache[original] = p if cache
return cb(null, p)
nextPartRe.lastIndex = pos
result = nextPartRe.exec(p)
previous = current
current += result[0]
base = previous + result[1]
pos = nextPartRe.lastIndex
return process.nextTick(LOOP) if knownHard[base] or (cache and cache[base] is base)
return gotResolvedLink(cache[base]) if cache and Object::hasOwnProperty.call(cache, base)
fs.lstat base, gotStat
gotStat = (err, stat) ->
return cb(err) if err
unless stat.isSymbolicLink()
knownHard[base] = true
cache[base] = base if cache
return process.nextTick(LOOP)
unless isWindows
id = stat.dev.toString(32) + ":" + stat.ino.toString(32)
return gotTarget(null, seenLinks[id], base) if seenLinks.hasOwnProperty(id)
fs.stat base, (err) ->
return cb(err) if err
fs.readlink base, (err, target) ->
seenLinks[id] = target unless isWindows
gotTarget err, target
return
return
return
gotTarget = (err, target, base) ->
return cb(err) if err
resolvedLink = pathModule.resolve(previous, target)
cache[base] = resolvedLink if cache
gotResolvedLink resolvedLink
return
gotResolvedLink = (resolvedLink) ->
p = pathModule.resolve(resolvedLink, p.slice(pos))
start()
return
unless util.isFunction(cb)
cb = maybeCallback(cache)
cache = null
p = pathModule.resolve(p)
return process.nextTick(cb.bind(null, null, cache[p])) if cache and Object::hasOwnProperty.call(cache, p)
original = p
seenLinks = {}
knownHard = {}
pos = undefined
current = undefined
base = undefined
previous = undefined
start()
return
pool = undefined
fs.createReadStream = (path, options) ->
new ReadStream(path, options)
util.inherits ReadStream, Readable
fs.ReadStream = ReadStream
fs.FileReadStream = fs.ReadStream
ReadStream::open = ->
self = this
fs.open @path, @flags, @mode, (er, fd) ->
if er
self.destroy() if self.autoClose
self.emit "error", er
return
self.fd = fd
self.emit "open", fd
self.read()
return
return
ReadStream::_read = (n) ->
onread = (er, bytesRead) ->
if er
self.destroy() if self.autoClose
self.emit "error", er
else
b = null
b = thisPool.slice(start, start + bytesRead) if bytesRead > 0
self.push b
return
unless util.isNumber(@fd)
return @once("open", ->
@_read n
return
)
return if @destroyed
if not pool or pool.length - pool.used < kMinPoolSpace
pool = null
allocNewPool @_readableState.highWaterMark
thisPool = pool
toRead = Math.min(pool.length - pool.used, n)
start = pool.used
toRead = Math.min(@end - @pos + 1, toRead) unless util.isUndefined(@pos)
return @push(null) if toRead <= 0
self = this
fs.read @fd, pool, pool.used, toRead, @pos, onread
@pos += toRead unless util.isUndefined(@pos)
pool.used += toRead
return
ReadStream::destroy = ->
return if @destroyed
@destroyed = true
@close() if util.isNumber(@fd)
return
ReadStream::close = (cb) ->
close = (fd) ->
fs.close fd or self.fd, (er) ->
if er
self.emit "error", er
else
self.emit "close"
return
self.fd = null
return
self = this
@once "close", cb if cb
if @closed or not util.isNumber(@fd)
unless util.isNumber(@fd)
@once "open", close
return
return process.nextTick(@emit.bind(this, "close"))
@closed = true
close()
return
fs.createWriteStream = (path, options) ->
new WriteStream(path, options)
util.inherits WriteStream, Writable
fs.WriteStream = WriteStream
fs.FileWriteStream = fs.WriteStream
WriteStream::open = ->
fs.open @path, @flags, @mode, ((er, fd) ->
if er
@destroy()
@emit "error", er
return
@fd = fd
@emit "open", fd
return
).bind(this)
return
WriteStream::_write = (data, encoding, cb) ->
return @emit("error", new Error("Invalid data")) unless util.isBuffer(data)
unless util.isNumber(@fd)
return @once("open", ->
@_write data, encoding, cb
return
)
self = this
fs.write @fd, data, 0, data.length, @pos, (er, bytes) ->
if er
self.destroy()
return cb(er)
self.bytesWritten += bytes
cb()
return
@pos += data.length unless util.isUndefined(@pos)
return
WriteStream::destroy = ReadStream::destroy
WriteStream::close = ReadStream::close
WriteStream::destroySoon = WriteStream::end
util.inherits SyncWriteStream, Stream
# Export
fs.SyncWriteStream = SyncWriteStream
SyncWriteStream::write = (data, arg1, arg2) ->
encoding = undefined
cb = undefined
# parse arguments
if arg1
if util.isString(arg1)
encoding = arg1
cb = arg2
else if util.isFunction(arg1)
cb = arg1
else
throw new Error("bad arg")
assertEncoding encoding
# Change strings to buffers. SLOW
data = new Buffer(data, encoding) if util.isString(data)
fs.writeSync @fd, data, 0, data.length
process.nextTick cb if cb
true
SyncWriteStream::end = (data, arg1, arg2) ->
@write data, arg1, arg2 if data
@destroy()
return
SyncWriteStream::destroy = ->
fs.closeSync @fd if @autoClose
@fd = null
@emit "close"
true
SyncWriteStream::destroySoon = SyncWriteStream::destroy
| 75761 | # 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.
# Maintainers, keep in mind that octal literals are not allowed
# in strict mode. Use the decimal value and add a comment with
# the octal value. Example:
#
# var mode = 438; /* mode=0666 */
rethrow = ->
# Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
# is fairly slow to generate.
if DEBUG
backtrace = new Error
return (err) ->
if err
backtrace.stack = err.name + ": " + err.message + backtrace.stack.substr(backtrace.name.length)
err = backtrace
throw err
return
(err) ->
throw err if err # Forgot a callback but don't know where? Use NODE_DEBUG=fs
return
maybeCallback = (cb) ->
(if util.isFunction(cb) then cb else rethrow())
# Ensure that callbacks run in the global context. Only use this function
# for callbacks that are passed to the binding layer, callbacks that are
# invoked from JS already run in the proper scope.
makeCallback = (cb) ->
return rethrow() unless util.isFunction(cb)
->
cb.apply null, arguments
assertEncoding = (encoding) ->
throw new Error("Unknown encoding: " + encoding) if encoding and not Buffer.isEncoding(encoding)
return
nullCheck = (path, callback) ->
if ("" + path).indexOf("\u0000") isnt -1
er = new Error("Path must be a string without null bytes.")
throw er unless callback
process.nextTick ->
callback er
return
return false
true
# Static method to set the stats properties on a Stats object.
# Create a C++ binding to the function which creates a Stats object.
# first, stat the file, so we know the size.
# single buffer with file data
# list for when size is unknown
#=0666
# the kernel lies about many files.
# Go ahead and try to read some bytes.
# unknown size, just read until we don't get bytes.
# collected the data into the buffers list.
#=0666
# single buffer with file data
# list for when size is unknown
# the kernel lies about many files.
# Go ahead and try to read some bytes.
# data was collected into the buffers list.
# Used by binding.open and friends
stringToFlags = (flag) ->
# Only mess with strings
return flag unless util.isString(flag)
switch flag
when "r"
return O_RDONLY
# fall through
when "rs", "sr"
return O_RDONLY | O_SYNC
when "r+"
return O_RDWR
# fall through
when "rs+", "sr+"
return O_RDWR | O_SYNC
when "w"
return O_TRUNC | O_CREAT | O_WRONLY
# fall through
when "wx", "xw"
return O_TRUNC | O_CREAT | O_WRONLY | O_EXCL
when "w+"
return O_TRUNC | O_CREAT | O_RDWR
# fall through
when "wx+", "xw+"
return O_TRUNC | O_CREAT | O_RDWR | O_EXCL
when "a"
return O_APPEND | O_CREAT | O_WRONLY
# fall through
when "ax", "xa"
return O_APPEND | O_CREAT | O_WRONLY | O_EXCL
when "a+"
return O_APPEND | O_CREAT | O_RDWR
# fall through
when "ax+", "xa+"
return O_APPEND | O_CREAT | O_RDWR | O_EXCL
throw new Error("Unknown file open flag: " + flag)return
# exported but hidden, only used by test/simple/test-fs-open-flags.js
# Yes, the follow could be easily DRYed up but I provide the explicit
# list to make the arguments clear.
modeNum = (m, def) ->
return m if util.isNumber(m)
return parseInt(m, 8) if util.isString(m)
return modeNum(def) if def
`undefined`
#=0666
#=0666
# legacy string interface (fd, length, position, encoding, callback)
# Retain a reference to buffer so that it can't be GC'ed too soon.
# legacy string interface (fd, length, position, encoding, callback)
# usage:
# fs.write(fd, buffer, offset, length[, position], callback);
# OR
# fs.write(fd, string[, position[, encoding]], callback);
# Retain a reference to buffer so that it can't be GC'ed too soon.
# retain reference to string in case it's external
# if no position is passed then assume null
# usage:
# fs.writeSync(fd, buffer, offset, length[, position]);
# OR
# fs.writeSync(fd, string[, position[, encoding]]);
# legacy
# allow error to be thrown, but still close fd.
#=0777
#=0777
preprocessSymlinkDestination = (path, type, linkPath) ->
unless isWindows
# No preprocessing is needed on Unix.
path
else if type is "junction"
# Junctions paths need to be absolute and \\?\-prefixed.
# A relative target is relative to the link's parent directory.
path = pathModule.resolve(linkPath, "..", path)
pathModule._makeLong path
else
# Windows symlinks don't tolerate forward slashes.
("" + path).replace /\//g, "\\"
# prefer to return the chmod error, if one occurs,
# but still try to close, and report closing errors if they occur.
# prefer to return the chmod error, if one occurs,
# but still try to close, and report closing errors if they occur.
# converts Date or number to a fractional UNIX timestamp
toUnixTimestamp = (time) ->
return time if util.isNumber(time)
# convert to 123.456 UNIX timestamp
return time.getTime() / 1000 if util.isDate(time)
throw new Error("Cannot parse time: " + time)return
# exported for unit tests, not for public consumption
writeAll = (fd, buffer, offset, length, position, callback) ->
callback = maybeCallback(arguments[arguments.length - 1])
# write(fd, buffer, offset, length, position, callback)
fs.write fd, buffer, offset, length, position, (writeErr, written) ->
if writeErr
fs.close fd, ->
callback writeErr if callback
return
else
if written is length
fs.close fd, callback
else
offset += written
length -= written
position += written
writeAll fd, buffer, offset, length, position, callback
return
return
#=0666
#=0666
#=0666
#=0666
FSWatcher = ->
EventEmitter.call this
self = this
FSEvent = process.binding("fs_event_wrap").FSEvent
@_handle = new FSEvent()
@_handle.owner = this
@_handle.onchange = (status, event, filename) ->
if status < 0
self._handle.close()
self.emit "error", errnoException(status, "watch")
else
self.emit "change", event, filename
return
return
# Stat Change Watchers
StatWatcher = ->
EventEmitter.call this
self = this
@_handle = new binding.StatWatcher()
# uv_fs_poll is a little more powerful than ev_stat but we curb it for
# the sake of backwards compatibility
oldStatus = -1
@_handle.onchange = (current, previous, newStatus) ->
return if oldStatus is -1 and newStatus is -1 and current.nlink is previous.nlink
oldStatus = newStatus
self.emit "change", current, previous
return
@_handle.onstop = ->
self.emit "stop"
return
return
inStatWatchers = (filename) ->
Object::hasOwnProperty.call(statWatchers, filename) and statWatchers[filename]
# Poll interval in milliseconds. 5007 is what libev used to use. It's
# a little on the slow side but let's stick with it for now to keep
# behavioral changes to a minimum.
# Regexp that finds the next partion of a (partial) path
# result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
# Regex to find the device root, including trailing slash. E.g. 'c:\\'.
# make p is absolute
# current character position in p
# the partial path so far, including a trailing slash if any
# the partial path without a trailing slash (except when pointing at a root)
# the partial path scanned in the previous round, with slash
# Skip over roots
# On windows, check that the root exists. On unix there is no need.
# walk down the path, swapping out linked pathparts for their real
# values
# NB: p.length changes.
# find the next part
# continue if not a symlink
# some known symbolic link. no need to stat again.
# read the link if it wasn't read before
# dev/ino always return 0 on windows, so skip the check.
# track this, if given a cache.
# resolve the link, then start over
# make p is absolute
# current character position in p
# the partial path so far, including a trailing slash if any
# the partial path without a trailing slash (except when pointing at a root)
# the partial path scanned in the previous round, with slash
# Skip over roots
# On windows, check that the root exists. On unix there is no need.
# walk down the path, swapping out linked pathparts for their real
# values
# stop if scanned past end of path
# find the next part
# continue if not a symlink
# known symbolic link. no need to stat again.
# if not a symlink, skip to the next path part
# stat & read the link if not read before
# call gotTarget as soon as the link target is known
# dev/ino always return 0 on windows, so skip the check.
# resolve the link, then start over
allocNewPool = (poolSize) ->
pool = new Buffer(poolSize)
pool.used = 0
return
ReadStream = (path, options) ->
return new ReadStream(path, options) unless this instanceof ReadStream
# a little bit bigger buffer and water marks by default
options = util._extend(
highWaterMark: 64 * 1024
, options or {})
Readable.call this, options
@path = path
@fd = (if options.hasOwnProperty("fd") then options.fd else null)
@flags = (if options.hasOwnProperty("flags") then options.flags else "r")
@mode = (if options.hasOwnProperty("mode") then options.mode else 438) #=0666
@start = (if options.hasOwnProperty("start") then options.start else `undefined`)
@end = (if options.hasOwnProperty("end") then options.end else `undefined`)
@autoClose = (if options.hasOwnProperty("autoClose") then options.autoClose else true)
@pos = `undefined`
unless util.isUndefined(@start)
throw TypeError("start must be a Number") unless util.isNumber(@start)
if util.isUndefined(@end)
@end = Infinity
else throw TypeError("end must be a Number") unless util.isNumber(@end)
throw new Error("start must be <= end") if @start > @end
@pos = @start
@open() unless util.isNumber(@fd)
@on "end", ->
@destroy() if @autoClose
return
return
# support the legacy name
# start the flow of data.
# discard the old pool.
# Grab another reference to the pool in the case that while we're
# in the thread pool another read() finishes up the pool, and
# allocates a new one.
# already read everything we were supposed to read!
# treat as EOF.
# the actual read.
# move the pool positions, and internal position for reading.
WriteStream = (path, options) ->
return new WriteStream(path, options) unless this instanceof WriteStream
options = options or {}
Writable.call this, options
@path = path
@fd = null
@fd = (if options.hasOwnProperty("fd") then options.fd else null)
@flags = (if options.hasOwnProperty("flags") then options.flags else "w")
@mode = (if options.hasOwnProperty("mode") then options.mode else 438) #=0666
@start = (if options.hasOwnProperty("start") then options.start else `undefined`)
@pos = `undefined`
@bytesWritten = 0
unless util.isUndefined(@start)
throw TypeError("start must be a Number") unless util.isNumber(@start)
throw new Error("start must be >= zero") if @start < 0
@pos = @start
@open() unless util.isNumber(@fd)
# dispose on finish.
@once "finish", @close
return
# support the legacy name
# There is no shutdown() for files.
# SyncWriteStream is internal. DO NOT USE.
# Temporary hack for process.stdout and process.stderr when piped to files.
SyncWriteStream = (fd, options) ->
Stream.call this
options = options or {}
@fd = fd
@writable = true
@readable = false
@autoClose = (if options.hasOwnProperty("autoClose") then options.autoClose else true)
return
"use strict"
util = require("util")
pathModule = require("path")
binding = process.binding("fs")
constants = process.binding("constants")
fs = exports
Stream = require("stream").Stream
EventEmitter = require("events").EventEmitter
FSReqWrap = binding.FSReqWrap
Readable = Stream.Readable
Writable = Stream.Writable
kMinPoolSpace = 128
kMaxLength = require("smalloc").kMaxLength
O_APPEND = constants.O_APPEND or 0
O_CREAT = constants.O_CREAT or 0
O_EXCL = constants.O_EXCL or 0
O_RDONLY = constants.O_RDONLY or 0
O_RDWR = constants.O_RDWR or 0
O_SYNC = constants.O_SYNC or 0
O_TRUNC = constants.O_TRUNC or 0
O_WRONLY = constants.O_WRONLY or 0
F_OK = constants.F_OK or 0
R_OK = constants.R_OK or 0
W_OK = constants.W_OK or 0
X_OK = constants.X_OK or 0
isWindows = process.platform is "win32"
DEBUG = process.env.NODE_DEBUG and /fs/.test(process.env.NODE_DEBUG)
errnoException = util._errnoException
fs.Stats = (dev, mode, nlink, uid, gid, rdev, blksize, ino, size, blocks, atim_msec, mtim_msec, ctim_msec, birthtim_msec) ->
@dev = dev
@mode = mode
@nlink = nlink
@uid = uid
@gid = gid
@rdev = rdev
@blksize = blksize
@ino = ino
@size = size
@blocks = blocks
@atime = new Date(atim_msec)
@mtime = new Date(mtim_msec)
@ctime = new Date(ctim_msec)
@birthtime = new Date(birthtim_msec)
return
binding.FSInitialize fs.Stats
fs.Stats::_checkModeProperty = (property) ->
(@mode & constants.S_IFMT) is property
fs.Stats::isDirectory = ->
@_checkModeProperty constants.S_IFDIR
fs.Stats::isFile = ->
@_checkModeProperty constants.S_IFREG
fs.Stats::isBlockDevice = ->
@_checkModeProperty constants.S_IFBLK
fs.Stats::isCharacterDevice = ->
@_checkModeProperty constants.S_IFCHR
fs.Stats::isSymbolicLink = ->
@_checkModeProperty constants.S_IFLNK
fs.Stats::isFIFO = ->
@_checkModeProperty constants.S_IFIFO
fs.Stats::isSocket = ->
@_checkModeProperty constants.S_IFSOCK
fs.F_OK = F_OK
fs.R_OK = R_OK
fs.W_OK = W_OK
fs.X_OK = X_OK
fs.access = (path, mode, callback) ->
return unless nullCheck(path, callback)
if typeof mode is "function"
callback = mode
mode = F_OK
else throw new TypeError("callback must be a function") if typeof callback isnt "function"
mode = mode | 0
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.access pathModule._makeLong(path), mode, req
return
fs.accessSync = (path, mode) ->
nullCheck path
if mode is `undefined`
mode = F_OK
else
mode = mode | 0
binding.access pathModule._makeLong(path), mode
return
fs.exists = (path, callback) ->
cb = (err, stats) ->
callback (if err then false else true) if callback
return
return unless nullCheck(path, cb)
req = new FSReqWrap()
req.oncomplete = cb
binding.stat pathModule._makeLong(path), req
return
fs.existsSync = (path) ->
try
nullCheck path
binding.stat pathModule._makeLong(path)
return true
catch e
return false
return
fs.readFile = (path, options, callback_) ->
read = ->
if size is 0
buffer = new Buffer(8192)
fs.read fd, buffer, 0, 8192, -1, afterRead
else
fs.read fd, buffer, pos, size - pos, -1, afterRead
return
afterRead = (er, bytesRead) ->
if er
return fs.close(fd, (er2) ->
callback er
)
return close() if bytesRead is 0
pos += bytesRead
if size isnt 0
if pos is size
close()
else
read()
else
buffers.push buffer.slice(0, bytesRead)
read()
return
close = ->
fs.close fd, (er) ->
if size is 0
buffer = Buffer.concat(buffers, pos)
else buffer = buffer.slice(0, pos) if pos < size
buffer = buffer.toString(encoding) if encoding
callback er, buffer
return
callback = maybeCallback(arguments[arguments.length - 1])
if util.isFunction(options) or not options
options =
encoding: null
flag: "r"
else if util.isString(options)
options =
encoding: options
flag: "r"
else throw new TypeError("Bad arguments") unless util.isObject(options)
encoding = options.encoding
assertEncoding encoding
size = undefined
buffer = undefined
buffers = undefined
pos = 0
fd = undefined
flag = options.flag or "r"
fs.open path, flag, 438, (er, fd_) ->
return callback(er) if er
fd = fd_
fs.fstat fd, (er, st) ->
if er
return fs.close(fd, ->
callback er
return
)
size = st.size
if size is 0
buffers = []
return read()
if size > kMaxLength
err = new RangeError("File size is greater than possible Buffer: " + "0x3FFFFFFF bytes")
return fs.close(fd, ->
callback err
return
)
buffer = new Buffer(size)
read()
return
return
return
fs.readFileSync = (path, options) ->
unless options
options =
encoding: null
flag: "r"
else if util.isString(options)
options =
encoding: options
flag: "r"
else throw new TypeError("Bad arguments") unless util.isObject(options)
encoding = options.encoding
assertEncoding encoding
flag = options.flag or "r"
fd = fs.openSync(path, flag, 438)
size = undefined
threw = true
try
size = fs.fstatSync(fd).size
threw = false
finally
fs.closeSync fd if threw
pos = 0
buffer = undefined
buffers = undefined
if size is 0
buffers = []
else
threw = true
try
buffer = new Buffer(size)
threw = false
finally
fs.closeSync fd if threw
done = false
until done
threw = true
try
if size isnt 0
bytesRead = fs.readSync(fd, buffer, pos, size - pos)
else
buffer = new Buffer(8192)
bytesRead = fs.readSync(fd, buffer, 0, 8192)
buffers.push buffer.slice(0, bytesRead) if bytesRead
threw = false
finally
fs.closeSync fd if threw
pos += bytesRead
done = (bytesRead is 0) or (size isnt 0 and pos >= size)
fs.closeSync fd
if size is 0
buffer = Buffer.concat(buffers, pos)
else buffer = buffer.slice(0, pos) if pos < size
buffer = buffer.toString(encoding) if encoding
buffer
Object.defineProperty exports, "_stringToFlags",
enumerable: false
value: stringToFlags
fs.close = (fd, callback) ->
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.close fd, req
return
fs.closeSync = (fd) ->
binding.close fd
fs.open = (path, flags, mode, callback) ->
callback = makeCallback(arguments[arguments.length - 1])
mode = modeNum(mode, 438)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.open pathModule._makeLong(path), stringToFlags(flags), mode, req
return
fs.openSync = (path, flags, mode) ->
mode = modeNum(mode, 438)
nullCheck path
binding.open pathModule._makeLong(path), stringToFlags(flags), mode
fs.read = (fd, buffer, offset, length, position, callback) ->
wrapper = (err, bytesRead) ->
callback and callback(err, bytesRead or 0, buffer)
return
unless util.isBuffer(buffer)
cb = arguments[4]
encoding = arguments[3]
assertEncoding encoding
position = arguments[2]
length = arguments[1]
buffer = new Buffer(length)
offset = 0
callback = (err, bytesRead) ->
return unless cb
str = (if (bytesRead > 0) then buffer.toString(encoding, 0, bytesRead) else "")
(cb) err, str, bytesRead
return
req = new FSReqWrap()
req.oncomplete = wrapper
binding.read fd, buffer, offset, length, position, req
return
fs.readSync = (fd, buffer, offset, length, position) ->
legacy = false
unless util.isBuffer(buffer)
legacy = true
encoding = arguments[3]
assertEncoding encoding
position = arguments[2]
length = arguments[1]
buffer = new Buffer(length)
offset = 0
r = binding.read(fd, buffer, offset, length, position)
return r unless legacy
str = (if (r > 0) then buffer.toString(encoding, 0, r) else "")
[
str
r
]
fs.write = (fd, buffer, offset, length, position, callback) ->
strWrapper = (err, written) ->
callback err, written or 0, buffer
return
bufWrapper = (err, written) ->
callback err, written or 0, buffer
return
if util.isBuffer(buffer)
if util.isFunction(position)
callback = position
position = null
callback = maybeCallback(callback)
req = new FSReqWrap()
req.oncomplete = strWrapper
return binding.writeBuffer(fd, buffer, offset, length, position, req)
buffer += "" if util.isString(buffer)
unless util.isFunction(position)
if util.isFunction(offset)
position = offset
offset = null
else
position = length
length = "utf8"
callback = maybeCallback(position)
req = new FSReqWrap()
req.oncomplete = bufWrapper
binding.writeString fd, buffer, offset, length, req
fs.writeSync = (fd, buffer, offset, length, position) ->
if util.isBuffer(buffer)
position = null if util.isUndefined(position)
return binding.writeBuffer(fd, buffer, offset, length, position)
buffer += "" unless util.isString(buffer)
offset = null if util.isUndefined(offset)
binding.writeString fd, buffer, offset, length, position
fs.rename = (oldPath, newPath, callback) ->
callback = makeCallback(callback)
return unless nullCheck(oldPath, callback)
return unless nullCheck(newPath, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.rename pathModule._makeLong(oldPath), pathModule._makeLong(newPath), req
return
fs.renameSync = (oldPath, newPath) ->
nullCheck oldPath
nullCheck newPath
binding.rename pathModule._makeLong(oldPath), pathModule._makeLong(newPath)
fs.truncate = (path, len, callback) ->
if util.isNumber(path)
req = new FSReqWrap()
req.oncomplete = callback
return fs.ftruncate(path, len, req)
if util.isFunction(len)
callback = len
len = 0
else len = 0 if util.isUndefined(len)
callback = maybeCallback(callback)
fs.open path, "r+", (er, fd) ->
return callback(er) if er
req = new FSReqWrap()
req.oncomplete = ftruncateCb = (er) ->
fs.close fd, (er2) ->
callback er or er2
return
return
binding.ftruncate fd, len, req
return
return
fs.truncateSync = (path, len) ->
return fs.ftruncateSync(path, len) if util.isNumber(path)
len = 0 if util.isUndefined(len)
fd = fs.openSync(path, "r+")
try
ret = fs.ftruncateSync(fd, len)
finally
fs.closeSync fd
ret
fs.ftruncate = (fd, len, callback) ->
if util.isFunction(len)
callback = len
len = 0
else len = 0 if util.isUndefined(len)
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.ftruncate fd, len, req
return
fs.ftruncateSync = (fd, len) ->
len = 0 if util.isUndefined(len)
binding.ftruncate fd, len
fs.rmdir = (path, callback) ->
callback = maybeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.rmdir pathModule._makeLong(path), req
return
fs.rmdirSync = (path) ->
nullCheck path
binding.rmdir pathModule._makeLong(path)
fs.fdatasync = (fd, callback) ->
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.fdatasync fd, req
return
fs.fdatasyncSync = (fd) ->
binding.fdatasync fd
fs.fsync = (fd, callback) ->
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.fsync fd, req
return
fs.fsyncSync = (fd) ->
binding.fsync fd
fs.mkdir = (path, mode, callback) ->
callback = mode if util.isFunction(mode)
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.mkdir pathModule._makeLong(path), modeNum(mode, 511), req
return
fs.mkdirSync = (path, mode) ->
nullCheck path
binding.mkdir pathModule._makeLong(path), modeNum(mode, 511)
fs.readdir = (path, callback) ->
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.readdir pathModule._makeLong(path), req
return
fs.readdirSync = (path) ->
nullCheck path
binding.readdir pathModule._makeLong(path)
fs.fstat = (fd, callback) ->
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.fstat fd, req
return
fs.lstat = (path, callback) ->
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.lstat pathModule._makeLong(path), req
return
fs.stat = (path, callback) ->
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.stat pathModule._makeLong(path), req
return
fs.fstatSync = (fd) ->
binding.fstat fd
fs.lstatSync = (path) ->
nullCheck path
binding.lstat pathModule._makeLong(path)
fs.statSync = (path) ->
nullCheck path
binding.stat pathModule._makeLong(path)
fs.readlink = (path, callback) ->
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.readlink pathModule._makeLong(path), req
return
fs.readlinkSync = (path) ->
nullCheck path
binding.readlink pathModule._makeLong(path)
fs.symlink = (destination, path, type_, callback) ->
type = ((if util.isString(type_) then type_ else null))
callback = makeCallback(arguments[arguments.length - 1])
return unless nullCheck(destination, callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.symlink preprocessSymlinkDestination(destination, type, path), pathModule._makeLong(path), type, req
return
fs.symlinkSync = (destination, path, type) ->
type = ((if util.isString(type) then type else null))
nullCheck destination
nullCheck path
binding.symlink preprocessSymlinkDestination(destination, type, path), pathModule._makeLong(path), type
fs.link = (srcpath, dstpath, callback) ->
callback = makeCallback(callback)
return unless nullCheck(srcpath, callback)
return unless nullCheck(dstpath, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.link pathModule._makeLong(srcpath), pathModule._makeLong(dstpath), req
return
fs.linkSync = (srcpath, dstpath) ->
nullCheck srcpath
nullCheck dstpath
binding.link pathModule._makeLong(srcpath), pathModule._makeLong(dstpath)
fs.unlink = (path, callback) ->
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.unlink pathModule._makeLong(path), req
return
fs.unlinkSync = (path) ->
nullCheck path
binding.unlink pathModule._makeLong(path)
fs.fchmod = (fd, mode, callback) ->
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.fchmod fd, modeNum(mode), req
return
fs.fchmodSync = (fd, mode) ->
binding.fchmod fd, modeNum(mode)
if constants.hasOwnProperty("O_SYMLINK")
fs.lchmod = (path, mode, callback) ->
callback = maybeCallback(callback)
fs.open path, constants.O_WRONLY | constants.O_SYMLINK, (err, fd) ->
if err
callback err
return
fs.fchmod fd, mode, (err) ->
fs.close fd, (err2) ->
callback err or err2
return
return
return
return
fs.lchmodSync = (path, mode) ->
fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK)
err = undefined
err2 = undefined
try
ret = fs.fchmodSync(fd, mode)
catch er
err = er
try
fs.closeSync fd
catch er
err2 = er
throw (err or err2) if err or err2
ret
fs.chmod = (path, mode, callback) ->
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.chmod pathModule._makeLong(path), modeNum(mode), req
return
fs.chmodSync = (path, mode) ->
nullCheck path
binding.chmod pathModule._makeLong(path), modeNum(mode)
if constants.hasOwnProperty("O_SYMLINK")
fs.lchown = (path, uid, gid, callback) ->
callback = maybeCallback(callback)
fs.open path, constants.O_WRONLY | constants.O_SYMLINK, (err, fd) ->
if err
callback err
return
fs.fchown fd, uid, gid, callback
return
return
fs.lchownSync = (path, uid, gid) ->
fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK)
fs.fchownSync fd, uid, gid
fs.fchown = (fd, uid, gid, callback) ->
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.fchown fd, uid, gid, req
return
fs.fchownSync = (fd, uid, gid) ->
binding.fchown fd, uid, gid
fs.chown = (path, uid, gid, callback) ->
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.chown pathModule._makeLong(path), uid, gid, req
return
fs.chownSync = (path, uid, gid) ->
nullCheck path
binding.chown pathModule._makeLong(path), uid, gid
fs._toUnixTimestamp = toUnixTimestamp
fs.utimes = (path, atime, mtime, callback) ->
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.utimes pathModule._makeLong(path), toUnixTimestamp(atime), toUnixTimestamp(mtime), req
return
fs.utimesSync = (path, atime, mtime) ->
nullCheck path
atime = toUnixTimestamp(atime)
mtime = toUnixTimestamp(mtime)
binding.utimes pathModule._makeLong(path), atime, mtime
return
fs.futimes = (fd, atime, mtime, callback) ->
atime = toUnixTimestamp(atime)
mtime = toUnixTimestamp(mtime)
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.futimes fd, atime, mtime, req
return
fs.futimesSync = (fd, atime, mtime) ->
atime = toUnixTimestamp(atime)
mtime = toUnixTimestamp(mtime)
binding.futimes fd, atime, mtime
return
fs.writeFile = (path, data, options, callback) ->
callback = maybeCallback(arguments[arguments.length - 1])
if util.isFunction(options) or not options
options =
encoding: "utf8"
mode: 438
flag: "w"
else if util.isString(options)
options =
encoding: options
mode: 438
flag: "w"
else throw new TypeError("Bad arguments") unless util.isObject(options)
assertEncoding options.encoding
flag = options.flag or "w"
fs.open path, flag, options.mode, (openErr, fd) ->
if openErr
callback openErr if callback
else
buffer = (if util.isBuffer(data) then data else new Buffer("" + data, options.encoding or "utf8"))
position = (if /a/.test(flag) then null else 0)
writeAll fd, buffer, 0, buffer.length, position, callback
return
return
fs.writeFileSync = (path, data, options) ->
unless options
options =
encoding: "utf8"
mode: 438
flag: "w"
else if util.isString(options)
options =
encoding: options
mode: 438
flag: "w"
else throw new TypeError("Bad arguments") unless util.isObject(options)
assertEncoding options.encoding
flag = options.flag or "w"
fd = fs.openSync(path, flag, options.mode)
data = new Buffer("" + data, options.encoding or "utf8") unless util.isBuffer(data)
written = 0
length = data.length
position = (if /a/.test(flag) then null else 0)
try
while written < length
written += fs.writeSync(fd, data, written, length - written, position)
position += written
finally
fs.closeSync fd
return
fs.appendFile = (path, data, options, callback_) ->
callback = maybeCallback(arguments[arguments.length - 1])
if util.isFunction(options) or not options
options =
encoding: "utf8"
mode: 438
flag: "a"
else if util.isString(options)
options =
encoding: options
mode: 438
flag: "a"
else throw new TypeError("Bad arguments") unless util.isObject(options)
unless options.flag
options = util._extend(
flag: "a"
, options)
fs.writeFile path, data, options, callback
return
fs.appendFileSync = (path, data, options) ->
unless options
options =
encoding: "utf8"
mode: 438
flag: "a"
else if util.isString(options)
options =
encoding: options
mode: 438
flag: "a"
else throw new TypeError("Bad arguments") unless util.isObject(options)
unless options.flag
options = util._extend(
flag: "a"
, options)
fs.writeFileSync path, data, options
return
util.inherits FSWatcher, EventEmitter
FSWatcher::start = (filename, persistent, recursive) ->
nullCheck filename
err = @_handle.start(pathModule._makeLong(filename), persistent, recursive)
if err
@_handle.close()
throw errnoException(err, "watch")
return
FSWatcher::close = ->
@_handle.close()
return
fs.watch = (filename) ->
nullCheck filename
watcher = undefined
options = undefined
listener = undefined
if util.isObject(arguments[1])
options = arguments[1]
listener = arguments[2]
else
options = {}
listener = arguments[1]
options.persistent = true if util.isUndefined(options.persistent)
options.recursive = false if util.isUndefined(options.recursive)
watcher = new FSWatcher()
watcher.start filename, options.persistent, options.recursive
watcher.addListener "change", listener if listener
watcher
util.inherits StatWatcher, EventEmitter
StatWatcher::start = (filename, persistent, interval) ->
nullCheck filename
@_handle.start pathModule._makeLong(filename), persistent, interval
return
StatWatcher::stop = ->
@_handle.stop()
return
statWatchers = {}
fs.watchFile = (filename) ->
nullCheck filename
filename = pathModule.resolve(filename)
stat = undefined
listener = undefined
options =
interval: 5007
persistent: true
if util.isObject(arguments[1])
options = util._extend(options, arguments[1])
listener = arguments[2]
else
listener = arguments[1]
throw new Error("watchFile requires a listener function") unless listener
if inStatWatchers(filename)
stat = statWatchers[filename]
else
stat = statWatchers[filename] = new StatWatcher()
stat.start filename, options.persistent, options.interval
stat.addListener "change", listener
stat
fs.unwatchFile = (filename, listener) ->
nullCheck filename
filename = pathModule.resolve(filename)
return unless inStatWatchers(filename)
stat = statWatchers[filename]
if util.isFunction(listener)
stat.removeListener "change", listener
else
stat.removeAllListeners "change"
if EventEmitter.listenerCount(stat, "change") is 0
stat.stop()
statWatchers[filename] = `undefined`
return
if isWindows
nextPartRe = /(.*?)(?:[\/\\]+|$)/g
else
nextPartRe = /(.*?)(?:[\/]+|$)/g
if isWindows
splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/
else
splitRootRe = /^[\/]*/
fs.realpathSync = realpathSync = (p, cache) ->
start = ->
m = splitRootRe.exec(p)
pos = m[0].length
current = m[0]
base = m[0]
previous = ""
if isWindows and not knownHard[base]
fs.lstatSync base
knownHard[base] = true
return
p = pathModule.resolve(p)
return cache[p] if cache and Object::hasOwnProperty.call(cache, p)
original = p
seenLinks = {}
knownHard = {}
pos = undefined
current = undefined
base = undefined
previous = undefined
start()
while pos < p.length
nextPartRe.lastIndex = pos
result = nextPartRe.exec(p)
previous = current
current += result[0]
base = previous + result[1]
pos = nextPartRe.lastIndex
continue if knownHard[base] or (cache and cache[base] is base)
resolvedLink = undefined
if cache and Object::hasOwnProperty.call(cache, base)
resolvedLink = cache[base]
else
stat = fs.lstatSync(base)
unless stat.isSymbolicLink()
knownHard[base] = true
cache[base] = base if cache
continue
linkTarget = null
unless isWindows
id = stat.dev.toString(32) + ":" + stat.ino.toString(32)
linkTarget = seenLinks[id] if seenLinks.hasOwnProperty(id)
if util.isNull(linkTarget)
fs.statSync base
linkTarget = fs.readlinkSync(base)
resolvedLink = pathModule.resolve(previous, linkTarget)
cache[base] = resolvedLink if cache
seenLinks[id] = linkTarget unless isWindows
p = pathModule.resolve(resolvedLink, p.slice(pos))
start()
cache[original] = p if cache
p
fs.realpath = realpath = (p, cache, cb) ->
start = ->
m = splitRootRe.exec(p)
pos = m[0].length
current = m[0]
base = m[0]
previous = ""
if isWindows and not knownHard[base]
fs.lstat base, (err) ->
return cb(err) if err
knownHard[base] = true
LOOP()
return
else
process.nextTick LOOP
return
LOOP = ->
if pos >= p.length
cache[original] = p if cache
return cb(null, p)
nextPartRe.lastIndex = pos
result = nextPartRe.exec(p)
previous = current
current += result[0]
base = previous + result[1]
pos = nextPartRe.lastIndex
return process.nextTick(LOOP) if knownHard[base] or (cache and cache[base] is base)
return gotResolvedLink(cache[base]) if cache and Object::hasOwnProperty.call(cache, base)
fs.lstat base, gotStat
gotStat = (err, stat) ->
return cb(err) if err
unless stat.isSymbolicLink()
knownHard[base] = true
cache[base] = base if cache
return process.nextTick(LOOP)
unless isWindows
id = stat.dev.toString(32) + ":" + stat.ino.toString(32)
return gotTarget(null, seenLinks[id], base) if seenLinks.hasOwnProperty(id)
fs.stat base, (err) ->
return cb(err) if err
fs.readlink base, (err, target) ->
seenLinks[id] = target unless isWindows
gotTarget err, target
return
return
return
gotTarget = (err, target, base) ->
return cb(err) if err
resolvedLink = pathModule.resolve(previous, target)
cache[base] = resolvedLink if cache
gotResolvedLink resolvedLink
return
gotResolvedLink = (resolvedLink) ->
p = pathModule.resolve(resolvedLink, p.slice(pos))
start()
return
unless util.isFunction(cb)
cb = maybeCallback(cache)
cache = null
p = pathModule.resolve(p)
return process.nextTick(cb.bind(null, null, cache[p])) if cache and Object::hasOwnProperty.call(cache, p)
original = p
seenLinks = {}
knownHard = {}
pos = undefined
current = undefined
base = undefined
previous = undefined
start()
return
pool = undefined
fs.createReadStream = (path, options) ->
new ReadStream(path, options)
util.inherits ReadStream, Readable
fs.ReadStream = ReadStream
fs.FileReadStream = fs.ReadStream
ReadStream::open = ->
self = this
fs.open @path, @flags, @mode, (er, fd) ->
if er
self.destroy() if self.autoClose
self.emit "error", er
return
self.fd = fd
self.emit "open", fd
self.read()
return
return
ReadStream::_read = (n) ->
onread = (er, bytesRead) ->
if er
self.destroy() if self.autoClose
self.emit "error", er
else
b = null
b = thisPool.slice(start, start + bytesRead) if bytesRead > 0
self.push b
return
unless util.isNumber(@fd)
return @once("open", ->
@_read n
return
)
return if @destroyed
if not pool or pool.length - pool.used < kMinPoolSpace
pool = null
allocNewPool @_readableState.highWaterMark
thisPool = pool
toRead = Math.min(pool.length - pool.used, n)
start = pool.used
toRead = Math.min(@end - @pos + 1, toRead) unless util.isUndefined(@pos)
return @push(null) if toRead <= 0
self = this
fs.read @fd, pool, pool.used, toRead, @pos, onread
@pos += toRead unless util.isUndefined(@pos)
pool.used += toRead
return
ReadStream::destroy = ->
return if @destroyed
@destroyed = true
@close() if util.isNumber(@fd)
return
ReadStream::close = (cb) ->
close = (fd) ->
fs.close fd or self.fd, (er) ->
if er
self.emit "error", er
else
self.emit "close"
return
self.fd = null
return
self = this
@once "close", cb if cb
if @closed or not util.isNumber(@fd)
unless util.isNumber(@fd)
@once "open", close
return
return process.nextTick(@emit.bind(this, "close"))
@closed = true
close()
return
fs.createWriteStream = (path, options) ->
new WriteStream(path, options)
util.inherits WriteStream, Writable
fs.WriteStream = WriteStream
fs.FileWriteStream = fs.WriteStream
WriteStream::open = ->
fs.open @path, @flags, @mode, ((er, fd) ->
if er
@destroy()
@emit "error", er
return
@fd = fd
@emit "open", fd
return
).bind(this)
return
WriteStream::_write = (data, encoding, cb) ->
return @emit("error", new Error("Invalid data")) unless util.isBuffer(data)
unless util.isNumber(@fd)
return @once("open", ->
@_write data, encoding, cb
return
)
self = this
fs.write @fd, data, 0, data.length, @pos, (er, bytes) ->
if er
self.destroy()
return cb(er)
self.bytesWritten += bytes
cb()
return
@pos += data.length unless util.isUndefined(@pos)
return
WriteStream::destroy = ReadStream::destroy
WriteStream::close = ReadStream::close
WriteStream::destroySoon = WriteStream::end
util.inherits SyncWriteStream, Stream
# Export
fs.SyncWriteStream = SyncWriteStream
SyncWriteStream::write = (data, arg1, arg2) ->
encoding = undefined
cb = undefined
# parse arguments
if arg1
if util.isString(arg1)
encoding = arg1
cb = arg2
else if util.isFunction(arg1)
cb = arg1
else
throw new Error("bad arg")
assertEncoding encoding
# Change strings to buffers. SLOW
data = new Buffer(data, encoding) if util.isString(data)
fs.writeSync @fd, data, 0, data.length
process.nextTick cb if cb
true
SyncWriteStream::end = (data, arg1, arg2) ->
@write data, arg1, arg2 if data
@destroy()
return
SyncWriteStream::destroy = ->
fs.closeSync @fd if @autoClose
@fd = null
@emit "close"
true
SyncWriteStream::destroySoon = SyncWriteStream::destroy
| 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.
# Maintainers, keep in mind that octal literals are not allowed
# in strict mode. Use the decimal value and add a comment with
# the octal value. Example:
#
# var mode = 438; /* mode=0666 */
rethrow = ->
# Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
# is fairly slow to generate.
if DEBUG
backtrace = new Error
return (err) ->
if err
backtrace.stack = err.name + ": " + err.message + backtrace.stack.substr(backtrace.name.length)
err = backtrace
throw err
return
(err) ->
throw err if err # Forgot a callback but don't know where? Use NODE_DEBUG=fs
return
maybeCallback = (cb) ->
(if util.isFunction(cb) then cb else rethrow())
# Ensure that callbacks run in the global context. Only use this function
# for callbacks that are passed to the binding layer, callbacks that are
# invoked from JS already run in the proper scope.
makeCallback = (cb) ->
return rethrow() unless util.isFunction(cb)
->
cb.apply null, arguments
assertEncoding = (encoding) ->
throw new Error("Unknown encoding: " + encoding) if encoding and not Buffer.isEncoding(encoding)
return
nullCheck = (path, callback) ->
if ("" + path).indexOf("\u0000") isnt -1
er = new Error("Path must be a string without null bytes.")
throw er unless callback
process.nextTick ->
callback er
return
return false
true
# Static method to set the stats properties on a Stats object.
# Create a C++ binding to the function which creates a Stats object.
# first, stat the file, so we know the size.
# single buffer with file data
# list for when size is unknown
#=0666
# the kernel lies about many files.
# Go ahead and try to read some bytes.
# unknown size, just read until we don't get bytes.
# collected the data into the buffers list.
#=0666
# single buffer with file data
# list for when size is unknown
# the kernel lies about many files.
# Go ahead and try to read some bytes.
# data was collected into the buffers list.
# Used by binding.open and friends
stringToFlags = (flag) ->
# Only mess with strings
return flag unless util.isString(flag)
switch flag
when "r"
return O_RDONLY
# fall through
when "rs", "sr"
return O_RDONLY | O_SYNC
when "r+"
return O_RDWR
# fall through
when "rs+", "sr+"
return O_RDWR | O_SYNC
when "w"
return O_TRUNC | O_CREAT | O_WRONLY
# fall through
when "wx", "xw"
return O_TRUNC | O_CREAT | O_WRONLY | O_EXCL
when "w+"
return O_TRUNC | O_CREAT | O_RDWR
# fall through
when "wx+", "xw+"
return O_TRUNC | O_CREAT | O_RDWR | O_EXCL
when "a"
return O_APPEND | O_CREAT | O_WRONLY
# fall through
when "ax", "xa"
return O_APPEND | O_CREAT | O_WRONLY | O_EXCL
when "a+"
return O_APPEND | O_CREAT | O_RDWR
# fall through
when "ax+", "xa+"
return O_APPEND | O_CREAT | O_RDWR | O_EXCL
throw new Error("Unknown file open flag: " + flag)return
# exported but hidden, only used by test/simple/test-fs-open-flags.js
# Yes, the follow could be easily DRYed up but I provide the explicit
# list to make the arguments clear.
modeNum = (m, def) ->
return m if util.isNumber(m)
return parseInt(m, 8) if util.isString(m)
return modeNum(def) if def
`undefined`
#=0666
#=0666
# legacy string interface (fd, length, position, encoding, callback)
# Retain a reference to buffer so that it can't be GC'ed too soon.
# legacy string interface (fd, length, position, encoding, callback)
# usage:
# fs.write(fd, buffer, offset, length[, position], callback);
# OR
# fs.write(fd, string[, position[, encoding]], callback);
# Retain a reference to buffer so that it can't be GC'ed too soon.
# retain reference to string in case it's external
# if no position is passed then assume null
# usage:
# fs.writeSync(fd, buffer, offset, length[, position]);
# OR
# fs.writeSync(fd, string[, position[, encoding]]);
# legacy
# allow error to be thrown, but still close fd.
#=0777
#=0777
preprocessSymlinkDestination = (path, type, linkPath) ->
unless isWindows
# No preprocessing is needed on Unix.
path
else if type is "junction"
# Junctions paths need to be absolute and \\?\-prefixed.
# A relative target is relative to the link's parent directory.
path = pathModule.resolve(linkPath, "..", path)
pathModule._makeLong path
else
# Windows symlinks don't tolerate forward slashes.
("" + path).replace /\//g, "\\"
# prefer to return the chmod error, if one occurs,
# but still try to close, and report closing errors if they occur.
# prefer to return the chmod error, if one occurs,
# but still try to close, and report closing errors if they occur.
# converts Date or number to a fractional UNIX timestamp
toUnixTimestamp = (time) ->
return time if util.isNumber(time)
# convert to 123.456 UNIX timestamp
return time.getTime() / 1000 if util.isDate(time)
throw new Error("Cannot parse time: " + time)return
# exported for unit tests, not for public consumption
writeAll = (fd, buffer, offset, length, position, callback) ->
callback = maybeCallback(arguments[arguments.length - 1])
# write(fd, buffer, offset, length, position, callback)
fs.write fd, buffer, offset, length, position, (writeErr, written) ->
if writeErr
fs.close fd, ->
callback writeErr if callback
return
else
if written is length
fs.close fd, callback
else
offset += written
length -= written
position += written
writeAll fd, buffer, offset, length, position, callback
return
return
#=0666
#=0666
#=0666
#=0666
FSWatcher = ->
EventEmitter.call this
self = this
FSEvent = process.binding("fs_event_wrap").FSEvent
@_handle = new FSEvent()
@_handle.owner = this
@_handle.onchange = (status, event, filename) ->
if status < 0
self._handle.close()
self.emit "error", errnoException(status, "watch")
else
self.emit "change", event, filename
return
return
# Stat Change Watchers
StatWatcher = ->
EventEmitter.call this
self = this
@_handle = new binding.StatWatcher()
# uv_fs_poll is a little more powerful than ev_stat but we curb it for
# the sake of backwards compatibility
oldStatus = -1
@_handle.onchange = (current, previous, newStatus) ->
return if oldStatus is -1 and newStatus is -1 and current.nlink is previous.nlink
oldStatus = newStatus
self.emit "change", current, previous
return
@_handle.onstop = ->
self.emit "stop"
return
return
inStatWatchers = (filename) ->
Object::hasOwnProperty.call(statWatchers, filename) and statWatchers[filename]
# Poll interval in milliseconds. 5007 is what libev used to use. It's
# a little on the slow side but let's stick with it for now to keep
# behavioral changes to a minimum.
# Regexp that finds the next partion of a (partial) path
# result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
# Regex to find the device root, including trailing slash. E.g. 'c:\\'.
# make p is absolute
# current character position in p
# the partial path so far, including a trailing slash if any
# the partial path without a trailing slash (except when pointing at a root)
# the partial path scanned in the previous round, with slash
# Skip over roots
# On windows, check that the root exists. On unix there is no need.
# walk down the path, swapping out linked pathparts for their real
# values
# NB: p.length changes.
# find the next part
# continue if not a symlink
# some known symbolic link. no need to stat again.
# read the link if it wasn't read before
# dev/ino always return 0 on windows, so skip the check.
# track this, if given a cache.
# resolve the link, then start over
# make p is absolute
# current character position in p
# the partial path so far, including a trailing slash if any
# the partial path without a trailing slash (except when pointing at a root)
# the partial path scanned in the previous round, with slash
# Skip over roots
# On windows, check that the root exists. On unix there is no need.
# walk down the path, swapping out linked pathparts for their real
# values
# stop if scanned past end of path
# find the next part
# continue if not a symlink
# known symbolic link. no need to stat again.
# if not a symlink, skip to the next path part
# stat & read the link if not read before
# call gotTarget as soon as the link target is known
# dev/ino always return 0 on windows, so skip the check.
# resolve the link, then start over
allocNewPool = (poolSize) ->
pool = new Buffer(poolSize)
pool.used = 0
return
ReadStream = (path, options) ->
return new ReadStream(path, options) unless this instanceof ReadStream
# a little bit bigger buffer and water marks by default
options = util._extend(
highWaterMark: 64 * 1024
, options or {})
Readable.call this, options
@path = path
@fd = (if options.hasOwnProperty("fd") then options.fd else null)
@flags = (if options.hasOwnProperty("flags") then options.flags else "r")
@mode = (if options.hasOwnProperty("mode") then options.mode else 438) #=0666
@start = (if options.hasOwnProperty("start") then options.start else `undefined`)
@end = (if options.hasOwnProperty("end") then options.end else `undefined`)
@autoClose = (if options.hasOwnProperty("autoClose") then options.autoClose else true)
@pos = `undefined`
unless util.isUndefined(@start)
throw TypeError("start must be a Number") unless util.isNumber(@start)
if util.isUndefined(@end)
@end = Infinity
else throw TypeError("end must be a Number") unless util.isNumber(@end)
throw new Error("start must be <= end") if @start > @end
@pos = @start
@open() unless util.isNumber(@fd)
@on "end", ->
@destroy() if @autoClose
return
return
# support the legacy name
# start the flow of data.
# discard the old pool.
# Grab another reference to the pool in the case that while we're
# in the thread pool another read() finishes up the pool, and
# allocates a new one.
# already read everything we were supposed to read!
# treat as EOF.
# the actual read.
# move the pool positions, and internal position for reading.
WriteStream = (path, options) ->
return new WriteStream(path, options) unless this instanceof WriteStream
options = options or {}
Writable.call this, options
@path = path
@fd = null
@fd = (if options.hasOwnProperty("fd") then options.fd else null)
@flags = (if options.hasOwnProperty("flags") then options.flags else "w")
@mode = (if options.hasOwnProperty("mode") then options.mode else 438) #=0666
@start = (if options.hasOwnProperty("start") then options.start else `undefined`)
@pos = `undefined`
@bytesWritten = 0
unless util.isUndefined(@start)
throw TypeError("start must be a Number") unless util.isNumber(@start)
throw new Error("start must be >= zero") if @start < 0
@pos = @start
@open() unless util.isNumber(@fd)
# dispose on finish.
@once "finish", @close
return
# support the legacy name
# There is no shutdown() for files.
# SyncWriteStream is internal. DO NOT USE.
# Temporary hack for process.stdout and process.stderr when piped to files.
SyncWriteStream = (fd, options) ->
Stream.call this
options = options or {}
@fd = fd
@writable = true
@readable = false
@autoClose = (if options.hasOwnProperty("autoClose") then options.autoClose else true)
return
"use strict"
util = require("util")
pathModule = require("path")
binding = process.binding("fs")
constants = process.binding("constants")
fs = exports
Stream = require("stream").Stream
EventEmitter = require("events").EventEmitter
FSReqWrap = binding.FSReqWrap
Readable = Stream.Readable
Writable = Stream.Writable
kMinPoolSpace = 128
kMaxLength = require("smalloc").kMaxLength
O_APPEND = constants.O_APPEND or 0
O_CREAT = constants.O_CREAT or 0
O_EXCL = constants.O_EXCL or 0
O_RDONLY = constants.O_RDONLY or 0
O_RDWR = constants.O_RDWR or 0
O_SYNC = constants.O_SYNC or 0
O_TRUNC = constants.O_TRUNC or 0
O_WRONLY = constants.O_WRONLY or 0
F_OK = constants.F_OK or 0
R_OK = constants.R_OK or 0
W_OK = constants.W_OK or 0
X_OK = constants.X_OK or 0
isWindows = process.platform is "win32"
DEBUG = process.env.NODE_DEBUG and /fs/.test(process.env.NODE_DEBUG)
errnoException = util._errnoException
fs.Stats = (dev, mode, nlink, uid, gid, rdev, blksize, ino, size, blocks, atim_msec, mtim_msec, ctim_msec, birthtim_msec) ->
@dev = dev
@mode = mode
@nlink = nlink
@uid = uid
@gid = gid
@rdev = rdev
@blksize = blksize
@ino = ino
@size = size
@blocks = blocks
@atime = new Date(atim_msec)
@mtime = new Date(mtim_msec)
@ctime = new Date(ctim_msec)
@birthtime = new Date(birthtim_msec)
return
binding.FSInitialize fs.Stats
fs.Stats::_checkModeProperty = (property) ->
(@mode & constants.S_IFMT) is property
fs.Stats::isDirectory = ->
@_checkModeProperty constants.S_IFDIR
fs.Stats::isFile = ->
@_checkModeProperty constants.S_IFREG
fs.Stats::isBlockDevice = ->
@_checkModeProperty constants.S_IFBLK
fs.Stats::isCharacterDevice = ->
@_checkModeProperty constants.S_IFCHR
fs.Stats::isSymbolicLink = ->
@_checkModeProperty constants.S_IFLNK
fs.Stats::isFIFO = ->
@_checkModeProperty constants.S_IFIFO
fs.Stats::isSocket = ->
@_checkModeProperty constants.S_IFSOCK
fs.F_OK = F_OK
fs.R_OK = R_OK
fs.W_OK = W_OK
fs.X_OK = X_OK
fs.access = (path, mode, callback) ->
return unless nullCheck(path, callback)
if typeof mode is "function"
callback = mode
mode = F_OK
else throw new TypeError("callback must be a function") if typeof callback isnt "function"
mode = mode | 0
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.access pathModule._makeLong(path), mode, req
return
fs.accessSync = (path, mode) ->
nullCheck path
if mode is `undefined`
mode = F_OK
else
mode = mode | 0
binding.access pathModule._makeLong(path), mode
return
fs.exists = (path, callback) ->
cb = (err, stats) ->
callback (if err then false else true) if callback
return
return unless nullCheck(path, cb)
req = new FSReqWrap()
req.oncomplete = cb
binding.stat pathModule._makeLong(path), req
return
fs.existsSync = (path) ->
try
nullCheck path
binding.stat pathModule._makeLong(path)
return true
catch e
return false
return
fs.readFile = (path, options, callback_) ->
read = ->
if size is 0
buffer = new Buffer(8192)
fs.read fd, buffer, 0, 8192, -1, afterRead
else
fs.read fd, buffer, pos, size - pos, -1, afterRead
return
afterRead = (er, bytesRead) ->
if er
return fs.close(fd, (er2) ->
callback er
)
return close() if bytesRead is 0
pos += bytesRead
if size isnt 0
if pos is size
close()
else
read()
else
buffers.push buffer.slice(0, bytesRead)
read()
return
close = ->
fs.close fd, (er) ->
if size is 0
buffer = Buffer.concat(buffers, pos)
else buffer = buffer.slice(0, pos) if pos < size
buffer = buffer.toString(encoding) if encoding
callback er, buffer
return
callback = maybeCallback(arguments[arguments.length - 1])
if util.isFunction(options) or not options
options =
encoding: null
flag: "r"
else if util.isString(options)
options =
encoding: options
flag: "r"
else throw new TypeError("Bad arguments") unless util.isObject(options)
encoding = options.encoding
assertEncoding encoding
size = undefined
buffer = undefined
buffers = undefined
pos = 0
fd = undefined
flag = options.flag or "r"
fs.open path, flag, 438, (er, fd_) ->
return callback(er) if er
fd = fd_
fs.fstat fd, (er, st) ->
if er
return fs.close(fd, ->
callback er
return
)
size = st.size
if size is 0
buffers = []
return read()
if size > kMaxLength
err = new RangeError("File size is greater than possible Buffer: " + "0x3FFFFFFF bytes")
return fs.close(fd, ->
callback err
return
)
buffer = new Buffer(size)
read()
return
return
return
fs.readFileSync = (path, options) ->
unless options
options =
encoding: null
flag: "r"
else if util.isString(options)
options =
encoding: options
flag: "r"
else throw new TypeError("Bad arguments") unless util.isObject(options)
encoding = options.encoding
assertEncoding encoding
flag = options.flag or "r"
fd = fs.openSync(path, flag, 438)
size = undefined
threw = true
try
size = fs.fstatSync(fd).size
threw = false
finally
fs.closeSync fd if threw
pos = 0
buffer = undefined
buffers = undefined
if size is 0
buffers = []
else
threw = true
try
buffer = new Buffer(size)
threw = false
finally
fs.closeSync fd if threw
done = false
until done
threw = true
try
if size isnt 0
bytesRead = fs.readSync(fd, buffer, pos, size - pos)
else
buffer = new Buffer(8192)
bytesRead = fs.readSync(fd, buffer, 0, 8192)
buffers.push buffer.slice(0, bytesRead) if bytesRead
threw = false
finally
fs.closeSync fd if threw
pos += bytesRead
done = (bytesRead is 0) or (size isnt 0 and pos >= size)
fs.closeSync fd
if size is 0
buffer = Buffer.concat(buffers, pos)
else buffer = buffer.slice(0, pos) if pos < size
buffer = buffer.toString(encoding) if encoding
buffer
Object.defineProperty exports, "_stringToFlags",
enumerable: false
value: stringToFlags
fs.close = (fd, callback) ->
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.close fd, req
return
fs.closeSync = (fd) ->
binding.close fd
fs.open = (path, flags, mode, callback) ->
callback = makeCallback(arguments[arguments.length - 1])
mode = modeNum(mode, 438)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.open pathModule._makeLong(path), stringToFlags(flags), mode, req
return
fs.openSync = (path, flags, mode) ->
mode = modeNum(mode, 438)
nullCheck path
binding.open pathModule._makeLong(path), stringToFlags(flags), mode
fs.read = (fd, buffer, offset, length, position, callback) ->
wrapper = (err, bytesRead) ->
callback and callback(err, bytesRead or 0, buffer)
return
unless util.isBuffer(buffer)
cb = arguments[4]
encoding = arguments[3]
assertEncoding encoding
position = arguments[2]
length = arguments[1]
buffer = new Buffer(length)
offset = 0
callback = (err, bytesRead) ->
return unless cb
str = (if (bytesRead > 0) then buffer.toString(encoding, 0, bytesRead) else "")
(cb) err, str, bytesRead
return
req = new FSReqWrap()
req.oncomplete = wrapper
binding.read fd, buffer, offset, length, position, req
return
fs.readSync = (fd, buffer, offset, length, position) ->
legacy = false
unless util.isBuffer(buffer)
legacy = true
encoding = arguments[3]
assertEncoding encoding
position = arguments[2]
length = arguments[1]
buffer = new Buffer(length)
offset = 0
r = binding.read(fd, buffer, offset, length, position)
return r unless legacy
str = (if (r > 0) then buffer.toString(encoding, 0, r) else "")
[
str
r
]
fs.write = (fd, buffer, offset, length, position, callback) ->
strWrapper = (err, written) ->
callback err, written or 0, buffer
return
bufWrapper = (err, written) ->
callback err, written or 0, buffer
return
if util.isBuffer(buffer)
if util.isFunction(position)
callback = position
position = null
callback = maybeCallback(callback)
req = new FSReqWrap()
req.oncomplete = strWrapper
return binding.writeBuffer(fd, buffer, offset, length, position, req)
buffer += "" if util.isString(buffer)
unless util.isFunction(position)
if util.isFunction(offset)
position = offset
offset = null
else
position = length
length = "utf8"
callback = maybeCallback(position)
req = new FSReqWrap()
req.oncomplete = bufWrapper
binding.writeString fd, buffer, offset, length, req
fs.writeSync = (fd, buffer, offset, length, position) ->
if util.isBuffer(buffer)
position = null if util.isUndefined(position)
return binding.writeBuffer(fd, buffer, offset, length, position)
buffer += "" unless util.isString(buffer)
offset = null if util.isUndefined(offset)
binding.writeString fd, buffer, offset, length, position
fs.rename = (oldPath, newPath, callback) ->
callback = makeCallback(callback)
return unless nullCheck(oldPath, callback)
return unless nullCheck(newPath, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.rename pathModule._makeLong(oldPath), pathModule._makeLong(newPath), req
return
fs.renameSync = (oldPath, newPath) ->
nullCheck oldPath
nullCheck newPath
binding.rename pathModule._makeLong(oldPath), pathModule._makeLong(newPath)
fs.truncate = (path, len, callback) ->
if util.isNumber(path)
req = new FSReqWrap()
req.oncomplete = callback
return fs.ftruncate(path, len, req)
if util.isFunction(len)
callback = len
len = 0
else len = 0 if util.isUndefined(len)
callback = maybeCallback(callback)
fs.open path, "r+", (er, fd) ->
return callback(er) if er
req = new FSReqWrap()
req.oncomplete = ftruncateCb = (er) ->
fs.close fd, (er2) ->
callback er or er2
return
return
binding.ftruncate fd, len, req
return
return
fs.truncateSync = (path, len) ->
return fs.ftruncateSync(path, len) if util.isNumber(path)
len = 0 if util.isUndefined(len)
fd = fs.openSync(path, "r+")
try
ret = fs.ftruncateSync(fd, len)
finally
fs.closeSync fd
ret
fs.ftruncate = (fd, len, callback) ->
if util.isFunction(len)
callback = len
len = 0
else len = 0 if util.isUndefined(len)
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.ftruncate fd, len, req
return
fs.ftruncateSync = (fd, len) ->
len = 0 if util.isUndefined(len)
binding.ftruncate fd, len
fs.rmdir = (path, callback) ->
callback = maybeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.rmdir pathModule._makeLong(path), req
return
fs.rmdirSync = (path) ->
nullCheck path
binding.rmdir pathModule._makeLong(path)
fs.fdatasync = (fd, callback) ->
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.fdatasync fd, req
return
fs.fdatasyncSync = (fd) ->
binding.fdatasync fd
fs.fsync = (fd, callback) ->
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.fsync fd, req
return
fs.fsyncSync = (fd) ->
binding.fsync fd
fs.mkdir = (path, mode, callback) ->
callback = mode if util.isFunction(mode)
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.mkdir pathModule._makeLong(path), modeNum(mode, 511), req
return
fs.mkdirSync = (path, mode) ->
nullCheck path
binding.mkdir pathModule._makeLong(path), modeNum(mode, 511)
fs.readdir = (path, callback) ->
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.readdir pathModule._makeLong(path), req
return
fs.readdirSync = (path) ->
nullCheck path
binding.readdir pathModule._makeLong(path)
fs.fstat = (fd, callback) ->
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.fstat fd, req
return
fs.lstat = (path, callback) ->
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.lstat pathModule._makeLong(path), req
return
fs.stat = (path, callback) ->
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.stat pathModule._makeLong(path), req
return
fs.fstatSync = (fd) ->
binding.fstat fd
fs.lstatSync = (path) ->
nullCheck path
binding.lstat pathModule._makeLong(path)
fs.statSync = (path) ->
nullCheck path
binding.stat pathModule._makeLong(path)
fs.readlink = (path, callback) ->
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.readlink pathModule._makeLong(path), req
return
fs.readlinkSync = (path) ->
nullCheck path
binding.readlink pathModule._makeLong(path)
fs.symlink = (destination, path, type_, callback) ->
type = ((if util.isString(type_) then type_ else null))
callback = makeCallback(arguments[arguments.length - 1])
return unless nullCheck(destination, callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.symlink preprocessSymlinkDestination(destination, type, path), pathModule._makeLong(path), type, req
return
fs.symlinkSync = (destination, path, type) ->
type = ((if util.isString(type) then type else null))
nullCheck destination
nullCheck path
binding.symlink preprocessSymlinkDestination(destination, type, path), pathModule._makeLong(path), type
fs.link = (srcpath, dstpath, callback) ->
callback = makeCallback(callback)
return unless nullCheck(srcpath, callback)
return unless nullCheck(dstpath, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.link pathModule._makeLong(srcpath), pathModule._makeLong(dstpath), req
return
fs.linkSync = (srcpath, dstpath) ->
nullCheck srcpath
nullCheck dstpath
binding.link pathModule._makeLong(srcpath), pathModule._makeLong(dstpath)
fs.unlink = (path, callback) ->
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.unlink pathModule._makeLong(path), req
return
fs.unlinkSync = (path) ->
nullCheck path
binding.unlink pathModule._makeLong(path)
fs.fchmod = (fd, mode, callback) ->
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.fchmod fd, modeNum(mode), req
return
fs.fchmodSync = (fd, mode) ->
binding.fchmod fd, modeNum(mode)
if constants.hasOwnProperty("O_SYMLINK")
fs.lchmod = (path, mode, callback) ->
callback = maybeCallback(callback)
fs.open path, constants.O_WRONLY | constants.O_SYMLINK, (err, fd) ->
if err
callback err
return
fs.fchmod fd, mode, (err) ->
fs.close fd, (err2) ->
callback err or err2
return
return
return
return
fs.lchmodSync = (path, mode) ->
fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK)
err = undefined
err2 = undefined
try
ret = fs.fchmodSync(fd, mode)
catch er
err = er
try
fs.closeSync fd
catch er
err2 = er
throw (err or err2) if err or err2
ret
fs.chmod = (path, mode, callback) ->
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.chmod pathModule._makeLong(path), modeNum(mode), req
return
fs.chmodSync = (path, mode) ->
nullCheck path
binding.chmod pathModule._makeLong(path), modeNum(mode)
if constants.hasOwnProperty("O_SYMLINK")
fs.lchown = (path, uid, gid, callback) ->
callback = maybeCallback(callback)
fs.open path, constants.O_WRONLY | constants.O_SYMLINK, (err, fd) ->
if err
callback err
return
fs.fchown fd, uid, gid, callback
return
return
fs.lchownSync = (path, uid, gid) ->
fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK)
fs.fchownSync fd, uid, gid
fs.fchown = (fd, uid, gid, callback) ->
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.fchown fd, uid, gid, req
return
fs.fchownSync = (fd, uid, gid) ->
binding.fchown fd, uid, gid
fs.chown = (path, uid, gid, callback) ->
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.chown pathModule._makeLong(path), uid, gid, req
return
fs.chownSync = (path, uid, gid) ->
nullCheck path
binding.chown pathModule._makeLong(path), uid, gid
fs._toUnixTimestamp = toUnixTimestamp
fs.utimes = (path, atime, mtime, callback) ->
callback = makeCallback(callback)
return unless nullCheck(path, callback)
req = new FSReqWrap()
req.oncomplete = callback
binding.utimes pathModule._makeLong(path), toUnixTimestamp(atime), toUnixTimestamp(mtime), req
return
fs.utimesSync = (path, atime, mtime) ->
nullCheck path
atime = toUnixTimestamp(atime)
mtime = toUnixTimestamp(mtime)
binding.utimes pathModule._makeLong(path), atime, mtime
return
fs.futimes = (fd, atime, mtime, callback) ->
atime = toUnixTimestamp(atime)
mtime = toUnixTimestamp(mtime)
req = new FSReqWrap()
req.oncomplete = makeCallback(callback)
binding.futimes fd, atime, mtime, req
return
fs.futimesSync = (fd, atime, mtime) ->
atime = toUnixTimestamp(atime)
mtime = toUnixTimestamp(mtime)
binding.futimes fd, atime, mtime
return
fs.writeFile = (path, data, options, callback) ->
callback = maybeCallback(arguments[arguments.length - 1])
if util.isFunction(options) or not options
options =
encoding: "utf8"
mode: 438
flag: "w"
else if util.isString(options)
options =
encoding: options
mode: 438
flag: "w"
else throw new TypeError("Bad arguments") unless util.isObject(options)
assertEncoding options.encoding
flag = options.flag or "w"
fs.open path, flag, options.mode, (openErr, fd) ->
if openErr
callback openErr if callback
else
buffer = (if util.isBuffer(data) then data else new Buffer("" + data, options.encoding or "utf8"))
position = (if /a/.test(flag) then null else 0)
writeAll fd, buffer, 0, buffer.length, position, callback
return
return
fs.writeFileSync = (path, data, options) ->
unless options
options =
encoding: "utf8"
mode: 438
flag: "w"
else if util.isString(options)
options =
encoding: options
mode: 438
flag: "w"
else throw new TypeError("Bad arguments") unless util.isObject(options)
assertEncoding options.encoding
flag = options.flag or "w"
fd = fs.openSync(path, flag, options.mode)
data = new Buffer("" + data, options.encoding or "utf8") unless util.isBuffer(data)
written = 0
length = data.length
position = (if /a/.test(flag) then null else 0)
try
while written < length
written += fs.writeSync(fd, data, written, length - written, position)
position += written
finally
fs.closeSync fd
return
fs.appendFile = (path, data, options, callback_) ->
callback = maybeCallback(arguments[arguments.length - 1])
if util.isFunction(options) or not options
options =
encoding: "utf8"
mode: 438
flag: "a"
else if util.isString(options)
options =
encoding: options
mode: 438
flag: "a"
else throw new TypeError("Bad arguments") unless util.isObject(options)
unless options.flag
options = util._extend(
flag: "a"
, options)
fs.writeFile path, data, options, callback
return
fs.appendFileSync = (path, data, options) ->
unless options
options =
encoding: "utf8"
mode: 438
flag: "a"
else if util.isString(options)
options =
encoding: options
mode: 438
flag: "a"
else throw new TypeError("Bad arguments") unless util.isObject(options)
unless options.flag
options = util._extend(
flag: "a"
, options)
fs.writeFileSync path, data, options
return
util.inherits FSWatcher, EventEmitter
FSWatcher::start = (filename, persistent, recursive) ->
nullCheck filename
err = @_handle.start(pathModule._makeLong(filename), persistent, recursive)
if err
@_handle.close()
throw errnoException(err, "watch")
return
FSWatcher::close = ->
@_handle.close()
return
fs.watch = (filename) ->
nullCheck filename
watcher = undefined
options = undefined
listener = undefined
if util.isObject(arguments[1])
options = arguments[1]
listener = arguments[2]
else
options = {}
listener = arguments[1]
options.persistent = true if util.isUndefined(options.persistent)
options.recursive = false if util.isUndefined(options.recursive)
watcher = new FSWatcher()
watcher.start filename, options.persistent, options.recursive
watcher.addListener "change", listener if listener
watcher
util.inherits StatWatcher, EventEmitter
StatWatcher::start = (filename, persistent, interval) ->
nullCheck filename
@_handle.start pathModule._makeLong(filename), persistent, interval
return
StatWatcher::stop = ->
@_handle.stop()
return
statWatchers = {}
fs.watchFile = (filename) ->
nullCheck filename
filename = pathModule.resolve(filename)
stat = undefined
listener = undefined
options =
interval: 5007
persistent: true
if util.isObject(arguments[1])
options = util._extend(options, arguments[1])
listener = arguments[2]
else
listener = arguments[1]
throw new Error("watchFile requires a listener function") unless listener
if inStatWatchers(filename)
stat = statWatchers[filename]
else
stat = statWatchers[filename] = new StatWatcher()
stat.start filename, options.persistent, options.interval
stat.addListener "change", listener
stat
fs.unwatchFile = (filename, listener) ->
nullCheck filename
filename = pathModule.resolve(filename)
return unless inStatWatchers(filename)
stat = statWatchers[filename]
if util.isFunction(listener)
stat.removeListener "change", listener
else
stat.removeAllListeners "change"
if EventEmitter.listenerCount(stat, "change") is 0
stat.stop()
statWatchers[filename] = `undefined`
return
if isWindows
nextPartRe = /(.*?)(?:[\/\\]+|$)/g
else
nextPartRe = /(.*?)(?:[\/]+|$)/g
if isWindows
splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/
else
splitRootRe = /^[\/]*/
fs.realpathSync = realpathSync = (p, cache) ->
start = ->
m = splitRootRe.exec(p)
pos = m[0].length
current = m[0]
base = m[0]
previous = ""
if isWindows and not knownHard[base]
fs.lstatSync base
knownHard[base] = true
return
p = pathModule.resolve(p)
return cache[p] if cache and Object::hasOwnProperty.call(cache, p)
original = p
seenLinks = {}
knownHard = {}
pos = undefined
current = undefined
base = undefined
previous = undefined
start()
while pos < p.length
nextPartRe.lastIndex = pos
result = nextPartRe.exec(p)
previous = current
current += result[0]
base = previous + result[1]
pos = nextPartRe.lastIndex
continue if knownHard[base] or (cache and cache[base] is base)
resolvedLink = undefined
if cache and Object::hasOwnProperty.call(cache, base)
resolvedLink = cache[base]
else
stat = fs.lstatSync(base)
unless stat.isSymbolicLink()
knownHard[base] = true
cache[base] = base if cache
continue
linkTarget = null
unless isWindows
id = stat.dev.toString(32) + ":" + stat.ino.toString(32)
linkTarget = seenLinks[id] if seenLinks.hasOwnProperty(id)
if util.isNull(linkTarget)
fs.statSync base
linkTarget = fs.readlinkSync(base)
resolvedLink = pathModule.resolve(previous, linkTarget)
cache[base] = resolvedLink if cache
seenLinks[id] = linkTarget unless isWindows
p = pathModule.resolve(resolvedLink, p.slice(pos))
start()
cache[original] = p if cache
p
fs.realpath = realpath = (p, cache, cb) ->
start = ->
m = splitRootRe.exec(p)
pos = m[0].length
current = m[0]
base = m[0]
previous = ""
if isWindows and not knownHard[base]
fs.lstat base, (err) ->
return cb(err) if err
knownHard[base] = true
LOOP()
return
else
process.nextTick LOOP
return
LOOP = ->
if pos >= p.length
cache[original] = p if cache
return cb(null, p)
nextPartRe.lastIndex = pos
result = nextPartRe.exec(p)
previous = current
current += result[0]
base = previous + result[1]
pos = nextPartRe.lastIndex
return process.nextTick(LOOP) if knownHard[base] or (cache and cache[base] is base)
return gotResolvedLink(cache[base]) if cache and Object::hasOwnProperty.call(cache, base)
fs.lstat base, gotStat
gotStat = (err, stat) ->
return cb(err) if err
unless stat.isSymbolicLink()
knownHard[base] = true
cache[base] = base if cache
return process.nextTick(LOOP)
unless isWindows
id = stat.dev.toString(32) + ":" + stat.ino.toString(32)
return gotTarget(null, seenLinks[id], base) if seenLinks.hasOwnProperty(id)
fs.stat base, (err) ->
return cb(err) if err
fs.readlink base, (err, target) ->
seenLinks[id] = target unless isWindows
gotTarget err, target
return
return
return
gotTarget = (err, target, base) ->
return cb(err) if err
resolvedLink = pathModule.resolve(previous, target)
cache[base] = resolvedLink if cache
gotResolvedLink resolvedLink
return
gotResolvedLink = (resolvedLink) ->
p = pathModule.resolve(resolvedLink, p.slice(pos))
start()
return
unless util.isFunction(cb)
cb = maybeCallback(cache)
cache = null
p = pathModule.resolve(p)
return process.nextTick(cb.bind(null, null, cache[p])) if cache and Object::hasOwnProperty.call(cache, p)
original = p
seenLinks = {}
knownHard = {}
pos = undefined
current = undefined
base = undefined
previous = undefined
start()
return
pool = undefined
fs.createReadStream = (path, options) ->
new ReadStream(path, options)
util.inherits ReadStream, Readable
fs.ReadStream = ReadStream
fs.FileReadStream = fs.ReadStream
ReadStream::open = ->
self = this
fs.open @path, @flags, @mode, (er, fd) ->
if er
self.destroy() if self.autoClose
self.emit "error", er
return
self.fd = fd
self.emit "open", fd
self.read()
return
return
ReadStream::_read = (n) ->
onread = (er, bytesRead) ->
if er
self.destroy() if self.autoClose
self.emit "error", er
else
b = null
b = thisPool.slice(start, start + bytesRead) if bytesRead > 0
self.push b
return
unless util.isNumber(@fd)
return @once("open", ->
@_read n
return
)
return if @destroyed
if not pool or pool.length - pool.used < kMinPoolSpace
pool = null
allocNewPool @_readableState.highWaterMark
thisPool = pool
toRead = Math.min(pool.length - pool.used, n)
start = pool.used
toRead = Math.min(@end - @pos + 1, toRead) unless util.isUndefined(@pos)
return @push(null) if toRead <= 0
self = this
fs.read @fd, pool, pool.used, toRead, @pos, onread
@pos += toRead unless util.isUndefined(@pos)
pool.used += toRead
return
ReadStream::destroy = ->
return if @destroyed
@destroyed = true
@close() if util.isNumber(@fd)
return
ReadStream::close = (cb) ->
close = (fd) ->
fs.close fd or self.fd, (er) ->
if er
self.emit "error", er
else
self.emit "close"
return
self.fd = null
return
self = this
@once "close", cb if cb
if @closed or not util.isNumber(@fd)
unless util.isNumber(@fd)
@once "open", close
return
return process.nextTick(@emit.bind(this, "close"))
@closed = true
close()
return
fs.createWriteStream = (path, options) ->
new WriteStream(path, options)
util.inherits WriteStream, Writable
fs.WriteStream = WriteStream
fs.FileWriteStream = fs.WriteStream
WriteStream::open = ->
fs.open @path, @flags, @mode, ((er, fd) ->
if er
@destroy()
@emit "error", er
return
@fd = fd
@emit "open", fd
return
).bind(this)
return
WriteStream::_write = (data, encoding, cb) ->
return @emit("error", new Error("Invalid data")) unless util.isBuffer(data)
unless util.isNumber(@fd)
return @once("open", ->
@_write data, encoding, cb
return
)
self = this
fs.write @fd, data, 0, data.length, @pos, (er, bytes) ->
if er
self.destroy()
return cb(er)
self.bytesWritten += bytes
cb()
return
@pos += data.length unless util.isUndefined(@pos)
return
WriteStream::destroy = ReadStream::destroy
WriteStream::close = ReadStream::close
WriteStream::destroySoon = WriteStream::end
util.inherits SyncWriteStream, Stream
# Export
fs.SyncWriteStream = SyncWriteStream
SyncWriteStream::write = (data, arg1, arg2) ->
encoding = undefined
cb = undefined
# parse arguments
if arg1
if util.isString(arg1)
encoding = arg1
cb = arg2
else if util.isFunction(arg1)
cb = arg1
else
throw new Error("bad arg")
assertEncoding encoding
# Change strings to buffers. SLOW
data = new Buffer(data, encoding) if util.isString(data)
fs.writeSync @fd, data, 0, data.length
process.nextTick cb if cb
true
SyncWriteStream::end = (data, arg1, arg2) ->
@write data, arg1, arg2 if data
@destroy()
return
SyncWriteStream::destroy = ->
fs.closeSync @fd if @autoClose
@fd = null
@emit "close"
true
SyncWriteStream::destroySoon = SyncWriteStream::destroy
|
[
{
"context": "ient =\n client_id: 'uuid', client_secret: 'h4sh'\n verifier = () ->\n strategy = new OAut",
"end": 1515,
"score": 0.998765230178833,
"start": 1511,
"tag": "KEY",
"value": "h4sh"
},
{
"context": "ient =\n client_id: 'uuid', client_secret: 'h4sh'\... | test/unit/strategies/oauth2/authorizationCodeGrant.coffee | Zacaria/connect | 0 | # Test dependencies
_ = require 'lodash'
chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
expect = chai.expect
proxyquire = require('proxyquire').noCallThru()
superagent = require 'superagent'
version = require('../../../../package').version
# Assertions
chai.use sinonChai
chai.should()
# Code under test
User = proxyquire('../../../../models/User', {
'../boot/redis': {
getClient: () => {}
}
})
OAuth2Strategy = proxyquire('../../../../protocols/OAuth2', {
'../models/User': User
})
providers = require '../../../../providers'
# We need to test two things.
# 1. That the request is being formed correctly given the
# properties of a provider and client. For this we'll
# return a superagent request object to assert against.
# 2. That the response is handled correctly. For this we'll
# use `nock`, to mock the HTTP service in question.
sandbox = sinon.createSandbox()
describe 'OAuth2Strategy authorizationCodeGrant', ->
{ err, res, provider, client, strategy } = {}
before () ->
sandbox.stub(superagent, 'post')
sandbox.stub(superagent, 'patch')
after ()->
sandbox.restore()
describe 'with defaults and valid parameters', ->
postStub = {
set: sinon.stub(),
send: sinon.stub(),
end: sinon.stub().callsArgWith(0, null, {})
}
before (done) ->
superagent.post.returns(postStub)
provider = _.clone providers.oauth2test, true
client =
client_id: 'uuid', client_secret: 'h4sh'
verifier = () ->
strategy = new OAuth2Strategy provider, client, verifier
strategy.authorizationCodeGrant 'r4nd0m', () ->
done()
it 'should use the specified endpoint', ->
superagent.post.should.be.calledOnce.and.calledWith(provider.endpoints.token.url)
it 'should send the grant_type', ->
postStub.send.should.be.calledOnce.and.calledWith('grant_type=authorization_code&code=r4nd0m&redirect_uri=' + encodeURIComponent(provider.redirect_uri))
it 'should set the accept header', ->
postStub.set.should.be.calledWith('accept', 'application/json')
it 'should set the user agent', ->
postStub.set.should.be.calledWith('user-agent', 'Anvil Connect/' + version)
describe 'with custom method', ->
patchStub = {
set: sinon.stub(),
send: sinon.stub(),
end: sinon.stub().callsArgWith(0, null, {})
}
before (done) ->
superagent.patch.returns(patchStub)
provider = _.clone providers.oauth2test, true
provider.endpoints.token.method = 'PATCH'
client =
client_id: 'uuid', client_secret: 'h4sh'
verifier = () ->
strategy = new OAuth2Strategy provider, client, verifier
strategy.authorizationCodeGrant 'r4nd0m', () ->
done()
it 'should use the correct HTTP method', ->
expect(superagent.patch).to.be.calledOnce
describe 'with "client_secret_basic" auth', ->
postStub = {
set: sinon.stub(),
send: sinon.stub(),
end: sinon.stub().callsArgWith(0, null, {})
}
before (done) ->
superagent.post.returns(postStub)
provider = _.clone providers.oauth2test, true
# Specifically setting the method, was getting holdover from other tests.
provider.endpoints.token.method = 'post'
provider.endpoints.token.auth = 'client_secret_basic'
client =
client_id: 'uuid', client_secret: 'h4sh'
verifier = () ->
strategy = new OAuth2Strategy provider, client, verifier
strategy.authorizationCodeGrant 'r4nd0m', () ->
done()
it 'should set the Authorization header', ->
postStub.set.should.be.calledWith('Authorization', 'Basic ' + strategy.base64credentials())
describe 'with "client_secret_post" auth', ->
postStub = {
set: sinon.stub(),
send: sinon.stub(),
end: sinon.stub().callsArgWith(0, null, {})
}
before (done) ->
superagent.post.returns(postStub)
provider = _.clone providers.oauth2test, true
provider.endpoints.token.auth = 'client_secret_post'
client =
client_id: 'uuid', client_secret: 'h4sh'
verifier = () ->
strategy = new OAuth2Strategy provider, client, verifier
strategy.authorizationCodeGrant 'r4nd0m', () ->
done()
it 'should send the client_id', ->
postStub.send.should.be.calledOnce.and.calledWith('grant_type=authorization_code&code=r4nd0m&redirect_uri=http%3A%2F%2Flocalhost%3A3000connect%2Foauth2test%2Fcallback&client_id=' + client.client_id + '&client_secret=' + client.client_secret)
describe 'with error response', ->
postStub = {
set: sinon.stub(),
send: sinon.stub(),
end: sinon.stub().callsArgWith(0, new Error())
}
before (done) ->
superagent.post.returns(postStub)
provider = _.clone providers.oauth2test, true
client =
client_id: 'uuid', client_secret: 'h4sh'
verifier = () ->
strategy = new OAuth2Strategy provider, client, verifier
strategy.authorizationCodeGrant 'r4nd0m', (error, response) ->
err = error
res = response
done()
it 'should provide an error', ->
expect(err).to.be.an('Error')
it 'should not provide a token response', ->
expect(res).to.be.undefined
describe 'with "x-www-form-urlencoded" response', ->
postStub = {
set: sinon.stub(),
send: sinon.stub(),
end: sinon.stub().callsArgWith(0, null, {
text: 'access_token=t0k3n&expires=3600',
headers: {
'content-type': 'application/x-www-form-urlencoded'
},
statusCode: 200
})
}
before (done) ->
superagent.post.returns(postStub)
provider = _.clone providers.oauth2test, true
provider.endpoints.token.parser = 'x-www-form-urlencoded'
client =
client_id: 'uuid', client_secret: 'h4sh'
verifier = () ->
strategy = new OAuth2Strategy provider, client, verifier
strategy.authorizationCodeGrant 'r4nd0m', (error, response) ->
err = error
res = response
done()
it 'should not provide an error', ->
expect(err).to.be.null
it 'should provide the token response', ->
res.access_token.should.equal 't0k3n'
res.expires.should.equal '3600'
describe 'with "JSON" response', ->
postStub = {
set: sinon.stub(),
send: sinon.stub(),
end: sinon.stub().callsArgWith(0, null, {
body: { access_token: 'h3x' },
statusCode: 200
})
}
before (done) ->
superagent.post.returns(postStub)
provider = _.clone providers.oauth2test, true
provider.endpoints.token.parser = 'json'
client =
client_id: 'uuid', client_secret: 'h4sh'
verifier = () ->
strategy = new OAuth2Strategy provider, client, verifier
strategy.authorizationCodeGrant 'r4nd0m', (error, response) ->
err = error
res = response
done()
it 'should not provide an error', ->
expect(err).to.be.null
it 'should provide the token response', ->
res.access_token.should.equal 'h3x'
| 25213 | # Test dependencies
_ = require 'lodash'
chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
expect = chai.expect
proxyquire = require('proxyquire').noCallThru()
superagent = require 'superagent'
version = require('../../../../package').version
# Assertions
chai.use sinonChai
chai.should()
# Code under test
User = proxyquire('../../../../models/User', {
'../boot/redis': {
getClient: () => {}
}
})
OAuth2Strategy = proxyquire('../../../../protocols/OAuth2', {
'../models/User': User
})
providers = require '../../../../providers'
# We need to test two things.
# 1. That the request is being formed correctly given the
# properties of a provider and client. For this we'll
# return a superagent request object to assert against.
# 2. That the response is handled correctly. For this we'll
# use `nock`, to mock the HTTP service in question.
sandbox = sinon.createSandbox()
describe 'OAuth2Strategy authorizationCodeGrant', ->
{ err, res, provider, client, strategy } = {}
before () ->
sandbox.stub(superagent, 'post')
sandbox.stub(superagent, 'patch')
after ()->
sandbox.restore()
describe 'with defaults and valid parameters', ->
postStub = {
set: sinon.stub(),
send: sinon.stub(),
end: sinon.stub().callsArgWith(0, null, {})
}
before (done) ->
superagent.post.returns(postStub)
provider = _.clone providers.oauth2test, true
client =
client_id: 'uuid', client_secret: '<KEY>'
verifier = () ->
strategy = new OAuth2Strategy provider, client, verifier
strategy.authorizationCodeGrant 'r4nd0m', () ->
done()
it 'should use the specified endpoint', ->
superagent.post.should.be.calledOnce.and.calledWith(provider.endpoints.token.url)
it 'should send the grant_type', ->
postStub.send.should.be.calledOnce.and.calledWith('grant_type=authorization_code&code=r4nd0m&redirect_uri=' + encodeURIComponent(provider.redirect_uri))
it 'should set the accept header', ->
postStub.set.should.be.calledWith('accept', 'application/json')
it 'should set the user agent', ->
postStub.set.should.be.calledWith('user-agent', 'Anvil Connect/' + version)
describe 'with custom method', ->
patchStub = {
set: sinon.stub(),
send: sinon.stub(),
end: sinon.stub().callsArgWith(0, null, {})
}
before (done) ->
superagent.patch.returns(patchStub)
provider = _.clone providers.oauth2test, true
provider.endpoints.token.method = 'PATCH'
client =
client_id: 'uuid', client_secret: '<KEY>'
verifier = () ->
strategy = new OAuth2Strategy provider, client, verifier
strategy.authorizationCodeGrant 'r4nd0m', () ->
done()
it 'should use the correct HTTP method', ->
expect(superagent.patch).to.be.calledOnce
describe 'with "client_secret_basic" auth', ->
postStub = {
set: sinon.stub(),
send: sinon.stub(),
end: sinon.stub().callsArgWith(0, null, {})
}
before (done) ->
superagent.post.returns(postStub)
provider = _.clone providers.oauth2test, true
# Specifically setting the method, was getting holdover from other tests.
provider.endpoints.token.method = 'post'
provider.endpoints.token.auth = 'client_secret_basic'
client =
client_id: 'uuid', client_secret: '<KEY>'
verifier = () ->
strategy = new OAuth2Strategy provider, client, verifier
strategy.authorizationCodeGrant 'r4nd0m', () ->
done()
it 'should set the Authorization header', ->
postStub.set.should.be.calledWith('Authorization', 'Basic ' + strategy.base64credentials())
describe 'with "client_secret_post" auth', ->
postStub = {
set: sinon.stub(),
send: sinon.stub(),
end: sinon.stub().callsArgWith(0, null, {})
}
before (done) ->
superagent.post.returns(postStub)
provider = _.clone providers.oauth2test, true
provider.endpoints.token.auth = 'client_secret_post'
client =
client_id: 'uuid', client_secret: '<KEY>'
verifier = () ->
strategy = new OAuth2Strategy provider, client, verifier
strategy.authorizationCodeGrant 'r4nd0m', () ->
done()
it 'should send the client_id', ->
postStub.send.should.be.calledOnce.and.calledWith('grant_type=authorization_code&code=r4nd0m&redirect_uri=http%3A%2F%2Flocalhost%3A3000connect%2Foauth2test%2Fcallback&client_id=' + client.client_id + '&client_secret=' + client.client_secret)
describe 'with error response', ->
postStub = {
set: sinon.stub(),
send: sinon.stub(),
end: sinon.stub().callsArgWith(0, new Error())
}
before (done) ->
superagent.post.returns(postStub)
provider = _.clone providers.oauth2test, true
client =
client_id: 'uuid', client_secret: '<KEY>'
verifier = () ->
strategy = new OAuth2Strategy provider, client, verifier
strategy.authorizationCodeGrant 'r4nd0m', (error, response) ->
err = error
res = response
done()
it 'should provide an error', ->
expect(err).to.be.an('Error')
it 'should not provide a token response', ->
expect(res).to.be.undefined
describe 'with "x-www-form-urlencoded" response', ->
postStub = {
set: sinon.stub(),
send: sinon.stub(),
end: sinon.stub().callsArgWith(0, null, {
text: 'access_token=t0k3n&expires=3600',
headers: {
'content-type': 'application/x-www-form-urlencoded'
},
statusCode: 200
})
}
before (done) ->
superagent.post.returns(postStub)
provider = _.clone providers.oauth2test, true
provider.endpoints.token.parser = 'x-www-form-urlencoded'
client =
client_id: 'uuid', client_secret: '<KEY>'
verifier = () ->
strategy = new OAuth2Strategy provider, client, verifier
strategy.authorizationCodeGrant 'r4nd0m', (error, response) ->
err = error
res = response
done()
it 'should not provide an error', ->
expect(err).to.be.null
it 'should provide the token response', ->
res.access_token.should.equal '<PASSWORD>'
res.expires.should.equal '3600'
describe 'with "JSON" response', ->
postStub = {
set: sinon.stub(),
send: sinon.stub(),
end: sinon.stub().callsArgWith(0, null, {
body: { access_token: '<PASSWORD>' },
statusCode: 200
})
}
before (done) ->
superagent.post.returns(postStub)
provider = _.clone providers.oauth2test, true
provider.endpoints.token.parser = 'json'
client =
client_id: 'uuid', client_secret: '<KEY>'
verifier = () ->
strategy = new OAuth2Strategy provider, client, verifier
strategy.authorizationCodeGrant 'r4nd0m', (error, response) ->
err = error
res = response
done()
it 'should not provide an error', ->
expect(err).to.be.null
it 'should provide the token response', ->
res.access_token.should.equal 'h<PASSWORD>'
| true | # Test dependencies
_ = require 'lodash'
chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
expect = chai.expect
proxyquire = require('proxyquire').noCallThru()
superagent = require 'superagent'
version = require('../../../../package').version
# Assertions
chai.use sinonChai
chai.should()
# Code under test
User = proxyquire('../../../../models/User', {
'../boot/redis': {
getClient: () => {}
}
})
OAuth2Strategy = proxyquire('../../../../protocols/OAuth2', {
'../models/User': User
})
providers = require '../../../../providers'
# We need to test two things.
# 1. That the request is being formed correctly given the
# properties of a provider and client. For this we'll
# return a superagent request object to assert against.
# 2. That the response is handled correctly. For this we'll
# use `nock`, to mock the HTTP service in question.
sandbox = sinon.createSandbox()
describe 'OAuth2Strategy authorizationCodeGrant', ->
{ err, res, provider, client, strategy } = {}
before () ->
sandbox.stub(superagent, 'post')
sandbox.stub(superagent, 'patch')
after ()->
sandbox.restore()
describe 'with defaults and valid parameters', ->
postStub = {
set: sinon.stub(),
send: sinon.stub(),
end: sinon.stub().callsArgWith(0, null, {})
}
before (done) ->
superagent.post.returns(postStub)
provider = _.clone providers.oauth2test, true
client =
client_id: 'uuid', client_secret: 'PI:KEY:<KEY>END_PI'
verifier = () ->
strategy = new OAuth2Strategy provider, client, verifier
strategy.authorizationCodeGrant 'r4nd0m', () ->
done()
it 'should use the specified endpoint', ->
superagent.post.should.be.calledOnce.and.calledWith(provider.endpoints.token.url)
it 'should send the grant_type', ->
postStub.send.should.be.calledOnce.and.calledWith('grant_type=authorization_code&code=r4nd0m&redirect_uri=' + encodeURIComponent(provider.redirect_uri))
it 'should set the accept header', ->
postStub.set.should.be.calledWith('accept', 'application/json')
it 'should set the user agent', ->
postStub.set.should.be.calledWith('user-agent', 'Anvil Connect/' + version)
describe 'with custom method', ->
patchStub = {
set: sinon.stub(),
send: sinon.stub(),
end: sinon.stub().callsArgWith(0, null, {})
}
before (done) ->
superagent.patch.returns(patchStub)
provider = _.clone providers.oauth2test, true
provider.endpoints.token.method = 'PATCH'
client =
client_id: 'uuid', client_secret: 'PI:KEY:<KEY>END_PI'
verifier = () ->
strategy = new OAuth2Strategy provider, client, verifier
strategy.authorizationCodeGrant 'r4nd0m', () ->
done()
it 'should use the correct HTTP method', ->
expect(superagent.patch).to.be.calledOnce
describe 'with "client_secret_basic" auth', ->
postStub = {
set: sinon.stub(),
send: sinon.stub(),
end: sinon.stub().callsArgWith(0, null, {})
}
before (done) ->
superagent.post.returns(postStub)
provider = _.clone providers.oauth2test, true
# Specifically setting the method, was getting holdover from other tests.
provider.endpoints.token.method = 'post'
provider.endpoints.token.auth = 'client_secret_basic'
client =
client_id: 'uuid', client_secret: 'PI:KEY:<KEY>END_PI'
verifier = () ->
strategy = new OAuth2Strategy provider, client, verifier
strategy.authorizationCodeGrant 'r4nd0m', () ->
done()
it 'should set the Authorization header', ->
postStub.set.should.be.calledWith('Authorization', 'Basic ' + strategy.base64credentials())
describe 'with "client_secret_post" auth', ->
postStub = {
set: sinon.stub(),
send: sinon.stub(),
end: sinon.stub().callsArgWith(0, null, {})
}
before (done) ->
superagent.post.returns(postStub)
provider = _.clone providers.oauth2test, true
provider.endpoints.token.auth = 'client_secret_post'
client =
client_id: 'uuid', client_secret: 'PI:KEY:<KEY>END_PI'
verifier = () ->
strategy = new OAuth2Strategy provider, client, verifier
strategy.authorizationCodeGrant 'r4nd0m', () ->
done()
it 'should send the client_id', ->
postStub.send.should.be.calledOnce.and.calledWith('grant_type=authorization_code&code=r4nd0m&redirect_uri=http%3A%2F%2Flocalhost%3A3000connect%2Foauth2test%2Fcallback&client_id=' + client.client_id + '&client_secret=' + client.client_secret)
describe 'with error response', ->
postStub = {
set: sinon.stub(),
send: sinon.stub(),
end: sinon.stub().callsArgWith(0, new Error())
}
before (done) ->
superagent.post.returns(postStub)
provider = _.clone providers.oauth2test, true
client =
client_id: 'uuid', client_secret: 'PI:KEY:<KEY>END_PI'
verifier = () ->
strategy = new OAuth2Strategy provider, client, verifier
strategy.authorizationCodeGrant 'r4nd0m', (error, response) ->
err = error
res = response
done()
it 'should provide an error', ->
expect(err).to.be.an('Error')
it 'should not provide a token response', ->
expect(res).to.be.undefined
describe 'with "x-www-form-urlencoded" response', ->
postStub = {
set: sinon.stub(),
send: sinon.stub(),
end: sinon.stub().callsArgWith(0, null, {
text: 'access_token=t0k3n&expires=3600',
headers: {
'content-type': 'application/x-www-form-urlencoded'
},
statusCode: 200
})
}
before (done) ->
superagent.post.returns(postStub)
provider = _.clone providers.oauth2test, true
provider.endpoints.token.parser = 'x-www-form-urlencoded'
client =
client_id: 'uuid', client_secret: 'PI:KEY:<KEY>END_PI'
verifier = () ->
strategy = new OAuth2Strategy provider, client, verifier
strategy.authorizationCodeGrant 'r4nd0m', (error, response) ->
err = error
res = response
done()
it 'should not provide an error', ->
expect(err).to.be.null
it 'should provide the token response', ->
res.access_token.should.equal 'PI:PASSWORD:<PASSWORD>END_PI'
res.expires.should.equal '3600'
describe 'with "JSON" response', ->
postStub = {
set: sinon.stub(),
send: sinon.stub(),
end: sinon.stub().callsArgWith(0, null, {
body: { access_token: 'PI:PASSWORD:<PASSWORD>END_PI' },
statusCode: 200
})
}
before (done) ->
superagent.post.returns(postStub)
provider = _.clone providers.oauth2test, true
provider.endpoints.token.parser = 'json'
client =
client_id: 'uuid', client_secret: 'PI:KEY:<KEY>END_PI'
verifier = () ->
strategy = new OAuth2Strategy provider, client, verifier
strategy.authorizationCodeGrant 'r4nd0m', (error, response) ->
err = error
res = response
done()
it 'should not provide an error', ->
expect(err).to.be.null
it 'should provide the token response', ->
res.access_token.should.equal 'hPI:PASSWORD:<PASSWORD>END_PI'
|
[
{
"context": "hema)\n \n instance = new SimpleModel({name: 'testName', title: 'testTitle'})\n should.exist instanc",
"end": 1796,
"score": 0.9007583856582642,
"start": 1788,
"tag": "USERNAME",
"value": "testName"
},
{
"context": "true\n instance.should.have.property '... | node_modules/mongoose-file/test/test.coffee | brilliantyy/Pictopia | 19 | chai = require 'chai'
assert = chai.assert
expect = chai.expect
should = chai.should()
mongoose = require 'mongoose'
fs = require 'fs'
path = require 'path'
index = require '../src/index'
PLUGIN_TIMEOUT = 800
rmDir = (dirPath) ->
try
files = fs.readdirSync(dirPath)
catch e
return
if files.length > 0
i = 0
while i < files.length
continue if files[i] in ['.', '..']
filePath = dirPath + "/" + files[i]
if fs.statSync(filePath).isFile()
fs.unlinkSync filePath
else
rmDir filePath
i++
fs.rmdirSync dirPath
db = mongoose.createConnection('localhost', 'mongoose_file_tests')
db.on('error', console.error.bind(console, 'connection error:'))
uploads_base = __dirname + "/uploads"
uploads = uploads_base + "/u"
tmpFilePath = '/tmp/mongoose-file-test.txt'
uploadedDate = new Date()
uploadedFile =
size: 12345
path: tmpFilePath
name: 'photo.png'
type: 'image/png',
hash: false,
lastModifiedDate: uploadedDate
Schema = mongoose.Schema
ObjectId = Schema.ObjectId
SimpleSchema = new Schema
name: String
title: String
describe 'WHEN working with the plugin', ->
before (done) ->
done()
after (done) ->
SimpleModel = db.model("SimpleModel", SimpleSchema)
SimpleModel.remove {}, (err) ->
return done(err) if err
rmDir(uploads_base)
done()
describe 'library', ->
it 'should exist', (done) ->
should.exist index
done()
describe 'adding the plugin', ->
it 'should work', (done) ->
SimpleSchema.plugin index.filePlugin,
name: "photo",
upload_to: index.make_upload_to_model(uploads, 'photos'),
relative_to: uploads_base
SimpleModel = db.model("SimpleModel", SimpleSchema)
instance = new SimpleModel({name: 'testName', title: 'testTitle'})
should.exist instance
should.equal instance.isModified(), true
instance.should.have.property 'name', 'testName'
instance.should.have.property 'title', 'testTitle'
instance.should.have.property 'photo'
should.exist instance.photo
instance.photo.should.have.property 'name'
instance.photo.should.have.property 'path'
instance.photo.should.have.property 'rel'
instance.photo.should.have.property 'type'
instance.photo.should.have.property 'size'
instance.photo.should.have.property 'lastModified'
should.not.exist instance.photo.name
should.not.exist instance.photo.path
should.not.exist instance.photo.rel
should.not.exist instance.photo.type
should.not.exist instance.photo.size
should.not.exist instance.photo.lastModified
done()
describe 'assigning to the instance field', ->
it 'should populate subfields', (done) ->
SimpleSchema.plugin index.filePlugin,
name: "photo",
upload_to: index.make_upload_to_model(uploads, 'photos'),
relative_to: uploads_base
SimpleModel = db.model("SimpleModel", SimpleSchema)
instance = new SimpleModel({name: 'testName', title: 'testTitle'})
should.exist instance
should.exist instance.photo
should.equal instance.isModified(), true
fs.writeFile tmpFilePath, "Dummy content here.\n", (err) ->
return done(err) if (err)
instance.set('photo.file', uploadedFile)
# give the plugin some time to notice the assignment and execute its
# asynchronous code
setTimeout ->
should.equal instance.isModified(), true
should.exist instance.photo.name
should.exist instance.photo.path
should.exist instance.photo.rel
should.exist instance.photo.type
should.exist instance.photo.size
should.exist instance.photo.lastModified
should.equal instance.photo.name, uploadedFile.name
should.not.equal instance.photo.path, uploadedFile.path
should.equal instance.photo.type, uploadedFile.type
should.equal instance.photo.size, uploadedFile.size
should.equal instance.photo.lastModified, uploadedFile.lastModifiedDate
done()
, PLUGIN_TIMEOUT
describe 'assigning to the instance field', ->
it 'should mark as modified', (done) ->
SimpleSchema.plugin index.filePlugin,
name: "photo",
upload_to: index.make_upload_to_model(uploads, 'photos'),
relative_to: uploads_base
SimpleModel = db.model("SimpleModel", SimpleSchema)
instance = new SimpleModel({name: 'testName', title: 'testTitle'})
should.exist instance
should.equal instance.isModified(), true
instance.save (err) ->
return done(err) if err
should.equal instance.isModified(), false
fs.writeFile tmpFilePath, "Dummy content here.\n", (err) ->
return done(err) if (err)
instance.set('photo.file', uploadedFile)
# give the plugin some time to notice the assignment and execute its
# asynchronous code
setTimeout ->
should.equal instance.isModified(), true
instance.save (err) ->
return done(err) if err
should.equal instance.isModified(), false
done()
, PLUGIN_TIMEOUT
| 82844 | chai = require 'chai'
assert = chai.assert
expect = chai.expect
should = chai.should()
mongoose = require 'mongoose'
fs = require 'fs'
path = require 'path'
index = require '../src/index'
PLUGIN_TIMEOUT = 800
rmDir = (dirPath) ->
try
files = fs.readdirSync(dirPath)
catch e
return
if files.length > 0
i = 0
while i < files.length
continue if files[i] in ['.', '..']
filePath = dirPath + "/" + files[i]
if fs.statSync(filePath).isFile()
fs.unlinkSync filePath
else
rmDir filePath
i++
fs.rmdirSync dirPath
db = mongoose.createConnection('localhost', 'mongoose_file_tests')
db.on('error', console.error.bind(console, 'connection error:'))
uploads_base = __dirname + "/uploads"
uploads = uploads_base + "/u"
tmpFilePath = '/tmp/mongoose-file-test.txt'
uploadedDate = new Date()
uploadedFile =
size: 12345
path: tmpFilePath
name: 'photo.png'
type: 'image/png',
hash: false,
lastModifiedDate: uploadedDate
Schema = mongoose.Schema
ObjectId = Schema.ObjectId
SimpleSchema = new Schema
name: String
title: String
describe 'WHEN working with the plugin', ->
before (done) ->
done()
after (done) ->
SimpleModel = db.model("SimpleModel", SimpleSchema)
SimpleModel.remove {}, (err) ->
return done(err) if err
rmDir(uploads_base)
done()
describe 'library', ->
it 'should exist', (done) ->
should.exist index
done()
describe 'adding the plugin', ->
it 'should work', (done) ->
SimpleSchema.plugin index.filePlugin,
name: "photo",
upload_to: index.make_upload_to_model(uploads, 'photos'),
relative_to: uploads_base
SimpleModel = db.model("SimpleModel", SimpleSchema)
instance = new SimpleModel({name: 'testName', title: 'testTitle'})
should.exist instance
should.equal instance.isModified(), true
instance.should.have.property 'name', '<NAME> <NAME>'
instance.should.have.property 'title', 'testTitle'
instance.should.have.property 'photo'
should.exist instance.photo
instance.photo.should.have.property 'name'
instance.photo.should.have.property 'path'
instance.photo.should.have.property 'rel'
instance.photo.should.have.property 'type'
instance.photo.should.have.property 'size'
instance.photo.should.have.property 'lastModified'
should.not.exist instance.photo.name
should.not.exist instance.photo.path
should.not.exist instance.photo.rel
should.not.exist instance.photo.type
should.not.exist instance.photo.size
should.not.exist instance.photo.lastModified
done()
describe 'assigning to the instance field', ->
it 'should populate subfields', (done) ->
SimpleSchema.plugin index.filePlugin,
name: "photo",
upload_to: index.make_upload_to_model(uploads, 'photos'),
relative_to: uploads_base
SimpleModel = db.model("SimpleModel", SimpleSchema)
instance = new SimpleModel({name: '<NAME> <NAME>', title: 'testTitle'})
should.exist instance
should.exist instance.photo
should.equal instance.isModified(), true
fs.writeFile tmpFilePath, "Dummy content here.\n", (err) ->
return done(err) if (err)
instance.set('photo.file', uploadedFile)
# give the plugin some time to notice the assignment and execute its
# asynchronous code
setTimeout ->
should.equal instance.isModified(), true
should.exist instance.photo.name
should.exist instance.photo.path
should.exist instance.photo.rel
should.exist instance.photo.type
should.exist instance.photo.size
should.exist instance.photo.lastModified
should.equal instance.photo.name, uploadedFile.name
should.not.equal instance.photo.path, uploadedFile.path
should.equal instance.photo.type, uploadedFile.type
should.equal instance.photo.size, uploadedFile.size
should.equal instance.photo.lastModified, uploadedFile.lastModifiedDate
done()
, PLUGIN_TIMEOUT
describe 'assigning to the instance field', ->
it 'should mark as modified', (done) ->
SimpleSchema.plugin index.filePlugin,
name: "photo",
upload_to: index.make_upload_to_model(uploads, 'photos'),
relative_to: uploads_base
SimpleModel = db.model("SimpleModel", SimpleSchema)
instance = new SimpleModel({name: '<NAME>Name', title: 'testTitle'})
should.exist instance
should.equal instance.isModified(), true
instance.save (err) ->
return done(err) if err
should.equal instance.isModified(), false
fs.writeFile tmpFilePath, "Dummy content here.\n", (err) ->
return done(err) if (err)
instance.set('photo.file', uploadedFile)
# give the plugin some time to notice the assignment and execute its
# asynchronous code
setTimeout ->
should.equal instance.isModified(), true
instance.save (err) ->
return done(err) if err
should.equal instance.isModified(), false
done()
, PLUGIN_TIMEOUT
| true | chai = require 'chai'
assert = chai.assert
expect = chai.expect
should = chai.should()
mongoose = require 'mongoose'
fs = require 'fs'
path = require 'path'
index = require '../src/index'
PLUGIN_TIMEOUT = 800
rmDir = (dirPath) ->
try
files = fs.readdirSync(dirPath)
catch e
return
if files.length > 0
i = 0
while i < files.length
continue if files[i] in ['.', '..']
filePath = dirPath + "/" + files[i]
if fs.statSync(filePath).isFile()
fs.unlinkSync filePath
else
rmDir filePath
i++
fs.rmdirSync dirPath
db = mongoose.createConnection('localhost', 'mongoose_file_tests')
db.on('error', console.error.bind(console, 'connection error:'))
uploads_base = __dirname + "/uploads"
uploads = uploads_base + "/u"
tmpFilePath = '/tmp/mongoose-file-test.txt'
uploadedDate = new Date()
uploadedFile =
size: 12345
path: tmpFilePath
name: 'photo.png'
type: 'image/png',
hash: false,
lastModifiedDate: uploadedDate
Schema = mongoose.Schema
ObjectId = Schema.ObjectId
SimpleSchema = new Schema
name: String
title: String
describe 'WHEN working with the plugin', ->
before (done) ->
done()
after (done) ->
SimpleModel = db.model("SimpleModel", SimpleSchema)
SimpleModel.remove {}, (err) ->
return done(err) if err
rmDir(uploads_base)
done()
describe 'library', ->
it 'should exist', (done) ->
should.exist index
done()
describe 'adding the plugin', ->
it 'should work', (done) ->
SimpleSchema.plugin index.filePlugin,
name: "photo",
upload_to: index.make_upload_to_model(uploads, 'photos'),
relative_to: uploads_base
SimpleModel = db.model("SimpleModel", SimpleSchema)
instance = new SimpleModel({name: 'testName', title: 'testTitle'})
should.exist instance
should.equal instance.isModified(), true
instance.should.have.property 'name', 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI'
instance.should.have.property 'title', 'testTitle'
instance.should.have.property 'photo'
should.exist instance.photo
instance.photo.should.have.property 'name'
instance.photo.should.have.property 'path'
instance.photo.should.have.property 'rel'
instance.photo.should.have.property 'type'
instance.photo.should.have.property 'size'
instance.photo.should.have.property 'lastModified'
should.not.exist instance.photo.name
should.not.exist instance.photo.path
should.not.exist instance.photo.rel
should.not.exist instance.photo.type
should.not.exist instance.photo.size
should.not.exist instance.photo.lastModified
done()
describe 'assigning to the instance field', ->
it 'should populate subfields', (done) ->
SimpleSchema.plugin index.filePlugin,
name: "photo",
upload_to: index.make_upload_to_model(uploads, 'photos'),
relative_to: uploads_base
SimpleModel = db.model("SimpleModel", SimpleSchema)
instance = new SimpleModel({name: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI', title: 'testTitle'})
should.exist instance
should.exist instance.photo
should.equal instance.isModified(), true
fs.writeFile tmpFilePath, "Dummy content here.\n", (err) ->
return done(err) if (err)
instance.set('photo.file', uploadedFile)
# give the plugin some time to notice the assignment and execute its
# asynchronous code
setTimeout ->
should.equal instance.isModified(), true
should.exist instance.photo.name
should.exist instance.photo.path
should.exist instance.photo.rel
should.exist instance.photo.type
should.exist instance.photo.size
should.exist instance.photo.lastModified
should.equal instance.photo.name, uploadedFile.name
should.not.equal instance.photo.path, uploadedFile.path
should.equal instance.photo.type, uploadedFile.type
should.equal instance.photo.size, uploadedFile.size
should.equal instance.photo.lastModified, uploadedFile.lastModifiedDate
done()
, PLUGIN_TIMEOUT
describe 'assigning to the instance field', ->
it 'should mark as modified', (done) ->
SimpleSchema.plugin index.filePlugin,
name: "photo",
upload_to: index.make_upload_to_model(uploads, 'photos'),
relative_to: uploads_base
SimpleModel = db.model("SimpleModel", SimpleSchema)
instance = new SimpleModel({name: 'PI:NAME:<NAME>END_PIName', title: 'testTitle'})
should.exist instance
should.equal instance.isModified(), true
instance.save (err) ->
return done(err) if err
should.equal instance.isModified(), false
fs.writeFile tmpFilePath, "Dummy content here.\n", (err) ->
return done(err) if (err)
instance.set('photo.file', uploadedFile)
# give the plugin some time to notice the assignment and execute its
# asynchronous code
setTimeout ->
should.equal instance.isModified(), true
instance.save (err) ->
return done(err) if err
should.equal instance.isModified(), false
done()
, PLUGIN_TIMEOUT
|
[
{
"context": "###\n# config/env/test.coffee\n#\n# © 2014 Dan Nichols\n# See LICENSE for more details\n#\n# Test environme",
"end": 51,
"score": 0.9996894598007202,
"start": 40,
"tag": "NAME",
"value": "Dan Nichols"
}
] | lib/config/env/test.coffee | dlnichols/h_media | 0 | ###
# config/env/test.coffee
#
# © 2014 Dan Nichols
# See LICENSE for more details
#
# Test environment setup
###
'use strict'
###
# Test environment
###
module.exports = exports =
env: 'test'
port: process.env.PORT or 3001
logger: null
mongo:
uri: 'mongodb://localhost/h_media-test'
| 45928 | ###
# config/env/test.coffee
#
# © 2014 <NAME>
# See LICENSE for more details
#
# Test environment setup
###
'use strict'
###
# Test environment
###
module.exports = exports =
env: 'test'
port: process.env.PORT or 3001
logger: null
mongo:
uri: 'mongodb://localhost/h_media-test'
| true | ###
# config/env/test.coffee
#
# © 2014 PI:NAME:<NAME>END_PI
# See LICENSE for more details
#
# Test environment setup
###
'use strict'
###
# Test environment
###
module.exports = exports =
env: 'test'
port: process.env.PORT or 3001
logger: null
mongo:
uri: 'mongodb://localhost/h_media-test'
|
[
{
"context": " #\n super( method, url, async, username, password )\n else\n ",
"end": 4931,
"score": 0.9914649128913879,
"start": 4923,
"tag": "USERNAME",
"value": "username"
},
{
"context": " @timeout\n\n @request.... | src/xdm.coffee | Qwerios/madlib-xhr-xdm | 0 | # The XDM variant of the browser XHR. If an xdm settings section exists for the
# called url we will use the easyXDM based fall back
#
( ( factory ) ->
if typeof exports is "object"
module.exports = factory(
require "madlib-console"
require "q"
require "madlib-xhr"
require "madlib-shim-easyxdm"
require "madlib-hostmapping"
require "madlib-xmldom"
require "madlib-promise-queue"
)
else if typeof define is "function" and define.amd
define( [
"madlib-console"
"q"
"madlib-xhr"
"madlib-shim-easyxdm"
"madlib-hostmapping"
"madlib-xmldom"
"madlib-promise-queue"
], factory )
)( ( console, Q, XHR, easyXDMShim, HostMapping, xmldom, Queue ) ->
# The XDM variant of xhr uses our custom easyXDM based fall back for older
# browsers that don't support CORS.
# The XDM channel is also used if the service provider doesn't support CORS.
#
# Keep in mind you need a valid entry in the settings module and provider
# files need to be deployed on the server. This module transparently supports
# older v2 providers
#
class XDM extends XHR
constructor: ( settings ) ->
# Let the base XHR class setup itself first
#
super( settings )
# Create our host mapping instance
#
@hostMapping = new HostMapping( settings )
# XDM channels are managed and reused per host.
# Because multiple versions of the XDM module may exist we need to expose
# the shared channels on a global variable.
# Since XDM is a browser only thing we can use the window object directly
#
if not window.xdmChannelPool?
window.xdmChannelPool = {}
if not window.xdmChannelQueue?
window.xdmChannelQueue = new Queue( 1 )
@xdmChannelPool = window.xdmChannelPool
@xdmChannel
@xdmSettings
createXDMChannel: ( callback ) ->
url = @xdmSettings.xdmProvider
hostName = @hostMapping.extractHostName( url )
hostBaseUrl = url.substr( 0, url.lastIndexOf( "/" ) + 1 )
swfUrl = hostBaseUrl + "easyxdm.swf"
# Check if there is an existing channel
#
if @xdmChannelPool[ hostName ]?
console.log( "[XDM] Found existing channel for: #{@xdmSettings.xdmProvider}" )
return @xdmChannelPool[ hostName ]
console.log( "[XDM] Creating channel for: #{@xdmSettings.xdmProvider}" );
# Create a new XDM channel
#
options =
remote: url
swf: swfUrl
onReady: callback
rpcChannel =
remote:
ping: {}
request: {}
getCookie: {}
setCookie: {}
deleteCookie: {}
# easyXDM is not a CommonJS module. The shim we required ensures
# the global object is available
#
remote = new window.easyXDM.Rpc( options, rpcChannel )
# Add the channel to the pool for future use
#
@xdmChannelPool[ hostName ] = remote
return remote
open: ( method, url, async, username, password ) ->
# NOTE: We are not calling @createTransport here like the normal XHR does
#
# Retrieve the XDM settings for the target host
#
@xdmSettings = @hostMapping.getXdmSettings( url )
# XDM calls are always async
#
async = true
# Check if the host is present in the xdm settings
#
if not @xdmSettings? or @isSameOrigin( url )
# Not an XDM call
# Use the super class to create an XHR transport
# The existence of an @transport indicates a non XDM call
#
super( method, url, async, username, password )
else
# If the xdmSettings indicate the server should have CORS and if
# the browser supports it we don't have to use the XDM channel.
# In an application that uses different servers it can happen that
# the xdm enabled xhr is used for some and not for others
#
if ( @xdmSettings.cors and ( new XMLHttpRequest() )[ "withCredentials" ]? )
console.log( "[XDM] Open using available CORS support" )
# Use CORS instead
#
super( method, url, async, username, password )
else
# Clear @transport in case someone is reusing this XHR instance (bad boy!)
#
@transport = null
# Get or create the XML channel
#
@xdmChannel = @createXDMChannel()
@request =
headers: {}
url: url
method: method
timeout: @timeout
@request.username = username if username?
@request.password = password if password?
send: ( data ) ->
if @transport
# Not an XDM call so let the base XHR handle the request
#
super( data )
else
@deferred = Q.defer()
@request.data = data
# All calls using the XDM channel need to be marshalled as text
# So when constructing an answer we need to handle the conversion
# to what the caller expects (XML Document, Object, etc)
#
# Prepare the call using the parameters in @request
#
parameters =
url: @request.url
accepts: @request.accepts
contentType: @request.contentType
headers: @request.headers
data: data
cache: @request.cache
timeout: @request.timeout
username: @request.username
password: @request.password
# V2 XDM providers use jQuery style parameters
# V3 XDM providers use MAD XHR parameters
#
# Translation from MAD to jQuery is:
# * type -> dataType
# * method -> type
#
# NOTE: The use of headers requires a jQuery 1.5+ XDM provider
#
if ( @xdmSettings.xdmVersion < 3 )
parameters.dataType = "text"
parameters.type = @request.method
else
parameters.type = @request.type
parameters.method = @request.method
# Wait for a spot in XDM queue
#
window.xdmChannelQueue.ready()
.then( () =>
# Start the request timeout check
# This is our failsafe timeout check
# If timeout is set to 0 it means we will wait indefinitely
# XDM timout is half a second more then normal XHR because
# the XHR fallback timeout on the other side of the channel
# might also occur and there could be a small delay due to
# transport
#
if @timeout isnt 0
@timer = setTimeout( =>
# Free up our spot in the queue
#
window.xdmChannelQueue.done()
@createTimeoutResponse()
, @timeout + 1500 )
# Do the XHR call
#
try
@xdmChannel.request( parameters, ( response ) =>
# Free up our spot in the queue
#
window.xdmChannelQueue.done()
# Stop the timeout fall-back
#
clearTimeout( @timer )
console.log( "[XDM] consumer success", response )
# Convert XDM V2 response format
#
response = @convertV2Response( response ) if ( @xdmSettings.xdmVersion < 3 )
@createSuccessResponse( response )
, ( error ) =>
# Free up our spot in the queue
#
window.xdmChannelQueue.done()
# Stop the timeout fall-back
#
clearTimeout( @timer )
console.log( "[XDM] consumer error", error )
if ( @xdmSettings.xdmVersion < 3 )
# Convert XDM V2 response format
#
error = @convertV2Response( error )
else
error = error.message or error
@createErrorResponse( error )
)
catch xhrError
# Free up our spot in the queue
#
window.xdmChannelQueue.done()
# Stop the timeout fall-back
#
clearTimeout( @timer )
# NOTE: Consuming exceptions might not be the way to go here
# But this way the promise will be rejected as expected
#
console.error( "[XHR] Error during request", xhrError )
return
)
.done()
return @deferred.promise
isSameOrigin: ( url ) ->
# Check if window.location exists
# If it doesn't exist there should be no cross-domain restriction
#
isSameOrigin = true
if window? and document?
location = window.location
aLink = document.createElement( "a" )
aLink.href = url
isSameOrigin =
aLink.hostname is location.hostname and
aLink.port is location.port and
aLink.protocol is location.protocol
convertV2Response: ( response ) ->
xhr = response.xhr
# The V2 provider has a different mapping for the response data
# We will map it to the new V3 format here
#
newResponse =
request: @request
response: xhr.responseText
status: xhr.status
statusText: xhr.statusText
createSuccessResponse: ( xhrResponse ) ->
if @transport
# Not an XDM call
#
super( xhrResponse )
else if ( @xdmSettings.cors and ( new XMLHttpRequest() )[ "withCredentials" ]? )
# Using CORS isnstead of XDM
#
super( xhrResponse )
else
# Some XHR don't implement .response so fall-back to .responseText
#
response = xhrResponse.response || xhrResponse.responseText || xhrResponse.statusText
status = parseInt( xhrResponse.status, 10 )
if @request.type is "json" and typeof response is "string"
# Try to parse the JSON response
# Can be empty for 204 no content response
#
if response
try
response = JSON.parse( response )
catch jsonError
console.warn( "[XHR] Failed JSON parse, returning plain text", @request.url )
response = xhrResponse.response || xhrResponse.responseText || xhrResponse.statusText
else if @request.type is "xml" and typeof response is "string" and response.substr( 0, 5 ) is "<?xml"
# Try to parse the XML response
#
if response
try
response = xmldom.parse( response )
catch xmlError
console.warn( "[XHR] Failed XML parse, returning plain text", @request.url )
response = xhrResponse.responseText
# A successful XDM channel response can still be an XHR error response
#
if ( status >= 200 and status < 300 ) or status is 1223
# Internet Explorer mangles the 204 no content status code
#
status = 204 if status is 1233
@deferred.resolve(
request: @request
response: response
status: status
statusText: xhrResponse.statusText
)
else
@deferred.reject(
request: @request
response: response
status: status
statusText: xhrResponse.statusText
)
createErrorResponse: ( xhrResponse ) ->
if @transport
# Not an XDM call
#
super( xhrResponse )
else if ( @xdmSettings.cors and ( new XMLHttpRequest() )[ "withCredentials" ]? )
# Using CORS instead of XDM
#
super( xhrResponse )
else
response = xhrResponse.response || xhrResponse.responseText || xhrResponse.statusText
if @request.type is "json" and typeof response is "string"
# Try to parse the JSON response
# Can be empty for 204 no content response
#
if response
try
response = JSON.parse( response )
catch jsonError
console.warn( "[XHR] Failed JSON parse, returning plain text", @request.url )
response = xhrResponse.response || xhrResponse.responseText || xhrResponse.statusText
@deferred.reject(
request: @request
response: response
status: xhrResponse.status
statusText: xhrResponse.statusText
)
) | 159982 | # The XDM variant of the browser XHR. If an xdm settings section exists for the
# called url we will use the easyXDM based fall back
#
( ( factory ) ->
if typeof exports is "object"
module.exports = factory(
require "madlib-console"
require "q"
require "madlib-xhr"
require "madlib-shim-easyxdm"
require "madlib-hostmapping"
require "madlib-xmldom"
require "madlib-promise-queue"
)
else if typeof define is "function" and define.amd
define( [
"madlib-console"
"q"
"madlib-xhr"
"madlib-shim-easyxdm"
"madlib-hostmapping"
"madlib-xmldom"
"madlib-promise-queue"
], factory )
)( ( console, Q, XHR, easyXDMShim, HostMapping, xmldom, Queue ) ->
# The XDM variant of xhr uses our custom easyXDM based fall back for older
# browsers that don't support CORS.
# The XDM channel is also used if the service provider doesn't support CORS.
#
# Keep in mind you need a valid entry in the settings module and provider
# files need to be deployed on the server. This module transparently supports
# older v2 providers
#
class XDM extends XHR
constructor: ( settings ) ->
# Let the base XHR class setup itself first
#
super( settings )
# Create our host mapping instance
#
@hostMapping = new HostMapping( settings )
# XDM channels are managed and reused per host.
# Because multiple versions of the XDM module may exist we need to expose
# the shared channels on a global variable.
# Since XDM is a browser only thing we can use the window object directly
#
if not window.xdmChannelPool?
window.xdmChannelPool = {}
if not window.xdmChannelQueue?
window.xdmChannelQueue = new Queue( 1 )
@xdmChannelPool = window.xdmChannelPool
@xdmChannel
@xdmSettings
createXDMChannel: ( callback ) ->
url = @xdmSettings.xdmProvider
hostName = @hostMapping.extractHostName( url )
hostBaseUrl = url.substr( 0, url.lastIndexOf( "/" ) + 1 )
swfUrl = hostBaseUrl + "easyxdm.swf"
# Check if there is an existing channel
#
if @xdmChannelPool[ hostName ]?
console.log( "[XDM] Found existing channel for: #{@xdmSettings.xdmProvider}" )
return @xdmChannelPool[ hostName ]
console.log( "[XDM] Creating channel for: #{@xdmSettings.xdmProvider}" );
# Create a new XDM channel
#
options =
remote: url
swf: swfUrl
onReady: callback
rpcChannel =
remote:
ping: {}
request: {}
getCookie: {}
setCookie: {}
deleteCookie: {}
# easyXDM is not a CommonJS module. The shim we required ensures
# the global object is available
#
remote = new window.easyXDM.Rpc( options, rpcChannel )
# Add the channel to the pool for future use
#
@xdmChannelPool[ hostName ] = remote
return remote
open: ( method, url, async, username, password ) ->
# NOTE: We are not calling @createTransport here like the normal XHR does
#
# Retrieve the XDM settings for the target host
#
@xdmSettings = @hostMapping.getXdmSettings( url )
# XDM calls are always async
#
async = true
# Check if the host is present in the xdm settings
#
if not @xdmSettings? or @isSameOrigin( url )
# Not an XDM call
# Use the super class to create an XHR transport
# The existence of an @transport indicates a non XDM call
#
super( method, url, async, username, password )
else
# If the xdmSettings indicate the server should have CORS and if
# the browser supports it we don't have to use the XDM channel.
# In an application that uses different servers it can happen that
# the xdm enabled xhr is used for some and not for others
#
if ( @xdmSettings.cors and ( new XMLHttpRequest() )[ "withCredentials" ]? )
console.log( "[XDM] Open using available CORS support" )
# Use CORS instead
#
super( method, url, async, username, password )
else
# Clear @transport in case someone is reusing this XHR instance (bad boy!)
#
@transport = null
# Get or create the XML channel
#
@xdmChannel = @createXDMChannel()
@request =
headers: {}
url: url
method: method
timeout: @timeout
@request.username = username if username?
@request.password = <PASSWORD> if <PASSWORD>?
send: ( data ) ->
if @transport
# Not an XDM call so let the base XHR handle the request
#
super( data )
else
@deferred = Q.defer()
@request.data = data
# All calls using the XDM channel need to be marshalled as text
# So when constructing an answer we need to handle the conversion
# to what the caller expects (XML Document, Object, etc)
#
# Prepare the call using the parameters in @request
#
parameters =
url: @request.url
accepts: @request.accepts
contentType: @request.contentType
headers: @request.headers
data: data
cache: @request.cache
timeout: @request.timeout
username: @request.username
password: <PASSWORD>
# V2 XDM providers use jQuery style parameters
# V3 XDM providers use MAD XHR parameters
#
# Translation from MAD to jQuery is:
# * type -> dataType
# * method -> type
#
# NOTE: The use of headers requires a jQuery 1.5+ XDM provider
#
if ( @xdmSettings.xdmVersion < 3 )
parameters.dataType = "text"
parameters.type = @request.method
else
parameters.type = @request.type
parameters.method = @request.method
# Wait for a spot in XDM queue
#
window.xdmChannelQueue.ready()
.then( () =>
# Start the request timeout check
# This is our failsafe timeout check
# If timeout is set to 0 it means we will wait indefinitely
# XDM timout is half a second more then normal XHR because
# the XHR fallback timeout on the other side of the channel
# might also occur and there could be a small delay due to
# transport
#
if @timeout isnt 0
@timer = setTimeout( =>
# Free up our spot in the queue
#
window.xdmChannelQueue.done()
@createTimeoutResponse()
, @timeout + 1500 )
# Do the XHR call
#
try
@xdmChannel.request( parameters, ( response ) =>
# Free up our spot in the queue
#
window.xdmChannelQueue.done()
# Stop the timeout fall-back
#
clearTimeout( @timer )
console.log( "[XDM] consumer success", response )
# Convert XDM V2 response format
#
response = @convertV2Response( response ) if ( @xdmSettings.xdmVersion < 3 )
@createSuccessResponse( response )
, ( error ) =>
# Free up our spot in the queue
#
window.xdmChannelQueue.done()
# Stop the timeout fall-back
#
clearTimeout( @timer )
console.log( "[XDM] consumer error", error )
if ( @xdmSettings.xdmVersion < 3 )
# Convert XDM V2 response format
#
error = @convertV2Response( error )
else
error = error.message or error
@createErrorResponse( error )
)
catch xhrError
# Free up our spot in the queue
#
window.xdmChannelQueue.done()
# Stop the timeout fall-back
#
clearTimeout( @timer )
# NOTE: Consuming exceptions might not be the way to go here
# But this way the promise will be rejected as expected
#
console.error( "[XHR] Error during request", xhrError )
return
)
.done()
return @deferred.promise
isSameOrigin: ( url ) ->
# Check if window.location exists
# If it doesn't exist there should be no cross-domain restriction
#
isSameOrigin = true
if window? and document?
location = window.location
aLink = document.createElement( "a" )
aLink.href = url
isSameOrigin =
aLink.hostname is location.hostname and
aLink.port is location.port and
aLink.protocol is location.protocol
convertV2Response: ( response ) ->
xhr = response.xhr
# The V2 provider has a different mapping for the response data
# We will map it to the new V3 format here
#
newResponse =
request: @request
response: xhr.responseText
status: xhr.status
statusText: xhr.statusText
createSuccessResponse: ( xhrResponse ) ->
if @transport
# Not an XDM call
#
super( xhrResponse )
else if ( @xdmSettings.cors and ( new XMLHttpRequest() )[ "withCredentials" ]? )
# Using CORS isnstead of XDM
#
super( xhrResponse )
else
# Some XHR don't implement .response so fall-back to .responseText
#
response = xhrResponse.response || xhrResponse.responseText || xhrResponse.statusText
status = parseInt( xhrResponse.status, 10 )
if @request.type is "json" and typeof response is "string"
# Try to parse the JSON response
# Can be empty for 204 no content response
#
if response
try
response = JSON.parse( response )
catch jsonError
console.warn( "[XHR] Failed JSON parse, returning plain text", @request.url )
response = xhrResponse.response || xhrResponse.responseText || xhrResponse.statusText
else if @request.type is "xml" and typeof response is "string" and response.substr( 0, 5 ) is "<?xml"
# Try to parse the XML response
#
if response
try
response = xmldom.parse( response )
catch xmlError
console.warn( "[XHR] Failed XML parse, returning plain text", @request.url )
response = xhrResponse.responseText
# A successful XDM channel response can still be an XHR error response
#
if ( status >= 200 and status < 300 ) or status is 1223
# Internet Explorer mangles the 204 no content status code
#
status = 204 if status is 1233
@deferred.resolve(
request: @request
response: response
status: status
statusText: xhrResponse.statusText
)
else
@deferred.reject(
request: @request
response: response
status: status
statusText: xhrResponse.statusText
)
createErrorResponse: ( xhrResponse ) ->
if @transport
# Not an XDM call
#
super( xhrResponse )
else if ( @xdmSettings.cors and ( new XMLHttpRequest() )[ "withCredentials" ]? )
# Using CORS instead of XDM
#
super( xhrResponse )
else
response = xhrResponse.response || xhrResponse.responseText || xhrResponse.statusText
if @request.type is "json" and typeof response is "string"
# Try to parse the JSON response
# Can be empty for 204 no content response
#
if response
try
response = JSON.parse( response )
catch jsonError
console.warn( "[XHR] Failed JSON parse, returning plain text", @request.url )
response = xhrResponse.response || xhrResponse.responseText || xhrResponse.statusText
@deferred.reject(
request: @request
response: response
status: xhrResponse.status
statusText: xhrResponse.statusText
)
) | true | # The XDM variant of the browser XHR. If an xdm settings section exists for the
# called url we will use the easyXDM based fall back
#
( ( factory ) ->
if typeof exports is "object"
module.exports = factory(
require "madlib-console"
require "q"
require "madlib-xhr"
require "madlib-shim-easyxdm"
require "madlib-hostmapping"
require "madlib-xmldom"
require "madlib-promise-queue"
)
else if typeof define is "function" and define.amd
define( [
"madlib-console"
"q"
"madlib-xhr"
"madlib-shim-easyxdm"
"madlib-hostmapping"
"madlib-xmldom"
"madlib-promise-queue"
], factory )
)( ( console, Q, XHR, easyXDMShim, HostMapping, xmldom, Queue ) ->
# The XDM variant of xhr uses our custom easyXDM based fall back for older
# browsers that don't support CORS.
# The XDM channel is also used if the service provider doesn't support CORS.
#
# Keep in mind you need a valid entry in the settings module and provider
# files need to be deployed on the server. This module transparently supports
# older v2 providers
#
class XDM extends XHR
constructor: ( settings ) ->
# Let the base XHR class setup itself first
#
super( settings )
# Create our host mapping instance
#
@hostMapping = new HostMapping( settings )
# XDM channels are managed and reused per host.
# Because multiple versions of the XDM module may exist we need to expose
# the shared channels on a global variable.
# Since XDM is a browser only thing we can use the window object directly
#
if not window.xdmChannelPool?
window.xdmChannelPool = {}
if not window.xdmChannelQueue?
window.xdmChannelQueue = new Queue( 1 )
@xdmChannelPool = window.xdmChannelPool
@xdmChannel
@xdmSettings
createXDMChannel: ( callback ) ->
url = @xdmSettings.xdmProvider
hostName = @hostMapping.extractHostName( url )
hostBaseUrl = url.substr( 0, url.lastIndexOf( "/" ) + 1 )
swfUrl = hostBaseUrl + "easyxdm.swf"
# Check if there is an existing channel
#
if @xdmChannelPool[ hostName ]?
console.log( "[XDM] Found existing channel for: #{@xdmSettings.xdmProvider}" )
return @xdmChannelPool[ hostName ]
console.log( "[XDM] Creating channel for: #{@xdmSettings.xdmProvider}" );
# Create a new XDM channel
#
options =
remote: url
swf: swfUrl
onReady: callback
rpcChannel =
remote:
ping: {}
request: {}
getCookie: {}
setCookie: {}
deleteCookie: {}
# easyXDM is not a CommonJS module. The shim we required ensures
# the global object is available
#
remote = new window.easyXDM.Rpc( options, rpcChannel )
# Add the channel to the pool for future use
#
@xdmChannelPool[ hostName ] = remote
return remote
open: ( method, url, async, username, password ) ->
# NOTE: We are not calling @createTransport here like the normal XHR does
#
# Retrieve the XDM settings for the target host
#
@xdmSettings = @hostMapping.getXdmSettings( url )
# XDM calls are always async
#
async = true
# Check if the host is present in the xdm settings
#
if not @xdmSettings? or @isSameOrigin( url )
# Not an XDM call
# Use the super class to create an XHR transport
# The existence of an @transport indicates a non XDM call
#
super( method, url, async, username, password )
else
# If the xdmSettings indicate the server should have CORS and if
# the browser supports it we don't have to use the XDM channel.
# In an application that uses different servers it can happen that
# the xdm enabled xhr is used for some and not for others
#
if ( @xdmSettings.cors and ( new XMLHttpRequest() )[ "withCredentials" ]? )
console.log( "[XDM] Open using available CORS support" )
# Use CORS instead
#
super( method, url, async, username, password )
else
# Clear @transport in case someone is reusing this XHR instance (bad boy!)
#
@transport = null
# Get or create the XML channel
#
@xdmChannel = @createXDMChannel()
@request =
headers: {}
url: url
method: method
timeout: @timeout
@request.username = username if username?
@request.password = PI:PASSWORD:<PASSWORD>END_PI if PI:PASSWORD:<PASSWORD>END_PI?
send: ( data ) ->
if @transport
# Not an XDM call so let the base XHR handle the request
#
super( data )
else
@deferred = Q.defer()
@request.data = data
# All calls using the XDM channel need to be marshalled as text
# So when constructing an answer we need to handle the conversion
# to what the caller expects (XML Document, Object, etc)
#
# Prepare the call using the parameters in @request
#
parameters =
url: @request.url
accepts: @request.accepts
contentType: @request.contentType
headers: @request.headers
data: data
cache: @request.cache
timeout: @request.timeout
username: @request.username
password: PI:PASSWORD:<PASSWORD>END_PI
# V2 XDM providers use jQuery style parameters
# V3 XDM providers use MAD XHR parameters
#
# Translation from MAD to jQuery is:
# * type -> dataType
# * method -> type
#
# NOTE: The use of headers requires a jQuery 1.5+ XDM provider
#
if ( @xdmSettings.xdmVersion < 3 )
parameters.dataType = "text"
parameters.type = @request.method
else
parameters.type = @request.type
parameters.method = @request.method
# Wait for a spot in XDM queue
#
window.xdmChannelQueue.ready()
.then( () =>
# Start the request timeout check
# This is our failsafe timeout check
# If timeout is set to 0 it means we will wait indefinitely
# XDM timout is half a second more then normal XHR because
# the XHR fallback timeout on the other side of the channel
# might also occur and there could be a small delay due to
# transport
#
if @timeout isnt 0
@timer = setTimeout( =>
# Free up our spot in the queue
#
window.xdmChannelQueue.done()
@createTimeoutResponse()
, @timeout + 1500 )
# Do the XHR call
#
try
@xdmChannel.request( parameters, ( response ) =>
# Free up our spot in the queue
#
window.xdmChannelQueue.done()
# Stop the timeout fall-back
#
clearTimeout( @timer )
console.log( "[XDM] consumer success", response )
# Convert XDM V2 response format
#
response = @convertV2Response( response ) if ( @xdmSettings.xdmVersion < 3 )
@createSuccessResponse( response )
, ( error ) =>
# Free up our spot in the queue
#
window.xdmChannelQueue.done()
# Stop the timeout fall-back
#
clearTimeout( @timer )
console.log( "[XDM] consumer error", error )
if ( @xdmSettings.xdmVersion < 3 )
# Convert XDM V2 response format
#
error = @convertV2Response( error )
else
error = error.message or error
@createErrorResponse( error )
)
catch xhrError
# Free up our spot in the queue
#
window.xdmChannelQueue.done()
# Stop the timeout fall-back
#
clearTimeout( @timer )
# NOTE: Consuming exceptions might not be the way to go here
# But this way the promise will be rejected as expected
#
console.error( "[XHR] Error during request", xhrError )
return
)
.done()
return @deferred.promise
isSameOrigin: ( url ) ->
# Check if window.location exists
# If it doesn't exist there should be no cross-domain restriction
#
isSameOrigin = true
if window? and document?
location = window.location
aLink = document.createElement( "a" )
aLink.href = url
isSameOrigin =
aLink.hostname is location.hostname and
aLink.port is location.port and
aLink.protocol is location.protocol
convertV2Response: ( response ) ->
xhr = response.xhr
# The V2 provider has a different mapping for the response data
# We will map it to the new V3 format here
#
newResponse =
request: @request
response: xhr.responseText
status: xhr.status
statusText: xhr.statusText
createSuccessResponse: ( xhrResponse ) ->
if @transport
# Not an XDM call
#
super( xhrResponse )
else if ( @xdmSettings.cors and ( new XMLHttpRequest() )[ "withCredentials" ]? )
# Using CORS isnstead of XDM
#
super( xhrResponse )
else
# Some XHR don't implement .response so fall-back to .responseText
#
response = xhrResponse.response || xhrResponse.responseText || xhrResponse.statusText
status = parseInt( xhrResponse.status, 10 )
if @request.type is "json" and typeof response is "string"
# Try to parse the JSON response
# Can be empty for 204 no content response
#
if response
try
response = JSON.parse( response )
catch jsonError
console.warn( "[XHR] Failed JSON parse, returning plain text", @request.url )
response = xhrResponse.response || xhrResponse.responseText || xhrResponse.statusText
else if @request.type is "xml" and typeof response is "string" and response.substr( 0, 5 ) is "<?xml"
# Try to parse the XML response
#
if response
try
response = xmldom.parse( response )
catch xmlError
console.warn( "[XHR] Failed XML parse, returning plain text", @request.url )
response = xhrResponse.responseText
# A successful XDM channel response can still be an XHR error response
#
if ( status >= 200 and status < 300 ) or status is 1223
# Internet Explorer mangles the 204 no content status code
#
status = 204 if status is 1233
@deferred.resolve(
request: @request
response: response
status: status
statusText: xhrResponse.statusText
)
else
@deferred.reject(
request: @request
response: response
status: status
statusText: xhrResponse.statusText
)
createErrorResponse: ( xhrResponse ) ->
if @transport
# Not an XDM call
#
super( xhrResponse )
else if ( @xdmSettings.cors and ( new XMLHttpRequest() )[ "withCredentials" ]? )
# Using CORS instead of XDM
#
super( xhrResponse )
else
response = xhrResponse.response || xhrResponse.responseText || xhrResponse.statusText
if @request.type is "json" and typeof response is "string"
# Try to parse the JSON response
# Can be empty for 204 no content response
#
if response
try
response = JSON.parse( response )
catch jsonError
console.warn( "[XHR] Failed JSON parse, returning plain text", @request.url )
response = xhrResponse.response || xhrResponse.responseText || xhrResponse.statusText
@deferred.reject(
request: @request
response: response
status: xhrResponse.status
statusText: xhrResponse.statusText
)
) |
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9990074038505554,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-net-keepalive.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
net = require("net")
serverConnection = undefined
echoServer = net.createServer((connection) ->
serverConnection = connection
connection.setTimeout 0
assert.notEqual connection.setKeepAlive, `undefined`
# send a keepalive packet after 1000 ms
connection.setKeepAlive true, 1000
connection.on "end", ->
connection.end()
return
return
)
echoServer.listen common.PORT
echoServer.on "listening", ->
clientConnection = net.createConnection(common.PORT)
clientConnection.setTimeout 0
setTimeout (->
# make sure both connections are still open
assert.equal serverConnection.readyState, "open"
assert.equal clientConnection.readyState, "open"
serverConnection.end()
clientConnection.end()
echoServer.close()
return
), 1200
return
| 75067 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
net = require("net")
serverConnection = undefined
echoServer = net.createServer((connection) ->
serverConnection = connection
connection.setTimeout 0
assert.notEqual connection.setKeepAlive, `undefined`
# send a keepalive packet after 1000 ms
connection.setKeepAlive true, 1000
connection.on "end", ->
connection.end()
return
return
)
echoServer.listen common.PORT
echoServer.on "listening", ->
clientConnection = net.createConnection(common.PORT)
clientConnection.setTimeout 0
setTimeout (->
# make sure both connections are still open
assert.equal serverConnection.readyState, "open"
assert.equal clientConnection.readyState, "open"
serverConnection.end()
clientConnection.end()
echoServer.close()
return
), 1200
return
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
net = require("net")
serverConnection = undefined
echoServer = net.createServer((connection) ->
serverConnection = connection
connection.setTimeout 0
assert.notEqual connection.setKeepAlive, `undefined`
# send a keepalive packet after 1000 ms
connection.setKeepAlive true, 1000
connection.on "end", ->
connection.end()
return
return
)
echoServer.listen common.PORT
echoServer.on "listening", ->
clientConnection = net.createConnection(common.PORT)
clientConnection.setTimeout 0
setTimeout (->
# make sure both connections are still open
assert.equal serverConnection.readyState, "open"
assert.equal clientConnection.readyState, "open"
serverConnection.end()
clientConnection.end()
echoServer.close()
return
), 1200
return
|
[
{
"context": " / 30)\n keygen username, (key) ->\n key = (new Buffer(key)).toString('hex')\n hmac = crypto.createHm",
"end": 329,
"score": 0.8049151301383972,
"start": 318,
"tag": "KEY",
"value": "new Buffer("
},
{
"context": "gen username, (key) ->\n key = (new Buf... | lib/auth-api.coffee | zenozeng/qr-auth | 3 | crypto = require 'crypto'
lm = require './login-manager.js'
module.exports = (req, res, keygen) ->
res.writeHead 200, {'Content-Type': 'text/html'}
{username, hash, sid} = req.body
if hash? # login from api
timestamp = parseInt((new Date().getTime()) / 1000 / 30)
keygen username, (key) ->
key = (new Buffer(key)).toString('hex')
hmac = crypto.createHmac 'sha512', key
hmac.setEncoding 'hex'
hmac.write [username, sid, timestamp].join('')
hmac.end()
if hash is hmac.read()
lm.login sid
res.write JSON.stringify {status: "success"}
else
res.write JSON.stringify {status: "error", error: "hash not match"}
else # login checker
res.write JSON.stringify {login: lm.test(sid)}
res.end()
| 115966 | crypto = require 'crypto'
lm = require './login-manager.js'
module.exports = (req, res, keygen) ->
res.writeHead 200, {'Content-Type': 'text/html'}
{username, hash, sid} = req.body
if hash? # login from api
timestamp = parseInt((new Date().getTime()) / 1000 / 30)
keygen username, (key) ->
key = (<KEY>key)).<KEY>')
hmac = crypto.createHmac 'sha512', key
hmac.setEncoding 'hex'
hmac.write [username, sid, timestamp].join('')
hmac.end()
if hash is hmac.read()
lm.login sid
res.write JSON.stringify {status: "success"}
else
res.write JSON.stringify {status: "error", error: "hash not match"}
else # login checker
res.write JSON.stringify {login: lm.test(sid)}
res.end()
| true | crypto = require 'crypto'
lm = require './login-manager.js'
module.exports = (req, res, keygen) ->
res.writeHead 200, {'Content-Type': 'text/html'}
{username, hash, sid} = req.body
if hash? # login from api
timestamp = parseInt((new Date().getTime()) / 1000 / 30)
keygen username, (key) ->
key = (PI:KEY:<KEY>END_PIkey)).PI:KEY:<KEY>END_PI')
hmac = crypto.createHmac 'sha512', key
hmac.setEncoding 'hex'
hmac.write [username, sid, timestamp].join('')
hmac.end()
if hash is hmac.read()
lm.login sid
res.write JSON.stringify {status: "success"}
else
res.write JSON.stringify {status: "error", error: "hash not match"}
else # login checker
res.write JSON.stringify {login: lm.test(sid)}
res.end()
|
[
{
"context": "**\n * The Calamity day lowers luck.\n *\n * @name Calamity\n * @effect -5% LUCK\n * @category Day\n * @",
"end": 98,
"score": 0.7168852090835571,
"start": 95,
"tag": "NAME",
"value": "Cal"
}
] | src/event/calendar/day/CalamityDay.coffee | sadbear-/IdleLands | 3 |
TimePeriod = require "../../TimePeriod"
`/**
* The Calamity day lowers luck.
*
* @name Calamity
* @effect -5% LUCK
* @category Day
* @package Calendar
*/`
class CalamityDay extends TimePeriod
constructor: ->
@dateName = "Day of Calamity"
@desc = "-5% LUCK"
@luckPercent: -> -5
module.exports = exports = CalamityDay
| 224674 |
TimePeriod = require "../../TimePeriod"
`/**
* The Calamity day lowers luck.
*
* @name <NAME>amity
* @effect -5% LUCK
* @category Day
* @package Calendar
*/`
class CalamityDay extends TimePeriod
constructor: ->
@dateName = "Day of Calamity"
@desc = "-5% LUCK"
@luckPercent: -> -5
module.exports = exports = CalamityDay
| true |
TimePeriod = require "../../TimePeriod"
`/**
* The Calamity day lowers luck.
*
* @name PI:NAME:<NAME>END_PIamity
* @effect -5% LUCK
* @category Day
* @package Calendar
*/`
class CalamityDay extends TimePeriod
constructor: ->
@dateName = "Day of Calamity"
@desc = "-5% LUCK"
@luckPercent: -> -5
module.exports = exports = CalamityDay
|
[
{
"context": " ->\n new DotLedger.Models.Account\n name: 'Some Account'\n balance: 10.00\n updated_at: '2013-01-",
"end": 126,
"score": 0.9965451955795288,
"start": 114,
"tag": "NAME",
"value": "Some Account"
},
{
"context": "model = new DotLedger.Models.Account\n ... | spec/javascripts/dot_ledger/views/accounts/list_item_spec.js.coffee | malclocke/dotledger | 0 | describe "DotLedger.Views.Accounts.ListItem", ->
createModel = ->
new DotLedger.Models.Account
name: 'Some Account'
balance: 10.00
updated_at: '2013-01-01T01:00:00Z'
unsorted_transaction_count: 123
id: 1
createView = (model = createModel()) ->
view = new DotLedger.Views.Accounts.ListItem
model: model
view
it "should be defined", ->
expect(DotLedger.Views.Accounts.ListItem).toBeDefined()
it "should use the correct template", ->
expect(DotLedger.Views.Accounts.ListItem).toUseTemplate('accounts/list_item')
it "can be rendered", ->
view = createView()
expect(view.render).not.toThrow()
it "renders the account name", ->
view = createView().render()
expect(view.$el).toHaveText(/Some Account/)
it "renders the account link", ->
view = createView().render()
expect(view.$el).toContainElement('a[href="/accounts/1?tab=sorted&page=1"]')
it "renders the updated at time", ->
view = createView().render()
expect(view.$el).toContainElement('time[datetime="2013-01-01T01:00:00Z"]')
it "renders unsorted transaction count if greater than 0", ->
view = createView().render()
expect(view.$el).toHaveText(/123 unsorted/)
expect(view.$el).toContainElement('a[href="/accounts/1?tab=unsorted&page=1"]')
it "does not render unsorted transaction count if 0", ->
model = new DotLedger.Models.Account
name: 'Some Account'
balance: 10.00
updated_at: '2013-01-01T01:00:00Z'
unsorted_transaction_count: 0
id: 1
view = createView(model).render()
expect(view.$el).not.toHaveText(/0 unsorted/)
| 76864 | describe "DotLedger.Views.Accounts.ListItem", ->
createModel = ->
new DotLedger.Models.Account
name: '<NAME>'
balance: 10.00
updated_at: '2013-01-01T01:00:00Z'
unsorted_transaction_count: 123
id: 1
createView = (model = createModel()) ->
view = new DotLedger.Views.Accounts.ListItem
model: model
view
it "should be defined", ->
expect(DotLedger.Views.Accounts.ListItem).toBeDefined()
it "should use the correct template", ->
expect(DotLedger.Views.Accounts.ListItem).toUseTemplate('accounts/list_item')
it "can be rendered", ->
view = createView()
expect(view.render).not.toThrow()
it "renders the account name", ->
view = createView().render()
expect(view.$el).toHaveText(/Some Account/)
it "renders the account link", ->
view = createView().render()
expect(view.$el).toContainElement('a[href="/accounts/1?tab=sorted&page=1"]')
it "renders the updated at time", ->
view = createView().render()
expect(view.$el).toContainElement('time[datetime="2013-01-01T01:00:00Z"]')
it "renders unsorted transaction count if greater than 0", ->
view = createView().render()
expect(view.$el).toHaveText(/123 unsorted/)
expect(view.$el).toContainElement('a[href="/accounts/1?tab=unsorted&page=1"]')
it "does not render unsorted transaction count if 0", ->
model = new DotLedger.Models.Account
name: '<NAME>'
balance: 10.00
updated_at: '2013-01-01T01:00:00Z'
unsorted_transaction_count: 0
id: 1
view = createView(model).render()
expect(view.$el).not.toHaveText(/0 unsorted/)
| true | describe "DotLedger.Views.Accounts.ListItem", ->
createModel = ->
new DotLedger.Models.Account
name: 'PI:NAME:<NAME>END_PI'
balance: 10.00
updated_at: '2013-01-01T01:00:00Z'
unsorted_transaction_count: 123
id: 1
createView = (model = createModel()) ->
view = new DotLedger.Views.Accounts.ListItem
model: model
view
it "should be defined", ->
expect(DotLedger.Views.Accounts.ListItem).toBeDefined()
it "should use the correct template", ->
expect(DotLedger.Views.Accounts.ListItem).toUseTemplate('accounts/list_item')
it "can be rendered", ->
view = createView()
expect(view.render).not.toThrow()
it "renders the account name", ->
view = createView().render()
expect(view.$el).toHaveText(/Some Account/)
it "renders the account link", ->
view = createView().render()
expect(view.$el).toContainElement('a[href="/accounts/1?tab=sorted&page=1"]')
it "renders the updated at time", ->
view = createView().render()
expect(view.$el).toContainElement('time[datetime="2013-01-01T01:00:00Z"]')
it "renders unsorted transaction count if greater than 0", ->
view = createView().render()
expect(view.$el).toHaveText(/123 unsorted/)
expect(view.$el).toContainElement('a[href="/accounts/1?tab=unsorted&page=1"]')
it "does not render unsorted transaction count if 0", ->
model = new DotLedger.Models.Account
name: 'PI:NAME:<NAME>END_PI'
balance: 10.00
updated_at: '2013-01-01T01:00:00Z'
unsorted_transaction_count: 0
id: 1
view = createView(model).render()
expect(view.$el).not.toHaveText(/0 unsorted/)
|
[
{
"context": "module.exports =\n name: \"Linus\"\n url: '/linus/:name/:from'\n fields: [\n { na",
"end": 31,
"score": 0.999638557434082,
"start": 26,
"tag": "NAME",
"value": "Linus"
}
] | lib/operations/linus.coffee | brettminnie/foaas | 0 | module.exports =
name: "Linus"
url: '/linus/:name/:from'
fields: [
{ name: 'Name', field: 'name'}
{ name: 'From', field: 'from'}
]
register: (app, output) ->
app.get '/linus/:name/:from', (req, res) ->
message = "#{req.params.name}, there aren't enough swear-words in the English language, so now I'll have to call you perkeleen vittupää just to express my disgust and frustration with this crap."
subtitle = "- #{req.params.from}"
output(req, res, message, subtitle) | 181039 | module.exports =
name: "<NAME>"
url: '/linus/:name/:from'
fields: [
{ name: 'Name', field: 'name'}
{ name: 'From', field: 'from'}
]
register: (app, output) ->
app.get '/linus/:name/:from', (req, res) ->
message = "#{req.params.name}, there aren't enough swear-words in the English language, so now I'll have to call you perkeleen vittupää just to express my disgust and frustration with this crap."
subtitle = "- #{req.params.from}"
output(req, res, message, subtitle) | true | module.exports =
name: "PI:NAME:<NAME>END_PI"
url: '/linus/:name/:from'
fields: [
{ name: 'Name', field: 'name'}
{ name: 'From', field: 'from'}
]
register: (app, output) ->
app.get '/linus/:name/:from', (req, res) ->
message = "#{req.params.name}, there aren't enough swear-words in the English language, so now I'll have to call you perkeleen vittupää just to express my disgust and frustration with this crap."
subtitle = "- #{req.params.from}"
output(req, res, message, subtitle) |
[
{
"context": " keydown: (cb) => windowKeyDown = cb\n\n names = {bill: 'bill', sally: 'sally', bob: 'bob', joe: 'Joe'}\n",
"end": 784,
"score": 0.975897490978241,
"start": 780,
"tag": "NAME",
"value": "bill"
},
{
"context": "wn: (cb) => windowKeyDown = cb\n\n names = {bill: 'bill',... | test/user_input_handler_test.coffee | nornagon/ircv | 20 | describe 'A user input handler', ->
handler = altHeld = val = inputKeyDown = windowKeyDown = undefined
onVal = jasmine.createSpy 'onVal'
keyDown = (code) ->
e =
which: code
altKey: altHeld
isDefaultPrevented: ->
preventDefault: ->
windowKeyDown e
inputKeyDown e
type = (text) ->
val = text
keyDown 13
tab = ->
keyDown 9
ctrl = ->
keyDown 17
numlock = ->
keyDown 144
space = ->
keyDown 32
val += ' '
cursor = (pos) ->
handler._getCursorPosition = -> pos
input =
keydown: (cb) => inputKeyDown = cb
focus: ->
val: (text) ->
if arguments.length == 0
return val
val = text
onVal(text)
window =
keydown: (cb) => windowKeyDown = cb
names = {bill: 'bill', sally: 'sally', bob: 'bob', joe: 'Joe'}
context = currentWindow:
target: '#bash'
conn:
name: 'freenode.net'
irc:
channels: {}
beforeEach ->
handler = new UserInputHandler input, window
handler._setCursorPosition = ->
context.currentWindow.conn.irc.channels['#bash'] = {names}
handler.setContext context
spyOn handler, 'emit'
altHeld = false
onVal.reset()
it "switches to the given window on 'alt-[0-9]'", ->
altHeld = true
keyDown 48 # 0
expect(handler.emit).toHaveBeenCalledWith 'switch_window', 0
keyDown 57 # 9
expect(handler.emit).toHaveBeenCalledWith 'switch_window', 9
it "doesn't switch windows when alt isn't held", ->
keyDown 48 # 0
keyDown 57 # 9
expect(handler.emit).not.toHaveBeenCalled()
it "sends a say command when text is entered", ->
type 'hello world!'
expect(handler.emit).toHaveBeenCalledWith 'command', jasmine.any Object
e = handler.emit.mostRecentCall.args[1]
expect(e.type).toBe 'command'
expect(e.name).toBe 'say'
expect(e.context).toEqual { server: 'freenode.net', channel: '#bash' }
expect(e.args).toEqual 'hello world!'.split ' '
it "sends the given command when a command is entered", ->
type '/kick sugarman for spamming /dance'
expect(handler.emit).toHaveBeenCalledWith 'command', jasmine.any Object
e = handler.emit.mostRecentCall.args[1]
expect(e.type).toBe 'command'
expect(e.name).toBe 'kick'
expect(e.context).toEqual { server: 'freenode.net', channel: '#bash' }
expect(e.args).toEqual 'sugarman for spamming /dance'.split ' '
describe 'auto-complete', ->
it "completes the current word and adds a colon + space after if it starts the phrase", ->
val = 'b'
cursor 1
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'bill: '
it "completes the current word when the cursor is at the begining of the input", ->
val = 'b'
cursor 0
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'bill: '
it "completes the current word and adds a space after if it doesn't start the phrase", ->
val = ' b'
cursor 2
tab()
expect(onVal.mostRecentCall.args[0]).toBe ' bill '
it "completes the current word when the phrase ends with a space", ->
val = 'b '
cursor 1
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'bill: '
it "completes the current word when the cursor is in the middle of a word", ->
val = 'sis cool'
cursor 1
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'sally: is cool'
it "completes the current word, even when the cursor moves", ->
val = 'well, s is great'
cursor 7
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'well, sally is great'
it "completes the current word, even when there is space between the cursor and the word", ->
val = 'well, sal is great'
cursor 15
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'well, sally is great'
it "goes to next completion on tab", ->
val = 'b'
cursor 0
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'bill: '
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'bob: '
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'bill: '
it "stops cycling possible completions only when input is entered", ->
val = 'b'
cursor 0
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'bill: '
ctrl()
numlock()
tab()
cursor 6
expect(onVal.mostRecentCall.args[0]).toBe 'bob: '
space()
tab()
cursor 5
expect(onVal.mostRecentCall.args[0]).toBe 'bob: '
it "does nothing when no completion candidates match", ->
val = 'zack'
cursor 0
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'zack'
it "adds ': ' even when the the full nick is typed out when tab is pressed", ->
val = 'bill'
cursor 4
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'bill: '
describe 'input stack', ->
upArrow = ->
keyDown 38
downArrow = ->
keyDown 40
it "uses the up arrow to show previous commands", ->
type 'hi'
type 'bye'
upArrow()
expect(onVal.mostRecentCall.args[0]).toBe 'bye'
upArrow()
expect(onVal.mostRecentCall.args[0]).toBe 'hi'
it "does nothing when the up arrow is pressed and there is no more previous command", ->
upArrow()
expect(onVal).not.toHaveBeenCalled()
val = 'current text'
upArrow()
expect(onVal).not.toHaveBeenCalled()
type 'hi'
upArrow()
onVal.reset()
upArrow()
upArrow()
expect(onVal).not.toHaveBeenCalled()
it "uses the down arrow to move back toward current commands", ->
type 'hi'
type 'bye'
upArrow()
upArrow()
downArrow()
expect(onVal.mostRecentCall.args[0]).toBe 'bye'
it "displays the current input value as most current previous command", ->
type('hi')
upArrow()
downArrow()
expect(onVal.mostRecentCall.args[0]).toBe ''
type('hi')
val = 'current text'
upArrow()
downArrow()
expect(onVal.mostRecentCall.args[0]).toBe 'current text'
it "does nothing when the down arrow is pressed but there is no more current command", ->
downArrow()
expect(onVal).not.toHaveBeenCalled()
val = 'current text'
downArrow()
expect(onVal).not.toHaveBeenCalled()
type('hi')
upArrow()
downArrow()
onVal.reset()
downArrow()
downArrow()
expect(onVal).not.toHaveBeenCalled()
| 160516 | describe 'A user input handler', ->
handler = altHeld = val = inputKeyDown = windowKeyDown = undefined
onVal = jasmine.createSpy 'onVal'
keyDown = (code) ->
e =
which: code
altKey: altHeld
isDefaultPrevented: ->
preventDefault: ->
windowKeyDown e
inputKeyDown e
type = (text) ->
val = text
keyDown 13
tab = ->
keyDown 9
ctrl = ->
keyDown 17
numlock = ->
keyDown 144
space = ->
keyDown 32
val += ' '
cursor = (pos) ->
handler._getCursorPosition = -> pos
input =
keydown: (cb) => inputKeyDown = cb
focus: ->
val: (text) ->
if arguments.length == 0
return val
val = text
onVal(text)
window =
keydown: (cb) => windowKeyDown = cb
names = {<NAME>: '<NAME>', <NAME>: '<NAME>', <NAME>: '<NAME>', <NAME>: '<NAME>'}
context = currentWindow:
target: '#bash'
conn:
name: 'freenode.net'
irc:
channels: {}
beforeEach ->
handler = new UserInputHandler input, window
handler._setCursorPosition = ->
context.currentWindow.conn.irc.channels['#bash'] = {names}
handler.setContext context
spyOn handler, 'emit'
altHeld = false
onVal.reset()
it "switches to the given window on 'alt-[0-9]'", ->
altHeld = true
keyDown 48 # 0
expect(handler.emit).toHaveBeenCalledWith 'switch_window', 0
keyDown 57 # 9
expect(handler.emit).toHaveBeenCalledWith 'switch_window', 9
it "doesn't switch windows when alt isn't held", ->
keyDown 48 # 0
keyDown 57 # 9
expect(handler.emit).not.toHaveBeenCalled()
it "sends a say command when text is entered", ->
type 'hello world!'
expect(handler.emit).toHaveBeenCalledWith 'command', jasmine.any Object
e = handler.emit.mostRecentCall.args[1]
expect(e.type).toBe 'command'
expect(e.name).toBe 'say'
expect(e.context).toEqual { server: 'freenode.net', channel: '#bash' }
expect(e.args).toEqual 'hello world!'.split ' '
it "sends the given command when a command is entered", ->
type '/kick sugarman for spamming /dance'
expect(handler.emit).toHaveBeenCalledWith 'command', jasmine.any Object
e = handler.emit.mostRecentCall.args[1]
expect(e.type).toBe 'command'
expect(e.name).toBe 'kick'
expect(e.context).toEqual { server: 'freenode.net', channel: '#bash' }
expect(e.args).toEqual 'sugarman for spamming /dance'.split ' '
describe 'auto-complete', ->
it "completes the current word and adds a colon + space after if it starts the phrase", ->
val = 'b'
cursor 1
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'bill: '
it "completes the current word when the cursor is at the begining of the input", ->
val = 'b'
cursor 0
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'bill: '
it "completes the current word and adds a space after if it doesn't start the phrase", ->
val = ' b'
cursor 2
tab()
expect(onVal.mostRecentCall.args[0]).toBe ' bill '
it "completes the current word when the phrase ends with a space", ->
val = 'b '
cursor 1
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'bill: '
it "completes the current word when the cursor is in the middle of a word", ->
val = 'sis cool'
cursor 1
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'sally: is cool'
it "completes the current word, even when the cursor moves", ->
val = 'well, s is great'
cursor 7
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'well, s<NAME> is great'
it "completes the current word, even when there is space between the cursor and the word", ->
val = 'well, sal is great'
cursor 15
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'well, s<NAME> is great'
it "goes to next completion on tab", ->
val = 'b'
cursor 0
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'bill: '
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'bob: '
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'bill: '
it "stops cycling possible completions only when input is entered", ->
val = 'b'
cursor 0
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'bill: '
ctrl()
numlock()
tab()
cursor 6
expect(onVal.mostRecentCall.args[0]).toBe 'bob: '
space()
tab()
cursor 5
expect(onVal.mostRecentCall.args[0]).toBe 'bob: '
it "does nothing when no completion candidates match", ->
val = '<NAME>ack'
cursor 0
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'zack'
it "adds ': ' even when the the full nick is typed out when tab is pressed", ->
val = '<NAME>'
cursor 4
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'bill: '
describe 'input stack', ->
upArrow = ->
keyDown 38
downArrow = ->
keyDown 40
it "uses the up arrow to show previous commands", ->
type 'hi'
type 'bye'
upArrow()
expect(onVal.mostRecentCall.args[0]).toBe 'bye'
upArrow()
expect(onVal.mostRecentCall.args[0]).toBe 'hi'
it "does nothing when the up arrow is pressed and there is no more previous command", ->
upArrow()
expect(onVal).not.toHaveBeenCalled()
val = 'current text'
upArrow()
expect(onVal).not.toHaveBeenCalled()
type 'hi'
upArrow()
onVal.reset()
upArrow()
upArrow()
expect(onVal).not.toHaveBeenCalled()
it "uses the down arrow to move back toward current commands", ->
type 'hi'
type 'bye'
upArrow()
upArrow()
downArrow()
expect(onVal.mostRecentCall.args[0]).toBe 'bye'
it "displays the current input value as most current previous command", ->
type('hi')
upArrow()
downArrow()
expect(onVal.mostRecentCall.args[0]).toBe ''
type('hi')
val = 'current text'
upArrow()
downArrow()
expect(onVal.mostRecentCall.args[0]).toBe 'current text'
it "does nothing when the down arrow is pressed but there is no more current command", ->
downArrow()
expect(onVal).not.toHaveBeenCalled()
val = 'current text'
downArrow()
expect(onVal).not.toHaveBeenCalled()
type('hi')
upArrow()
downArrow()
onVal.reset()
downArrow()
downArrow()
expect(onVal).not.toHaveBeenCalled()
| true | describe 'A user input handler', ->
handler = altHeld = val = inputKeyDown = windowKeyDown = undefined
onVal = jasmine.createSpy 'onVal'
keyDown = (code) ->
e =
which: code
altKey: altHeld
isDefaultPrevented: ->
preventDefault: ->
windowKeyDown e
inputKeyDown e
type = (text) ->
val = text
keyDown 13
tab = ->
keyDown 9
ctrl = ->
keyDown 17
numlock = ->
keyDown 144
space = ->
keyDown 32
val += ' '
cursor = (pos) ->
handler._getCursorPosition = -> pos
input =
keydown: (cb) => inputKeyDown = cb
focus: ->
val: (text) ->
if arguments.length == 0
return val
val = text
onVal(text)
window =
keydown: (cb) => windowKeyDown = cb
names = {PI:NAME:<NAME>END_PI: 'PI:NAME:<NAME>END_PI', PI:NAME:<NAME>END_PI: 'PI:NAME:<NAME>END_PI', PI:NAME:<NAME>END_PI: 'PI:NAME:<NAME>END_PI', PI:NAME:<NAME>END_PI: 'PI:NAME:<NAME>END_PI'}
context = currentWindow:
target: '#bash'
conn:
name: 'freenode.net'
irc:
channels: {}
beforeEach ->
handler = new UserInputHandler input, window
handler._setCursorPosition = ->
context.currentWindow.conn.irc.channels['#bash'] = {names}
handler.setContext context
spyOn handler, 'emit'
altHeld = false
onVal.reset()
it "switches to the given window on 'alt-[0-9]'", ->
altHeld = true
keyDown 48 # 0
expect(handler.emit).toHaveBeenCalledWith 'switch_window', 0
keyDown 57 # 9
expect(handler.emit).toHaveBeenCalledWith 'switch_window', 9
it "doesn't switch windows when alt isn't held", ->
keyDown 48 # 0
keyDown 57 # 9
expect(handler.emit).not.toHaveBeenCalled()
it "sends a say command when text is entered", ->
type 'hello world!'
expect(handler.emit).toHaveBeenCalledWith 'command', jasmine.any Object
e = handler.emit.mostRecentCall.args[1]
expect(e.type).toBe 'command'
expect(e.name).toBe 'say'
expect(e.context).toEqual { server: 'freenode.net', channel: '#bash' }
expect(e.args).toEqual 'hello world!'.split ' '
it "sends the given command when a command is entered", ->
type '/kick sugarman for spamming /dance'
expect(handler.emit).toHaveBeenCalledWith 'command', jasmine.any Object
e = handler.emit.mostRecentCall.args[1]
expect(e.type).toBe 'command'
expect(e.name).toBe 'kick'
expect(e.context).toEqual { server: 'freenode.net', channel: '#bash' }
expect(e.args).toEqual 'sugarman for spamming /dance'.split ' '
describe 'auto-complete', ->
it "completes the current word and adds a colon + space after if it starts the phrase", ->
val = 'b'
cursor 1
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'bill: '
it "completes the current word when the cursor is at the begining of the input", ->
val = 'b'
cursor 0
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'bill: '
it "completes the current word and adds a space after if it doesn't start the phrase", ->
val = ' b'
cursor 2
tab()
expect(onVal.mostRecentCall.args[0]).toBe ' bill '
it "completes the current word when the phrase ends with a space", ->
val = 'b '
cursor 1
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'bill: '
it "completes the current word when the cursor is in the middle of a word", ->
val = 'sis cool'
cursor 1
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'sally: is cool'
it "completes the current word, even when the cursor moves", ->
val = 'well, s is great'
cursor 7
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'well, sPI:NAME:<NAME>END_PI is great'
it "completes the current word, even when there is space between the cursor and the word", ->
val = 'well, sal is great'
cursor 15
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'well, sPI:NAME:<NAME>END_PI is great'
it "goes to next completion on tab", ->
val = 'b'
cursor 0
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'bill: '
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'bob: '
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'bill: '
it "stops cycling possible completions only when input is entered", ->
val = 'b'
cursor 0
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'bill: '
ctrl()
numlock()
tab()
cursor 6
expect(onVal.mostRecentCall.args[0]).toBe 'bob: '
space()
tab()
cursor 5
expect(onVal.mostRecentCall.args[0]).toBe 'bob: '
it "does nothing when no completion candidates match", ->
val = 'PI:NAME:<NAME>END_PIack'
cursor 0
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'zack'
it "adds ': ' even when the the full nick is typed out when tab is pressed", ->
val = 'PI:NAME:<NAME>END_PI'
cursor 4
tab()
expect(onVal.mostRecentCall.args[0]).toBe 'bill: '
describe 'input stack', ->
upArrow = ->
keyDown 38
downArrow = ->
keyDown 40
it "uses the up arrow to show previous commands", ->
type 'hi'
type 'bye'
upArrow()
expect(onVal.mostRecentCall.args[0]).toBe 'bye'
upArrow()
expect(onVal.mostRecentCall.args[0]).toBe 'hi'
it "does nothing when the up arrow is pressed and there is no more previous command", ->
upArrow()
expect(onVal).not.toHaveBeenCalled()
val = 'current text'
upArrow()
expect(onVal).not.toHaveBeenCalled()
type 'hi'
upArrow()
onVal.reset()
upArrow()
upArrow()
expect(onVal).not.toHaveBeenCalled()
it "uses the down arrow to move back toward current commands", ->
type 'hi'
type 'bye'
upArrow()
upArrow()
downArrow()
expect(onVal.mostRecentCall.args[0]).toBe 'bye'
it "displays the current input value as most current previous command", ->
type('hi')
upArrow()
downArrow()
expect(onVal.mostRecentCall.args[0]).toBe ''
type('hi')
val = 'current text'
upArrow()
downArrow()
expect(onVal.mostRecentCall.args[0]).toBe 'current text'
it "does nothing when the down arrow is pressed but there is no more current command", ->
downArrow()
expect(onVal).not.toHaveBeenCalled()
val = 'current text'
downArrow()
expect(onVal).not.toHaveBeenCalled()
type('hi')
upArrow()
downArrow()
onVal.reset()
downArrow()
downArrow()
expect(onVal).not.toHaveBeenCalled()
|
[
{
"context": "ks: [ {name: 'Kana Abe', value: 'Kana'}, { name: 'Bob Olsen', value: 'Bob' } ]\n }\n ]\n ",
"end": 2013,
"score": 0.9996108412742615,
"start": 2004,
"tag": "NAME",
"value": "Bob Olsen"
},
{
"context": "be', value: 'Kana'}, { name: 'Bob Olsen', val... | desktop/components/article/test/templates.coffee | dblock/force | 0 | _ = require 'underscore'
cheerio = require 'cheerio'
path = require 'path'
jade = require 'jade'
fs = require 'fs'
moment = require 'moment'
Article = require '../../../models/article'
Articles = require '../../../collections/articles'
fixtures = require '../../../test/helpers/fixtures.coffee'
render = (templateName) ->
filename = path.resolve __dirname, "../templates/#{templateName}.jade"
jade.compile(
fs.readFileSync(filename),
{ filename: filename }
)
describe 'article show template', ->
it 'renders sectionless articles', ->
html = render('index')
article: new Article title: 'hi', sections: [], section_ids: [], contributing_authors: []
footerArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.containEql 'hi'
it 'renders fullscreen headers with video', ->
html = render('index')
article: new Article
title: 'hi'
sections: []
contributing_authors: []
hero_section:
type: 'fullscreen'
background_url: 'http://video.mp4'
footerArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.containEql 'article-fullscreen-video-player'
it 'renders fullscreen headers with static image', ->
html = render('index')
article: new Article
title: 'hi'
sections: []
contributing_authors: []
hero_section:
type: 'fullscreen'
background_image_url: 'http://image.jpg'
footerArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.containEql 'article-fullscreen-image'
it 'renders a TOC', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'toc'
links: [ {name: 'Kana Abe', value: 'Kana'}, { name: 'Bob Olsen', value: 'Bob' } ]
}
]
contributing_authors: []
footerArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.containEql '<a href="#Kana">Kana Abe</a>'
it 'can optionally exclude share buttons', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'toc'
links: [ {name: 'Kana Abe', value: 'Kana'}, { name: 'Bob Olsen', value: 'Bob' } ]
}
]
contributing_authors: []
footerArticles: new Articles
hideShare: true
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.not.containEql 'share'
it 'can optionally exclude subscribe section', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'toc'
links: [ {name: 'Kana Abe', value: 'Kana'}, { name: 'Bob Olsen', value: 'Bob' } ]
}
]
contributing_authors: []
footerArticles: new Articles
hideSubscribe: true
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.not.containEql 'Subscribe'
it 'does not render a TOC header if there are no links', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'toc'
links: []
}
]
contributing_authors: []
footerArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.not.containEql 'Table Of Contents'
it 'renders top stories', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'callout'
top_stories: true
article: ''
}
]
contributing_authors: []
footerArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: PARSELY_ARTICLES: [
{
url: 'http://artsy.net/article/editorial-cool-article'
image_url: 'http://artsy.net/image.png'
title: '5 Must Read Stories'
}
]
asset: ->
html.should.containEql 'Top Stories on Artsy'
html.should.containEql '5 Must Read Stories'
html.should.containEql 'http://artsy.net/article/editorial-cool-article'
html.should.containEql 'http://artsy.net/image.png'
it 'renders pull quotes', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'callout'
top_stories: false
article: ''
text: 'It isn’t about ownership. It is about understanding these pieces not as static works of art for study, but as living pieces of significance to indigenous groups who have a right to them.'
}
]
contributing_authors: []
footerArticles: new Articles
calloutArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
asset: ->
sd: {}
html.should.containEql 'It isn’t about ownership.'
it 'renders callouts without a text field', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'callout'
top_stories: false
article: '54276766fd4f50996aeca2b8'
text: ''
}
]
contributing_authors: []
footerArticles: new Articles
calloutArticles: new Articles fixtures.article
crop: (url) -> url
resize: (u) -> u
moment: moment
asset: ->
sd: {}
html.should.containEql 'Top Ten Booths at miart 2014'
it 'renders callouts with a text field', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'callout'
top_stories: false
article: '54276766fd4f50996aeca2b8'
text: 'There is a text field here.'
}
]
contributing_authors: []
footerArticles: new Articles
calloutArticles: new Articles fixtures.article
crop: (url) -> url
resize: (u) -> u
moment: moment
asset: ->
sd: {}
html.should.containEql 'There is a text field here.'
it 'renders artworks', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'artworks',
ids: ['5321b73dc9dc2458c4000196', '5321b71c275b24bcaa0001a5'],
layout: 'overflow_fillwidth',
artworks: [
{
type: 'artwork'
id: '5321b73dc9dc2458c4000196'
slug: "govinda-sah-azad-in-between-1",
date: "2015",
title: "In Between",
image: "https://d32dm0rphc51dk.cloudfront.net/zjr8iMxGUQAVU83wi_oXaQ/larger.jpg",
partner: {
name: "October Gallery",
slug: "october-gallery"
},
artists: [{
name: "Govinda Sah 'Azad'",
slug: "govinda-sah-azad"
},
{
name: "Andy Warhol",
slug: "andy-warhol"
}]
},{
type: 'artwork'
id: '5321b71c275b24bcaa0001a5'
slug: "govinda-sah-azad-in-between-2",
date: "2015",
title: "In Between 2",
image: "https://d32dm0rphc51dk.cloudfront.net/zjr8iMxGUQAVU83wi_oXaQ2/larger.jpg",
partner: {
name: "October Gallery",
slug: "october-gallery"
},
artists: [{
name: "Govinda Sah 'Azad'",
slug: "govinda-sah-azad"
}]
}
]
}
]
contributing_authors: []
footerArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.containEql '/artwork/govinda-sah-azad-in-between-1'
html.should.containEql '/artwork/govinda-sah-azad-in-between-2'
html.should.containEql 'October Gallery'
html.should.containEql "Govinda Sah 'Azad'"
html.should.containEql "Andy Warhol"
html.should.containEql 'In Between 2'
it 'renders image collections', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'image_collection',
layout: 'overflow_fillwidth',
images: [
{
type: 'artwork'
id: '5321b73dc9dc2458c4000196'
slug: "govinda-sah-azad-in-between-1",
date: "2015",
title: "In Between",
image: "https://d32dm0rphc51dk.cloudfront.net/zjr8iMxGUQAVU83wi_oXaQ/larger.jpg",
partner: {
name: "October Gallery",
slug: "october-gallery"
},
artists: [{
name: "Govinda Sah 'Azad'",
slug: "govinda-sah-azad"
},
{
name: "Andy Warhol",
slug: "andy-warhol"
}]
},{
type: 'image'
url: "http://artsy.net/image.jpg",
caption: "<p>Some cool art from 2015</p>",
}
]
}
]
contributing_authors: []
footerArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.containEql '/artwork/govinda-sah-azad-in-between-1'
html.should.containEql 'http://artsy.net/image.jpg'
html.should.containEql '/october-gallery'
html.should.containEql "Govinda Sah 'Azad'"
html.should.containEql "Andy Warhol"
html.should.containEql '<p>Some cool art from 2015</p>'
| 129804 | _ = require 'underscore'
cheerio = require 'cheerio'
path = require 'path'
jade = require 'jade'
fs = require 'fs'
moment = require 'moment'
Article = require '../../../models/article'
Articles = require '../../../collections/articles'
fixtures = require '../../../test/helpers/fixtures.coffee'
render = (templateName) ->
filename = path.resolve __dirname, "../templates/#{templateName}.jade"
jade.compile(
fs.readFileSync(filename),
{ filename: filename }
)
describe 'article show template', ->
it 'renders sectionless articles', ->
html = render('index')
article: new Article title: 'hi', sections: [], section_ids: [], contributing_authors: []
footerArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.containEql 'hi'
it 'renders fullscreen headers with video', ->
html = render('index')
article: new Article
title: 'hi'
sections: []
contributing_authors: []
hero_section:
type: 'fullscreen'
background_url: 'http://video.mp4'
footerArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.containEql 'article-fullscreen-video-player'
it 'renders fullscreen headers with static image', ->
html = render('index')
article: new Article
title: 'hi'
sections: []
contributing_authors: []
hero_section:
type: 'fullscreen'
background_image_url: 'http://image.jpg'
footerArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.containEql 'article-fullscreen-image'
it 'renders a TOC', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'toc'
links: [ {name: 'Kana Abe', value: 'Kana'}, { name: '<NAME>', value: '<NAME>' } ]
}
]
contributing_authors: []
footerArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.containEql '<a href="#Kana">K<NAME></a>'
it 'can optionally exclude share buttons', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'toc'
links: [ {name: '<NAME>', value: '<NAME>'}, { name: '<NAME>', value: '<NAME>' } ]
}
]
contributing_authors: []
footerArticles: new Articles
hideShare: true
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.not.containEql 'share'
it 'can optionally exclude subscribe section', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'toc'
links: [ {name: '<NAME>', value: '<NAME>'}, { name: '<NAME>', value: '<NAME>' } ]
}
]
contributing_authors: []
footerArticles: new Articles
hideSubscribe: true
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.not.containEql 'Subscribe'
it 'does not render a TOC header if there are no links', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'toc'
links: []
}
]
contributing_authors: []
footerArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.not.containEql 'Table Of Contents'
it 'renders top stories', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'callout'
top_stories: true
article: ''
}
]
contributing_authors: []
footerArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: PARSELY_ARTICLES: [
{
url: 'http://artsy.net/article/editorial-cool-article'
image_url: 'http://artsy.net/image.png'
title: '5 Must Read Stories'
}
]
asset: ->
html.should.containEql 'Top Stories on Artsy'
html.should.containEql '5 Must Read Stories'
html.should.containEql 'http://artsy.net/article/editorial-cool-article'
html.should.containEql 'http://artsy.net/image.png'
it 'renders pull quotes', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'callout'
top_stories: false
article: ''
text: 'It isn’t about ownership. It is about understanding these pieces not as static works of art for study, but as living pieces of significance to indigenous groups who have a right to them.'
}
]
contributing_authors: []
footerArticles: new Articles
calloutArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
asset: ->
sd: {}
html.should.containEql 'It isn’t about ownership.'
it 'renders callouts without a text field', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'callout'
top_stories: false
article: '54276766fd4f50996aeca2b8'
text: ''
}
]
contributing_authors: []
footerArticles: new Articles
calloutArticles: new Articles fixtures.article
crop: (url) -> url
resize: (u) -> u
moment: moment
asset: ->
sd: {}
html.should.containEql 'Top Ten Booths at miart 2014'
it 'renders callouts with a text field', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'callout'
top_stories: false
article: '54276766fd4f50996aeca2b8'
text: 'There is a text field here.'
}
]
contributing_authors: []
footerArticles: new Articles
calloutArticles: new Articles fixtures.article
crop: (url) -> url
resize: (u) -> u
moment: moment
asset: ->
sd: {}
html.should.containEql 'There is a text field here.'
it 'renders artworks', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'artworks',
ids: ['5321b73dc9dc2458c4000196', '5321b71c275b24bcaa0001a5'],
layout: 'overflow_fillwidth',
artworks: [
{
type: 'artwork'
id: '5321b73dc9dc2458c4000196'
slug: "govinda-sah-azad-in-between-1",
date: "2015",
title: "In Between",
image: "https://d32dm0rphc51dk.cloudfront.net/zjr8iMxGUQAVU83wi_oXaQ/larger.jpg",
partner: {
name: "October Gallery",
slug: "october-gallery"
},
artists: [{
name: "<NAME> '<NAME>'",
slug: "govinda-sah-azad"
},
{
name: "<NAME>",
slug: "andy-warhol"
}]
},{
type: 'artwork'
id: '5321b71c275b24bcaa0001a5'
slug: "govinda-sah-azad-in-between-2",
date: "2015",
title: "In Between 2",
image: "https://d32dm0rphc51dk.cloudfront.net/zjr8iMxGUQAVU83wi_oXaQ2/larger.jpg",
partner: {
name: "October Gallery",
slug: "october-gallery"
},
artists: [{
name: "<NAME> '<NAME>'",
slug: "govinda-sah-azad"
}]
}
]
}
]
contributing_authors: []
footerArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.containEql '/artwork/govinda-sah-azad-in-between-1'
html.should.containEql '/artwork/govinda-sah-azad-in-between-2'
html.should.containEql 'October Gallery'
html.should.containEql "<NAME>'"
html.should.containEql "<NAME>"
html.should.containEql 'In Between 2'
it 'renders image collections', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'image_collection',
layout: 'overflow_fillwidth',
images: [
{
type: 'artwork'
id: '5321b73dc9dc2458c4000196'
slug: "govinda-sah-azad-in-between-1",
date: "2015",
title: "In Between",
image: "https://d32dm0rphc51dk.cloudfront.net/zjr8iMxGUQAVU83wi_oXaQ/larger.jpg",
partner: {
name: "October Gallery",
slug: "october-gallery"
},
artists: [{
name: "<NAME>'",
slug: "govinda-sah-azad"
},
{
name: "<NAME>",
slug: "andy-warhol"
}]
},{
type: 'image'
url: "http://artsy.net/image.jpg",
caption: "<p>Some cool art from 2015</p>",
}
]
}
]
contributing_authors: []
footerArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.containEql '/artwork/govinda-sah-azad-in-between-1'
html.should.containEql 'http://artsy.net/image.jpg'
html.should.containEql '/october-gallery'
html.should.containEql "<NAME> '<NAME>'"
html.should.containEql "<NAME>"
html.should.containEql '<p>Some cool art from 2015</p>'
| true | _ = require 'underscore'
cheerio = require 'cheerio'
path = require 'path'
jade = require 'jade'
fs = require 'fs'
moment = require 'moment'
Article = require '../../../models/article'
Articles = require '../../../collections/articles'
fixtures = require '../../../test/helpers/fixtures.coffee'
render = (templateName) ->
filename = path.resolve __dirname, "../templates/#{templateName}.jade"
jade.compile(
fs.readFileSync(filename),
{ filename: filename }
)
describe 'article show template', ->
it 'renders sectionless articles', ->
html = render('index')
article: new Article title: 'hi', sections: [], section_ids: [], contributing_authors: []
footerArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.containEql 'hi'
it 'renders fullscreen headers with video', ->
html = render('index')
article: new Article
title: 'hi'
sections: []
contributing_authors: []
hero_section:
type: 'fullscreen'
background_url: 'http://video.mp4'
footerArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.containEql 'article-fullscreen-video-player'
it 'renders fullscreen headers with static image', ->
html = render('index')
article: new Article
title: 'hi'
sections: []
contributing_authors: []
hero_section:
type: 'fullscreen'
background_image_url: 'http://image.jpg'
footerArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.containEql 'article-fullscreen-image'
it 'renders a TOC', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'toc'
links: [ {name: 'Kana Abe', value: 'Kana'}, { name: 'PI:NAME:<NAME>END_PI', value: 'PI:NAME:<NAME>END_PI' } ]
}
]
contributing_authors: []
footerArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.containEql '<a href="#Kana">KPI:NAME:<NAME>END_PI</a>'
it 'can optionally exclude share buttons', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'toc'
links: [ {name: 'PI:NAME:<NAME>END_PI', value: 'PI:NAME:<NAME>END_PI'}, { name: 'PI:NAME:<NAME>END_PI', value: 'PI:NAME:<NAME>END_PI' } ]
}
]
contributing_authors: []
footerArticles: new Articles
hideShare: true
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.not.containEql 'share'
it 'can optionally exclude subscribe section', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'toc'
links: [ {name: 'PI:NAME:<NAME>END_PI', value: 'PI:NAME:<NAME>END_PI'}, { name: 'PI:NAME:<NAME>END_PI', value: 'PI:NAME:<NAME>END_PI' } ]
}
]
contributing_authors: []
footerArticles: new Articles
hideSubscribe: true
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.not.containEql 'Subscribe'
it 'does not render a TOC header if there are no links', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'toc'
links: []
}
]
contributing_authors: []
footerArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.not.containEql 'Table Of Contents'
it 'renders top stories', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'callout'
top_stories: true
article: ''
}
]
contributing_authors: []
footerArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: PARSELY_ARTICLES: [
{
url: 'http://artsy.net/article/editorial-cool-article'
image_url: 'http://artsy.net/image.png'
title: '5 Must Read Stories'
}
]
asset: ->
html.should.containEql 'Top Stories on Artsy'
html.should.containEql '5 Must Read Stories'
html.should.containEql 'http://artsy.net/article/editorial-cool-article'
html.should.containEql 'http://artsy.net/image.png'
it 'renders pull quotes', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'callout'
top_stories: false
article: ''
text: 'It isn’t about ownership. It is about understanding these pieces not as static works of art for study, but as living pieces of significance to indigenous groups who have a right to them.'
}
]
contributing_authors: []
footerArticles: new Articles
calloutArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
asset: ->
sd: {}
html.should.containEql 'It isn’t about ownership.'
it 'renders callouts without a text field', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'callout'
top_stories: false
article: '54276766fd4f50996aeca2b8'
text: ''
}
]
contributing_authors: []
footerArticles: new Articles
calloutArticles: new Articles fixtures.article
crop: (url) -> url
resize: (u) -> u
moment: moment
asset: ->
sd: {}
html.should.containEql 'Top Ten Booths at miart 2014'
it 'renders callouts with a text field', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'callout'
top_stories: false
article: '54276766fd4f50996aeca2b8'
text: 'There is a text field here.'
}
]
contributing_authors: []
footerArticles: new Articles
calloutArticles: new Articles fixtures.article
crop: (url) -> url
resize: (u) -> u
moment: moment
asset: ->
sd: {}
html.should.containEql 'There is a text field here.'
it 'renders artworks', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'artworks',
ids: ['5321b73dc9dc2458c4000196', '5321b71c275b24bcaa0001a5'],
layout: 'overflow_fillwidth',
artworks: [
{
type: 'artwork'
id: '5321b73dc9dc2458c4000196'
slug: "govinda-sah-azad-in-between-1",
date: "2015",
title: "In Between",
image: "https://d32dm0rphc51dk.cloudfront.net/zjr8iMxGUQAVU83wi_oXaQ/larger.jpg",
partner: {
name: "October Gallery",
slug: "october-gallery"
},
artists: [{
name: "PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI'",
slug: "govinda-sah-azad"
},
{
name: "PI:NAME:<NAME>END_PI",
slug: "andy-warhol"
}]
},{
type: 'artwork'
id: '5321b71c275b24bcaa0001a5'
slug: "govinda-sah-azad-in-between-2",
date: "2015",
title: "In Between 2",
image: "https://d32dm0rphc51dk.cloudfront.net/zjr8iMxGUQAVU83wi_oXaQ2/larger.jpg",
partner: {
name: "October Gallery",
slug: "october-gallery"
},
artists: [{
name: "PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI'",
slug: "govinda-sah-azad"
}]
}
]
}
]
contributing_authors: []
footerArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.containEql '/artwork/govinda-sah-azad-in-between-1'
html.should.containEql '/artwork/govinda-sah-azad-in-between-2'
html.should.containEql 'October Gallery'
html.should.containEql "PI:NAME:<NAME>END_PI'"
html.should.containEql "PI:NAME:<NAME>END_PI"
html.should.containEql 'In Between 2'
it 'renders image collections', ->
html = render('index')
article: new Article
title: 'hi'
sections: [
{
type: 'image_collection',
layout: 'overflow_fillwidth',
images: [
{
type: 'artwork'
id: '5321b73dc9dc2458c4000196'
slug: "govinda-sah-azad-in-between-1",
date: "2015",
title: "In Between",
image: "https://d32dm0rphc51dk.cloudfront.net/zjr8iMxGUQAVU83wi_oXaQ/larger.jpg",
partner: {
name: "October Gallery",
slug: "october-gallery"
},
artists: [{
name: "PI:NAME:<NAME>END_PI'",
slug: "govinda-sah-azad"
},
{
name: "PI:NAME:<NAME>END_PI",
slug: "andy-warhol"
}]
},{
type: 'image'
url: "http://artsy.net/image.jpg",
caption: "<p>Some cool art from 2015</p>",
}
]
}
]
contributing_authors: []
footerArticles: new Articles
crop: (url) -> url
resize: (u) -> u
moment: moment
sd: {}
asset: ->
html.should.containEql '/artwork/govinda-sah-azad-in-between-1'
html.should.containEql 'http://artsy.net/image.jpg'
html.should.containEql '/october-gallery'
html.should.containEql "PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI'"
html.should.containEql "PI:NAME:<NAME>END_PI"
html.should.containEql '<p>Some cool art from 2015</p>'
|
[
{
"context": "by .doaxvv-news-scraper-bot.json.\n#\n# Author:\n# ktp <unofficial.doaxvv.bot@gmail.com>\n\nfs = require '",
"end": 867,
"score": 0.9996505975723267,
"start": 864,
"tag": "USERNAME",
"value": "ktp"
},
{
"context": "axvv-news-scraper-bot.json.\n#\n# Author:\n# ktp ... | scripts/doaxvv-news-scraper-bot.coffee | speedholicktp/doaxvv-news-scraper-bot | 1 | # Description
# A DOAXVV official site scraper for Discord.
#
# Configuration:
# HUBOT_DISCORD_TOKEN
# HUBOT_DISCORD_STATUS_MSG
# HUBOT_DISCORD_WEBHOOK_URL
# (Heroku only) HUBOT_HEROKU_KEEPALIVE_URL
# (Heroku only) HUBOT_HEROKU_KEEPALIVE_INTERVAL
# (Heroku only) HUBOT_HEROKU_WAKEUP_TIME
# (Heroku only) HUBOT_HEROKU_SLEEP_TIME
# (Heroku only) heroku config:add TZ='YOUR_TIME_ZONE'
# HUBOT_HEROKU_WAKEUP_TIME and HUBOT_HEROKU_SLEEP_TIME depend on TZ value.
# The default TZ value is UTC(GMT+0:00).
# (Heroku only) Heroku scheduler to execute the following for waking up BOT:
# curl ${HUBOT_HEROKU_KEEPALIVE_URL}heroku/keepalive
#
# Commands:
# check ... Force check now
#
# Notes:
# Runs periodically. The interval is determined by .doaxvv-news-scraper-bot.json.
#
# Author:
# ktp <unofficial.doaxvv.bot@gmail.com>
fs = require 'fs'
crypto = require 'crypto'
client = require 'cheerio-httpcli'
request = require 'request'
cronJob = require('cron').CronJob
# Get env vars.
config =
webhookUrl: process.env.HUBOT_DISCORD_WEBHOOK_URL
module.exports = (robot) ->
#
# Functions
#
loadJSON = ->
try
json = fs.readFileSync('./.doaxvv-news-scraper-bot.json', 'utf8')
return JSON.parse(json)
catch err
return err
md5hex = (src)->
md5hash = crypto.createHash('md5')
md5hash.update(src, 'binary')
return md5hash.digest('hex')
saveHex = (title, str) ->
try
fs.writeFileSync('./tmp/'+ md5hex(title),md5hex(str))
catch err
robot.logger.error err
return err
checkUpdate = (title, str) ->
try
hash = fs.readFileSync('./tmp/'+ md5hex(title)).toString()
newHash = md5hex(str)
if (hash is newHash) or (hash is '')
return false
else
return true
catch err
robot.logger.error err
return false
sendToDiscord = (title, url) ->
data = JSON.stringify({
content: title + "が更新されたみたい: " + url
})
robot.http(config.webhookUrl)
.header('Content-Type', 'application/json')
.post(data) (err, res, body) ->
#
checkPages = (client, pages, json, opt_pointer) ->
this.pointer = opt_pointer || 0
page = pages[pointer]
client.fetch(page.url)
.then (result) ->
robot.logger.info page.name
if page.exclude_class?
result.$('.' + page.exclude_class).remove()
res = checkUpdate(page.url, result.$('ul li').text())
if res is true
robot.logger.info page.name + ' is updated'
sendToDiscord(page.name, page.url)
saveHex(page.url, result.$('ul li').text())
pointer += 1
if pointer == pages.length
return
checkPages(client, pages, json, pointer)
.catch (err) ->
robot.logger.error err
#
# Execute
#
json = loadJSON()
robot.respond /check$/i, (msg) ->
checkPages(client, json.pages)
msg.reply('')
doaxvvNewsCron = new cronJob({
cronTime: json.cron_time
onTick: ->
checkPages(client, json.pages)
.then ->
robot.logger.info 'finish'
.catch (err) ->
robot.logger.error err
.finally ->
msg.reply('')
start: true
})
| 19350 | # Description
# A DOAXVV official site scraper for Discord.
#
# Configuration:
# HUBOT_DISCORD_TOKEN
# HUBOT_DISCORD_STATUS_MSG
# HUBOT_DISCORD_WEBHOOK_URL
# (Heroku only) HUBOT_HEROKU_KEEPALIVE_URL
# (Heroku only) HUBOT_HEROKU_KEEPALIVE_INTERVAL
# (Heroku only) HUBOT_HEROKU_WAKEUP_TIME
# (Heroku only) HUBOT_HEROKU_SLEEP_TIME
# (Heroku only) heroku config:add TZ='YOUR_TIME_ZONE'
# HUBOT_HEROKU_WAKEUP_TIME and HUBOT_HEROKU_SLEEP_TIME depend on TZ value.
# The default TZ value is UTC(GMT+0:00).
# (Heroku only) Heroku scheduler to execute the following for waking up BOT:
# curl ${HUBOT_HEROKU_KEEPALIVE_URL}heroku/keepalive
#
# Commands:
# check ... Force check now
#
# Notes:
# Runs periodically. The interval is determined by .doaxvv-news-scraper-bot.json.
#
# Author:
# ktp <<EMAIL>>
fs = require 'fs'
crypto = require 'crypto'
client = require 'cheerio-httpcli'
request = require 'request'
cronJob = require('cron').CronJob
# Get env vars.
config =
webhookUrl: process.env.HUBOT_DISCORD_WEBHOOK_URL
module.exports = (robot) ->
#
# Functions
#
loadJSON = ->
try
json = fs.readFileSync('./.doaxvv-news-scraper-bot.json', 'utf8')
return JSON.parse(json)
catch err
return err
md5hex = (src)->
md5hash = crypto.createHash('md5')
md5hash.update(src, 'binary')
return md5hash.digest('hex')
saveHex = (title, str) ->
try
fs.writeFileSync('./tmp/'+ md5hex(title),md5hex(str))
catch err
robot.logger.error err
return err
checkUpdate = (title, str) ->
try
hash = fs.readFileSync('./tmp/'+ md5hex(title)).toString()
newHash = md5hex(str)
if (hash is newHash) or (hash is '')
return false
else
return true
catch err
robot.logger.error err
return false
sendToDiscord = (title, url) ->
data = JSON.stringify({
content: title + "が更新されたみたい: " + url
})
robot.http(config.webhookUrl)
.header('Content-Type', 'application/json')
.post(data) (err, res, body) ->
#
checkPages = (client, pages, json, opt_pointer) ->
this.pointer = opt_pointer || 0
page = pages[pointer]
client.fetch(page.url)
.then (result) ->
robot.logger.info page.name
if page.exclude_class?
result.$('.' + page.exclude_class).remove()
res = checkUpdate(page.url, result.$('ul li').text())
if res is true
robot.logger.info page.name + ' is updated'
sendToDiscord(page.name, page.url)
saveHex(page.url, result.$('ul li').text())
pointer += 1
if pointer == pages.length
return
checkPages(client, pages, json, pointer)
.catch (err) ->
robot.logger.error err
#
# Execute
#
json = loadJSON()
robot.respond /check$/i, (msg) ->
checkPages(client, json.pages)
msg.reply('')
doaxvvNewsCron = new cronJob({
cronTime: json.cron_time
onTick: ->
checkPages(client, json.pages)
.then ->
robot.logger.info 'finish'
.catch (err) ->
robot.logger.error err
.finally ->
msg.reply('')
start: true
})
| true | # Description
# A DOAXVV official site scraper for Discord.
#
# Configuration:
# HUBOT_DISCORD_TOKEN
# HUBOT_DISCORD_STATUS_MSG
# HUBOT_DISCORD_WEBHOOK_URL
# (Heroku only) HUBOT_HEROKU_KEEPALIVE_URL
# (Heroku only) HUBOT_HEROKU_KEEPALIVE_INTERVAL
# (Heroku only) HUBOT_HEROKU_WAKEUP_TIME
# (Heroku only) HUBOT_HEROKU_SLEEP_TIME
# (Heroku only) heroku config:add TZ='YOUR_TIME_ZONE'
# HUBOT_HEROKU_WAKEUP_TIME and HUBOT_HEROKU_SLEEP_TIME depend on TZ value.
# The default TZ value is UTC(GMT+0:00).
# (Heroku only) Heroku scheduler to execute the following for waking up BOT:
# curl ${HUBOT_HEROKU_KEEPALIVE_URL}heroku/keepalive
#
# Commands:
# check ... Force check now
#
# Notes:
# Runs periodically. The interval is determined by .doaxvv-news-scraper-bot.json.
#
# Author:
# ktp <PI:EMAIL:<EMAIL>END_PI>
fs = require 'fs'
crypto = require 'crypto'
client = require 'cheerio-httpcli'
request = require 'request'
cronJob = require('cron').CronJob
# Get env vars.
config =
webhookUrl: process.env.HUBOT_DISCORD_WEBHOOK_URL
module.exports = (robot) ->
#
# Functions
#
loadJSON = ->
try
json = fs.readFileSync('./.doaxvv-news-scraper-bot.json', 'utf8')
return JSON.parse(json)
catch err
return err
md5hex = (src)->
md5hash = crypto.createHash('md5')
md5hash.update(src, 'binary')
return md5hash.digest('hex')
saveHex = (title, str) ->
try
fs.writeFileSync('./tmp/'+ md5hex(title),md5hex(str))
catch err
robot.logger.error err
return err
checkUpdate = (title, str) ->
try
hash = fs.readFileSync('./tmp/'+ md5hex(title)).toString()
newHash = md5hex(str)
if (hash is newHash) or (hash is '')
return false
else
return true
catch err
robot.logger.error err
return false
sendToDiscord = (title, url) ->
data = JSON.stringify({
content: title + "が更新されたみたい: " + url
})
robot.http(config.webhookUrl)
.header('Content-Type', 'application/json')
.post(data) (err, res, body) ->
#
checkPages = (client, pages, json, opt_pointer) ->
this.pointer = opt_pointer || 0
page = pages[pointer]
client.fetch(page.url)
.then (result) ->
robot.logger.info page.name
if page.exclude_class?
result.$('.' + page.exclude_class).remove()
res = checkUpdate(page.url, result.$('ul li').text())
if res is true
robot.logger.info page.name + ' is updated'
sendToDiscord(page.name, page.url)
saveHex(page.url, result.$('ul li').text())
pointer += 1
if pointer == pages.length
return
checkPages(client, pages, json, pointer)
.catch (err) ->
robot.logger.error err
#
# Execute
#
json = loadJSON()
robot.respond /check$/i, (msg) ->
checkPages(client, json.pages)
msg.reply('')
doaxvvNewsCron = new cronJob({
cronTime: json.cron_time
onTick: ->
checkPages(client, json.pages)
.then ->
robot.logger.info 'finish'
.catch (err) ->
robot.logger.error err
.finally ->
msg.reply('')
start: true
})
|
[
{
"context": "t = [\n {\n id: 0,\n name: \"supa\",\n race: \"shadow\",\n team: 0\n ",
"end": 15057,
"score": 0.998538613319397,
"start": 15053,
"tag": "NAME",
"value": "supa"
},
{
"context": " },\n {\n id: 1,\n n... | gameserver/test/unit/lib/game-unit-test.coffee | towerstorm/game | 11 | assert = require 'assert'
sinon = require 'sinon'
proxyquire = require 'proxyquire'
Player = require '../../../lib/player'
config = require 'config/general'
serverConfig = require 'config/gameserver'
Dispatcher = require '../dispatcher-mock'
GameModel = require '../mocks/game-model-mock'
gameMsg = require 'config/game-messages'
netMsg = require 'config/net-messages'
UserMock = {
findById: -> {}
}
QueuerMock = {
findAllByMatchId: -> []
}
noop = ->
class ModelMock
data: {}
set: (item, value) -> @data[item] = value
get: (item) -> @data[item]
save: (callback = noop) -> callback()
dbMock = {
models: {
User: UserMock
Queuer: QueuerMock
Model: ModelMock
}
}
Game = proxyquire '../../../models/game', {
'game': IGMock
'game/lib/game/main': IGGameMock
'database': dbMock
}
Game.register = ->
Game.updateState = ->
Game.postToLobby = ->
game = null
describe "Server Game", ->
beforeEach ->
app =
settings:
socketIO: null
game = new Game(app)
game.log = {
debug: ->
info: ->
warn: ->
erro: ->
}
game.data.startTime = 0
game.data.ticks = {};
game.socket = {
emit: ->
}
describe "init", ->
beforeEach ->
game.bindSockets = -> assert true
game.bindDispatcher = -> assert true
game.bindIGDispatcher = -> assert true
game.checkSomeoneConnected = -> assert true
game.checkEveryoneConnected = -> assert true
game.autoAddBots = -> assert true
game.start = -> assert true
it "should set the state to lobby", (done) ->
game.init ->
assert.equal(game.data.state, config.states.lobby)
done()
it "should set ticks to {}", (done) ->
game.init ->
assert.deepEqual(game.data.ticks, {})
done()
describe "call checkSomeoneConnected", ->
calledCheckSomeoneConnected = false
beforeEach (done) ->
game.hostId = "123"
serverConfig.waitForHostToConnectTime = 0.1;
game.checkSomeoneConnected = ->
calledCheckSomeoneConnected = true
done();
game.init()
it "should call checkSomeoneConnected after waitForHostToConnectTime seconds", ->
assert.equal calledCheckSomeoneConnected, true
describe "bindSockets", ->
describe "registerWithLobb" , ->
describe "autoAddBots", ->
it "Should call addBot twice with team 0 and three times with team 1", (done) ->
serverConfig.autoAddBots = true
game.hostId = '123'
addBot = sinon.stub(game, 'addBot').callsArgWith(1, 0)
game.autoAddBots (err, botNums) ->
assert.deepEqual addBot.getCall(0).args[0], {team: 1}
assert.deepEqual addBot.getCall(1).args[0], {team: 0}
assert.deepEqual addBot.getCall(2).args[0], {team: 1}
assert.deepEqual addBot.getCall(3).args[0], {team: 0}
assert.deepEqual addBot.getCall(4).args[0], {team: 1}
addBot.restore()
done()
describe "userConnected", ->
describe "checkPlayersAreLoaded", ->
describe "checkSomeoneConnected", ->
beforeEach ->
game.end = -> assert true
it "Should end the game if total players is 0", ->
game.totalPlayers = 0
calledEnd = false
game.end = ->
calledEnd = true
game.checkSomeoneConnected();
assert.equal calledEnd, true
it "Should not end the game if total players is greater than 0", ->
game.totalPlayers = 1
calledEnd = false
game.end = ->
calledEnd = true
game.checkSomeoneConnected();
assert.equal calledEnd, false
describe "checkEveryoneConnected", ->
beforeEach ->
game.cancel = -> true
game.log = {
info: -> true
warn: -> true
error: -> true
}
it "Should emit a warning if totalConnectedPlayers is 0 because it could just be a game that all players didn't accept", ->
game.getTotalConnectedPlayers = -> 0
sinon.stub(game.log, 'warn')
game.checkEveryoneConnected()
assert game.log.warn.calledOnce
it "Should emit an error if totalConnectedPlayers is > 0 && < 6 because something fucked up", ->
game.getTotalConnectedPlayers = -> 3
sinon.stub(game.log, 'error')
game.checkEveryoneConnected()
assert game.log.error.calledOnce
describe "start", ->
describe "begin", ->
describe "cancel", ->
beforeEach ->
game.socket = {emit: ->}
game.end = ->
it "Should send game cancelled message to all players", () ->
sinon.stub(game.socket, 'emit')
game.cancel()
assert game.socket.emit.calledWith(netMsg.game.didNotConnect)
game.socket.emit.restore()
it "Should call end", () ->
sinon.stub(game, 'end')
game.cancel()
assert game.end.calledOnce
game.end.restore()
describe "end", ->
beforeEach ->
game.deleteSelf = -> assert true
game.updatePlayerProfilesAtEnd = -> assert true
it "should set game state to finished", ->
game.data.state = config.states.begun;
game.end();
assert.equal game.data.state, config.states.finished
it "should return false if the state is already finished", ->
game.data.state = config.states.finished
funcReturn = game.end();
assert.equal funcReturn, false
describe "broadcastDetails", ->
it "Should return false if state is finished", ->
game.data.state = config.states.finished
returnCode = game.broadcastDetails();
assert.equal returnCode, false
describe "processPlayerActions", ->
it "Should add all the actions players have done to one array", (done) ->
game.players = [
{lastAction: {type: "minions", data: {xPos: 1, yPos: 2, type: "goblin"}}},
{lastAction: {type: "minions", data: {xPos: 9, yPos: 10, type: "ogre"}}},
{lastAction: {type: "towers", data: {xPos: 3, yPos: 8, type: "crossbow"}}},
]
sinon.stub(game, 'processTick');
game.processPlayerActions(5);
game.processTick.calledWith(5, {
"minions": [
data: {xPos: 1, yPos: 2, type: "goblin"},
data: {xPos: 9, yPos: 10, type: "ogre"},
],
"towers": [
data: {xPos: 3, yPos: 8, type: "crossbow"}
]
});
game.processPlayerActions = ->
done();
describe "processTick", ->
beforeEach ->
global.metricsServer = {
addMetric: -> true
}
it "Should send the tick to each player", ->
it "Should not store the tick but should set currentTick if there is no data", ->
game.set('ticks', {})
tick = 4
commandsDone = null
gameStateHash = 23823212902;
game.processTick tick, commandsDone, gameStateHash
assert !game.get('ticks')[tick]?
assert.equal game.get('currentTick'), 4
it "Should store the tick in ticks if it has data", ->
game.set('ticks', {})
tick = 19
commandsDone = "TestCommands"
gameStateHash = 23823212902;
game.processTick tick, commandsDone, gameStateHash
assert game.get('ticks')[tick]?
assert.equal game.get('ticks')[tick], commandsDone
assert.equal game.get('currentTick'), 19
it "Should create a copy of actionsDone instead of reference it directly", ->
describe "reportGameSnapshot", ->
it "Should set snapshot and snapshotHash and save them out to the db", ->
sinon.stub(game, 'save')
snapshot = {minions: {'one': 1}}
snapshotHash = 'abc123'
game.reportGameSnapshot(1, snapshot, snapshotHash)
assert.deepEqual game.data.snapshot, {tick: 1, hash: snapshotHash, data: JSON.stringify(snapshot)}
describe "setState", ->
describe "setMode", ->
describe "getMode", ->
describe "reportInvalidState", ->
describe "getPlayerTeam", ->
it "Should return team 0 if there are no players in the match yet", ->
game.players = []
assert.equal game.getPlayerTeam(), 0
it "Should allocate for team 0 when there are already many players on it if playerTeamAllocations says so", ->
game.players = [{team: 0}]
game.playerTeamAllocations = {'abc': 0, 'def': 0, 'gyy': 0}
assert.equal game.getPlayerTeam('abc'), 0
assert.equal game.getPlayerTeam('def'), 0
assert.equal game.getPlayerTeam('gyy'), 0
it "Should return playerTeamAllocation if it's set for this player", ->
game.playerTeamAllocations = {'abc': 1}
assert.equal game.getPlayerTeam('abc'), 1
it "Should add player to team with least players", ->
game.players = [{team: 0}]
assert.equal game.getPlayerTeam(), 1
describe "findFirstBot", ->
describe "playerJoin", ->
player = null
addPlayerArgs = null
callbackArgs = null
socket = "SockYea!"
socketArgs = null
joinedGame = false
beforeEach ->
player = new Player();
callback = ->
callbackArgs = arguments
game.addPlayer = ->
addPlayerArgs = arguments;
player.setSocket = ->
socketArgs = arguments;
player.joinGame = ->
joinedGame = true
player.sendDetails = -> assert true
game.dispatcher = new Dispatcher();
game.kickPlayer = -> assert true
game.isCustomGame = -> true
game.broadcastDetails = sinon.stub()
game.playerJoin(player, socket, callback)
it "Should call addplayer with the player", ->
assert addPlayerArgs?
assert.deepEqual addPlayerArgs[0], player
it "Should set players team and socket and call joinGame", ->
assert.equal player.team, 0
assert socketArgs?
assert.equal socketArgs[0], socket
assert.equal joinedGame, true
it "Should add players to teams equally as more are added", ->
it "Should call sendDetails", ->
sendDetailsCalled = false
player.sendDetails = ->
sendDetailsCalled = true
game.playerJoin player, socket
assert.equal sendDetailsCalled, true
it "Should trigger broadcastDetails", ->
assert game.broadcastDetails.calledOnce
it "Should report game is full if the game is in the lobby and total players is more than max and there are no bots in the game", ->
game.data.state = config.states.lobby
game.maxPlayers = 6
game.totalPlayers = 6
game.players = []
for i in [0...6]
game.players.push({isBot: false})
emitArgs = null
socket =
emit: () -> emitArgs = arguments
game.playerJoin(player, socket)
assert emitArgs?
assert.equal emitArgs[0], netMsg.game.error
assert.deepEqual emitArgs[1], {error: netMsg.game.full}
it "Should not report game is full if it is at max players but there are bots in the game", ->
game.data.state = config.states.lobby
game.maxPlayers = 6
game.totalPlayers = 6
game.players = []
for i in [0...6]
game.players.push({isBot: !!(i % 2)})
emitArgs = null
socket =
emit: () -> emitArgs = arguments
game.playerJoin(player, socket)
assert !emitArgs?
it "Should not report game is full if the game has started and total players is more than max", ->
game.data.state = config.states.started
game.maxPlayers = 6
game.totalPlayers = 6
emitArgs = null
socket =
emit: () -> emitArgs = arguments
game.playerJoin(player, socket)
assert !emitArgs?
it "Should call syncData on player if gamestate is begun", ->
calledSyncData = false
player.syncData = -> calledSyncData = true
game.data.state = config.states.init
game.playerJoin(player, socket)
assert.equal calledSyncData, false
game.data.state = config.states.begun
game.playerJoin(player, socket)
assert.equal calledSyncData, true
describe "addPlayer", ->
beforeEach ->
game.dispatcher = new Dispatcher();
describe "deletePlayer", ->
it "Should return false immediately if the game is finished", ->
### This is here because sometimes clients will send a disconnect
after the game is alredy over and make the game crash due to everything
being deleted already. ###
game.data.state = config.states.finished
player = {id: 5, disconnect: ->}
game.players = [player]
funcReturn = game.deletePlayer(player)
assert.equal funcReturn, false
it "Should end the game if the game is in lobby state and there are no players left", ->
endCalled = false
game.end = ->
endCalled = true
game.data.state = config.states.lobby
game.totalPlayers = 0
game.deletePlayer("testPlayerId")
assert.equal endCalled, true
describe "playerConnected", ->
it "should set gameEndCheck to null", ->
game.gameEndCheck = "test"
game.playerConnected({id: 5})
assert.equal game.gameEndCheck, null
describe "playerDisconnected", ->
beforeEach ->
game.checkIfGameShouldEnd = -> assert true
it "Should create a gameEndCheck if all players are disconnected and state is more than lobby", ->
game.data.state = config.states.begun
game.players = [{id: 5, disconnected: true}, {id: 6, disconnected: true}]
game.playerDisconnected(null)
assert game.gameEndCheck?
it "Should not create a gameEndCheck if all players are disconnected and state is lobby", ->
game.data.state = config.states.lobby
game.players = [{id: 5, disconnected: true}, {id: 6, disconnected: true}]
game.playerDisconnected(null)
assert.equal game.gameEndCheck, null
it "Should not create a gameEndCheck if all players are disconnected and state is started", ->
game.data.state = config.states.started
game.players = [{id: 5, disconnected: true}, {id: 6, disconnected: true}]
game.playerDisconnected(null)
assert.equal game.gameEndCheck, null
it "Sould not create a gameEndCheck if players list has connected people in it", ->
game.data.state = config.states.begun
game.players = [{id: 5, disconnected: false}, {id: 6, disconnected: true}]
game.playerDisconnected(null)
assert.equal game.gameEndCheck, null
it "Should not create a gameEndCheck if one already exists", ->
game.gameEndCheck = {mew: 5}
game.data.state = config.states.begun
game.players = [{id: 5, disconnected: true}, {id: 6, disconnected: true}]
game.playerDisconnected(null)
assert.deepEqual game.gameEndCheck, {mew: 5}
describe "addBot", ->
it "Should return false if the state is not lobby", ->
game.data.state = config.states.started
callback = sinon.stub()
game.addBot({}, callback);
assert callback.calledOnce
it "Should send a request to the bot master to add a bot to this game", ->
# game.data.state = config.states.lobby
# game.addBot();
describe "getPlayers", ->
it "Should get a list of players containing id, name, race, team for each", ->
playersList = [
{
id: 0,
name: "supa",
race: "shadow",
team: 0
isBot: false
ready: false
loaded: false
},
{
id: 1,
name: "yoohoo",
race: "druids",
team: 1
isBot: false
ready: false
loaded: false
}
]
game.players = playersList
playersReturn = game.getPlayers()
assert.deepEqual playersList, playersReturn
describe "update", ->
describe "checkIfGameShouldEnd", ->
beforeEach ->
game.end = -> assert true
it "Should set gameEndCheck to null", ->
game.gameEndCheck = {mew: 4}
game.checkIfGameShouldEnd()
assert.equal game.gameEndCheck, null
it "Should end the game if all players are disconnected", ->
game.players = [{id: 1, disconnected: true}]
endCalled = false
game.end = ->
endCalled = true
game.checkIfGameShouldEnd();
assert.equal endCalled, true
it "Should not end the game if players have reconnected", ->
game.players = [{id: 6, disconnected: false}, {id: 8, disconnected: true}]
endCalled = false
game.end = ->
endCalled = true
game.checkIfGameShouldEnd();
assert.equal endCalled, false
describe "updatePlayerProfilesAtEnd", ->
it "Should callback false if the winningTeam is undefined", (done) ->
game.updatePlayerProfilesAtEnd undefined, (err, result) ->
assert.equal result, false
done()
it "Should call calculateEloChange if winningTeam is 0", (done) ->
sinon.stub(game, "calculateEloChange")
game.updatePlayerProfilesAtEnd 0, (err, result) ->
assert game.calculateEloChange.calledWith(0)
game.calculateEloChange.restore()
done()
it "Should call calculateEloChange if winningTeam is 1", (done) ->
sinon.stub(game, "calculateEloChange")
game.updatePlayerProfilesAtEnd 1, (err, result) ->
assert game.calculateEloChange.calledWith(1)
game.calculateEloChange.restore()
done()
describe "calculateEloChange", ->
it "Should return 8 for winning team 0 if elos are 1600 and 1400", (done) ->
sinon.stub(game, 'getTeamElos').callsArgWith(0, null, [1600, 1400])
game.calculateEloChange 0, (err, eloChange) ->
assert.equal(eloChange, 8)
done()
it "Should return 8 for winning team 1 if elos are 1400 and 1600", (done) ->
sinon.stub(game, 'getTeamElos').callsArgWith(0, null, [1400, 1600])
game.calculateEloChange 1, (err, eloChange) ->
assert.equal(eloChange, 8)
done()
it "Should return 24 for winning team 0 if elos are 1600 and 1400", (done) ->
sinon.stub(game, 'getTeamElos').callsArgWith(0, null, [1600, 1400])
game.calculateEloChange 1, (err, eloChange) ->
assert.equal(eloChange, 24)
done()
it "Should return 24 for winning team 0 if elos are 1400 and 1600", (done) ->
sinon.stub(game, 'getTeamElos').callsArgWith(0, null, [1400, 1600])
game.calculateEloChange 0, (err, eloChange) ->
assert.equal(eloChange, 24)
done()
describe "getTeamElos", ->
it "Should return the average elo for each team", (done) ->
players = [
{id: 1, team: 0, get: -> 1100}
{id: 2, team: 0, get: -> 1200}
{id: 3, team: 0, get: -> 1300}
{id: 4, team: 1, get: -> 1700}
{id: 5, team: 1, get: -> 1800}
{id: 6, team: 1, get: -> 1750}
]
game.players = players
sinon.stub(UserMock, 'findById', (id, callback) -> callback(null, players[id-1]))
game.getTeamElos (err, teamElos) ->
if err then return done(err)
assert.equal(teamElos[0], 1200)
assert.equal(teamElos[1], 1750)
UserMock.findById.restore()
done()
describe "allocatePlayerTeams", ->
it "Should put 3 players on team 1 and 3 on team 2, grouped with those they matchmade with", (done) ->
game.matchId = "123"
data = [
{userIds: ['a', 'b', 'c']}
{userIds: ['d', 'e', 'f']}
]
queuers = data.map((q) -> {data: q, get: (name) -> @data[name]})
sinon.stub(QueuerMock, 'findAllByMatchId').callsArgWith(1, null, queuers)
game.allocatePlayerTeams (err, result) ->
assert.deepEqual game.playerTeamAllocations, {a: 0, b: 0, c: 0, d: 1, e: 1, f: 1}
QueuerMock.findAllByMatchId.restore()
done()
it "Should work with teams of 2 + 1", (done) ->
game.matchId = "123"
data = [
{userIds: ['a', 'b']}
{userIds: ['d', 'e']}
{userIds: ['c']}
{userIds: ['f']}
]
queuers = data.map((q) -> {data: q, get: (name) -> @data[name]})
sinon.stub(QueuerMock, 'findAllByMatchId').callsArgWith(1, null, queuers)
game.allocatePlayerTeams (err, result) ->
assert.deepEqual game.playerTeamAllocations, {a: 0, b: 0, c: 0, d: 1, e: 1, f: 1}
QueuerMock.findAllByMatchId.restore()
done()
it "Should work with teams of 2 + 1 in a strange order", (done) ->
game.matchId = "123"
data = [
{userIds: ['c']}
{userIds: ['a', 'b']}
{userIds: ['d', 'e']}
{userIds: ['f']}
]
queuers = data.map((q) -> {data: q, get: (name) -> @data[name]})
sinon.stub(QueuerMock, 'findAllByMatchId').callsArgWith(1, null, queuers)
game.allocatePlayerTeams (err, result) ->
assert.deepEqual game.playerTeamAllocations, {a: 0, b: 0, c: 0, d: 1, e: 1, f: 1}
QueuerMock.findAllByMatchId.restore()
done()
describe "allocateRandomRaces", ->
it "Should set all players who have a null race to a valid race", ->
game.isCustomGame = -> false
game.players = [
{race: 'shadow', team: 0}
{race: 'crusaders', team: 0}
{race: null, team: 0, setRace: (@race) ->}
]
game.allocateRandomRaces()
assert.equal(game.players[0].race, 'shadow')
assert.equal(game.players[1].race, 'crusaders')
assert(game.players[2].race != null)
| 81858 | assert = require 'assert'
sinon = require 'sinon'
proxyquire = require 'proxyquire'
Player = require '../../../lib/player'
config = require 'config/general'
serverConfig = require 'config/gameserver'
Dispatcher = require '../dispatcher-mock'
GameModel = require '../mocks/game-model-mock'
gameMsg = require 'config/game-messages'
netMsg = require 'config/net-messages'
UserMock = {
findById: -> {}
}
QueuerMock = {
findAllByMatchId: -> []
}
noop = ->
class ModelMock
data: {}
set: (item, value) -> @data[item] = value
get: (item) -> @data[item]
save: (callback = noop) -> callback()
dbMock = {
models: {
User: UserMock
Queuer: QueuerMock
Model: ModelMock
}
}
Game = proxyquire '../../../models/game', {
'game': IGMock
'game/lib/game/main': IGGameMock
'database': dbMock
}
Game.register = ->
Game.updateState = ->
Game.postToLobby = ->
game = null
describe "Server Game", ->
beforeEach ->
app =
settings:
socketIO: null
game = new Game(app)
game.log = {
debug: ->
info: ->
warn: ->
erro: ->
}
game.data.startTime = 0
game.data.ticks = {};
game.socket = {
emit: ->
}
describe "init", ->
beforeEach ->
game.bindSockets = -> assert true
game.bindDispatcher = -> assert true
game.bindIGDispatcher = -> assert true
game.checkSomeoneConnected = -> assert true
game.checkEveryoneConnected = -> assert true
game.autoAddBots = -> assert true
game.start = -> assert true
it "should set the state to lobby", (done) ->
game.init ->
assert.equal(game.data.state, config.states.lobby)
done()
it "should set ticks to {}", (done) ->
game.init ->
assert.deepEqual(game.data.ticks, {})
done()
describe "call checkSomeoneConnected", ->
calledCheckSomeoneConnected = false
beforeEach (done) ->
game.hostId = "123"
serverConfig.waitForHostToConnectTime = 0.1;
game.checkSomeoneConnected = ->
calledCheckSomeoneConnected = true
done();
game.init()
it "should call checkSomeoneConnected after waitForHostToConnectTime seconds", ->
assert.equal calledCheckSomeoneConnected, true
describe "bindSockets", ->
describe "registerWithLobb" , ->
describe "autoAddBots", ->
it "Should call addBot twice with team 0 and three times with team 1", (done) ->
serverConfig.autoAddBots = true
game.hostId = '123'
addBot = sinon.stub(game, 'addBot').callsArgWith(1, 0)
game.autoAddBots (err, botNums) ->
assert.deepEqual addBot.getCall(0).args[0], {team: 1}
assert.deepEqual addBot.getCall(1).args[0], {team: 0}
assert.deepEqual addBot.getCall(2).args[0], {team: 1}
assert.deepEqual addBot.getCall(3).args[0], {team: 0}
assert.deepEqual addBot.getCall(4).args[0], {team: 1}
addBot.restore()
done()
describe "userConnected", ->
describe "checkPlayersAreLoaded", ->
describe "checkSomeoneConnected", ->
beforeEach ->
game.end = -> assert true
it "Should end the game if total players is 0", ->
game.totalPlayers = 0
calledEnd = false
game.end = ->
calledEnd = true
game.checkSomeoneConnected();
assert.equal calledEnd, true
it "Should not end the game if total players is greater than 0", ->
game.totalPlayers = 1
calledEnd = false
game.end = ->
calledEnd = true
game.checkSomeoneConnected();
assert.equal calledEnd, false
describe "checkEveryoneConnected", ->
beforeEach ->
game.cancel = -> true
game.log = {
info: -> true
warn: -> true
error: -> true
}
it "Should emit a warning if totalConnectedPlayers is 0 because it could just be a game that all players didn't accept", ->
game.getTotalConnectedPlayers = -> 0
sinon.stub(game.log, 'warn')
game.checkEveryoneConnected()
assert game.log.warn.calledOnce
it "Should emit an error if totalConnectedPlayers is > 0 && < 6 because something fucked up", ->
game.getTotalConnectedPlayers = -> 3
sinon.stub(game.log, 'error')
game.checkEveryoneConnected()
assert game.log.error.calledOnce
describe "start", ->
describe "begin", ->
describe "cancel", ->
beforeEach ->
game.socket = {emit: ->}
game.end = ->
it "Should send game cancelled message to all players", () ->
sinon.stub(game.socket, 'emit')
game.cancel()
assert game.socket.emit.calledWith(netMsg.game.didNotConnect)
game.socket.emit.restore()
it "Should call end", () ->
sinon.stub(game, 'end')
game.cancel()
assert game.end.calledOnce
game.end.restore()
describe "end", ->
beforeEach ->
game.deleteSelf = -> assert true
game.updatePlayerProfilesAtEnd = -> assert true
it "should set game state to finished", ->
game.data.state = config.states.begun;
game.end();
assert.equal game.data.state, config.states.finished
it "should return false if the state is already finished", ->
game.data.state = config.states.finished
funcReturn = game.end();
assert.equal funcReturn, false
describe "broadcastDetails", ->
it "Should return false if state is finished", ->
game.data.state = config.states.finished
returnCode = game.broadcastDetails();
assert.equal returnCode, false
describe "processPlayerActions", ->
it "Should add all the actions players have done to one array", (done) ->
game.players = [
{lastAction: {type: "minions", data: {xPos: 1, yPos: 2, type: "goblin"}}},
{lastAction: {type: "minions", data: {xPos: 9, yPos: 10, type: "ogre"}}},
{lastAction: {type: "towers", data: {xPos: 3, yPos: 8, type: "crossbow"}}},
]
sinon.stub(game, 'processTick');
game.processPlayerActions(5);
game.processTick.calledWith(5, {
"minions": [
data: {xPos: 1, yPos: 2, type: "goblin"},
data: {xPos: 9, yPos: 10, type: "ogre"},
],
"towers": [
data: {xPos: 3, yPos: 8, type: "crossbow"}
]
});
game.processPlayerActions = ->
done();
describe "processTick", ->
beforeEach ->
global.metricsServer = {
addMetric: -> true
}
it "Should send the tick to each player", ->
it "Should not store the tick but should set currentTick if there is no data", ->
game.set('ticks', {})
tick = 4
commandsDone = null
gameStateHash = 23823212902;
game.processTick tick, commandsDone, gameStateHash
assert !game.get('ticks')[tick]?
assert.equal game.get('currentTick'), 4
it "Should store the tick in ticks if it has data", ->
game.set('ticks', {})
tick = 19
commandsDone = "TestCommands"
gameStateHash = 23823212902;
game.processTick tick, commandsDone, gameStateHash
assert game.get('ticks')[tick]?
assert.equal game.get('ticks')[tick], commandsDone
assert.equal game.get('currentTick'), 19
it "Should create a copy of actionsDone instead of reference it directly", ->
describe "reportGameSnapshot", ->
it "Should set snapshot and snapshotHash and save them out to the db", ->
sinon.stub(game, 'save')
snapshot = {minions: {'one': 1}}
snapshotHash = 'abc123'
game.reportGameSnapshot(1, snapshot, snapshotHash)
assert.deepEqual game.data.snapshot, {tick: 1, hash: snapshotHash, data: JSON.stringify(snapshot)}
describe "setState", ->
describe "setMode", ->
describe "getMode", ->
describe "reportInvalidState", ->
describe "getPlayerTeam", ->
it "Should return team 0 if there are no players in the match yet", ->
game.players = []
assert.equal game.getPlayerTeam(), 0
it "Should allocate for team 0 when there are already many players on it if playerTeamAllocations says so", ->
game.players = [{team: 0}]
game.playerTeamAllocations = {'abc': 0, 'def': 0, 'gyy': 0}
assert.equal game.getPlayerTeam('abc'), 0
assert.equal game.getPlayerTeam('def'), 0
assert.equal game.getPlayerTeam('gyy'), 0
it "Should return playerTeamAllocation if it's set for this player", ->
game.playerTeamAllocations = {'abc': 1}
assert.equal game.getPlayerTeam('abc'), 1
it "Should add player to team with least players", ->
game.players = [{team: 0}]
assert.equal game.getPlayerTeam(), 1
describe "findFirstBot", ->
describe "playerJoin", ->
player = null
addPlayerArgs = null
callbackArgs = null
socket = "SockYea!"
socketArgs = null
joinedGame = false
beforeEach ->
player = new Player();
callback = ->
callbackArgs = arguments
game.addPlayer = ->
addPlayerArgs = arguments;
player.setSocket = ->
socketArgs = arguments;
player.joinGame = ->
joinedGame = true
player.sendDetails = -> assert true
game.dispatcher = new Dispatcher();
game.kickPlayer = -> assert true
game.isCustomGame = -> true
game.broadcastDetails = sinon.stub()
game.playerJoin(player, socket, callback)
it "Should call addplayer with the player", ->
assert addPlayerArgs?
assert.deepEqual addPlayerArgs[0], player
it "Should set players team and socket and call joinGame", ->
assert.equal player.team, 0
assert socketArgs?
assert.equal socketArgs[0], socket
assert.equal joinedGame, true
it "Should add players to teams equally as more are added", ->
it "Should call sendDetails", ->
sendDetailsCalled = false
player.sendDetails = ->
sendDetailsCalled = true
game.playerJoin player, socket
assert.equal sendDetailsCalled, true
it "Should trigger broadcastDetails", ->
assert game.broadcastDetails.calledOnce
it "Should report game is full if the game is in the lobby and total players is more than max and there are no bots in the game", ->
game.data.state = config.states.lobby
game.maxPlayers = 6
game.totalPlayers = 6
game.players = []
for i in [0...6]
game.players.push({isBot: false})
emitArgs = null
socket =
emit: () -> emitArgs = arguments
game.playerJoin(player, socket)
assert emitArgs?
assert.equal emitArgs[0], netMsg.game.error
assert.deepEqual emitArgs[1], {error: netMsg.game.full}
it "Should not report game is full if it is at max players but there are bots in the game", ->
game.data.state = config.states.lobby
game.maxPlayers = 6
game.totalPlayers = 6
game.players = []
for i in [0...6]
game.players.push({isBot: !!(i % 2)})
emitArgs = null
socket =
emit: () -> emitArgs = arguments
game.playerJoin(player, socket)
assert !emitArgs?
it "Should not report game is full if the game has started and total players is more than max", ->
game.data.state = config.states.started
game.maxPlayers = 6
game.totalPlayers = 6
emitArgs = null
socket =
emit: () -> emitArgs = arguments
game.playerJoin(player, socket)
assert !emitArgs?
it "Should call syncData on player if gamestate is begun", ->
calledSyncData = false
player.syncData = -> calledSyncData = true
game.data.state = config.states.init
game.playerJoin(player, socket)
assert.equal calledSyncData, false
game.data.state = config.states.begun
game.playerJoin(player, socket)
assert.equal calledSyncData, true
describe "addPlayer", ->
beforeEach ->
game.dispatcher = new Dispatcher();
describe "deletePlayer", ->
it "Should return false immediately if the game is finished", ->
### This is here because sometimes clients will send a disconnect
after the game is alredy over and make the game crash due to everything
being deleted already. ###
game.data.state = config.states.finished
player = {id: 5, disconnect: ->}
game.players = [player]
funcReturn = game.deletePlayer(player)
assert.equal funcReturn, false
it "Should end the game if the game is in lobby state and there are no players left", ->
endCalled = false
game.end = ->
endCalled = true
game.data.state = config.states.lobby
game.totalPlayers = 0
game.deletePlayer("testPlayerId")
assert.equal endCalled, true
describe "playerConnected", ->
it "should set gameEndCheck to null", ->
game.gameEndCheck = "test"
game.playerConnected({id: 5})
assert.equal game.gameEndCheck, null
describe "playerDisconnected", ->
beforeEach ->
game.checkIfGameShouldEnd = -> assert true
it "Should create a gameEndCheck if all players are disconnected and state is more than lobby", ->
game.data.state = config.states.begun
game.players = [{id: 5, disconnected: true}, {id: 6, disconnected: true}]
game.playerDisconnected(null)
assert game.gameEndCheck?
it "Should not create a gameEndCheck if all players are disconnected and state is lobby", ->
game.data.state = config.states.lobby
game.players = [{id: 5, disconnected: true}, {id: 6, disconnected: true}]
game.playerDisconnected(null)
assert.equal game.gameEndCheck, null
it "Should not create a gameEndCheck if all players are disconnected and state is started", ->
game.data.state = config.states.started
game.players = [{id: 5, disconnected: true}, {id: 6, disconnected: true}]
game.playerDisconnected(null)
assert.equal game.gameEndCheck, null
it "Sould not create a gameEndCheck if players list has connected people in it", ->
game.data.state = config.states.begun
game.players = [{id: 5, disconnected: false}, {id: 6, disconnected: true}]
game.playerDisconnected(null)
assert.equal game.gameEndCheck, null
it "Should not create a gameEndCheck if one already exists", ->
game.gameEndCheck = {mew: 5}
game.data.state = config.states.begun
game.players = [{id: 5, disconnected: true}, {id: 6, disconnected: true}]
game.playerDisconnected(null)
assert.deepEqual game.gameEndCheck, {mew: 5}
describe "addBot", ->
it "Should return false if the state is not lobby", ->
game.data.state = config.states.started
callback = sinon.stub()
game.addBot({}, callback);
assert callback.calledOnce
it "Should send a request to the bot master to add a bot to this game", ->
# game.data.state = config.states.lobby
# game.addBot();
describe "getPlayers", ->
it "Should get a list of players containing id, name, race, team for each", ->
playersList = [
{
id: 0,
name: "<NAME>",
race: "shadow",
team: 0
isBot: false
ready: false
loaded: false
},
{
id: 1,
name: "<NAME>",
race: "druids",
team: 1
isBot: false
ready: false
loaded: false
}
]
game.players = playersList
playersReturn = game.getPlayers()
assert.deepEqual playersList, playersReturn
describe "update", ->
describe "checkIfGameShouldEnd", ->
beforeEach ->
game.end = -> assert true
it "Should set gameEndCheck to null", ->
game.gameEndCheck = {mew: 4}
game.checkIfGameShouldEnd()
assert.equal game.gameEndCheck, null
it "Should end the game if all players are disconnected", ->
game.players = [{id: 1, disconnected: true}]
endCalled = false
game.end = ->
endCalled = true
game.checkIfGameShouldEnd();
assert.equal endCalled, true
it "Should not end the game if players have reconnected", ->
game.players = [{id: 6, disconnected: false}, {id: 8, disconnected: true}]
endCalled = false
game.end = ->
endCalled = true
game.checkIfGameShouldEnd();
assert.equal endCalled, false
describe "updatePlayerProfilesAtEnd", ->
it "Should callback false if the winningTeam is undefined", (done) ->
game.updatePlayerProfilesAtEnd undefined, (err, result) ->
assert.equal result, false
done()
it "Should call calculateEloChange if winningTeam is 0", (done) ->
sinon.stub(game, "calculateEloChange")
game.updatePlayerProfilesAtEnd 0, (err, result) ->
assert game.calculateEloChange.calledWith(0)
game.calculateEloChange.restore()
done()
it "Should call calculateEloChange if winningTeam is 1", (done) ->
sinon.stub(game, "calculateEloChange")
game.updatePlayerProfilesAtEnd 1, (err, result) ->
assert game.calculateEloChange.calledWith(1)
game.calculateEloChange.restore()
done()
describe "calculateEloChange", ->
it "Should return 8 for winning team 0 if elos are 1600 and 1400", (done) ->
sinon.stub(game, 'getTeamElos').callsArgWith(0, null, [1600, 1400])
game.calculateEloChange 0, (err, eloChange) ->
assert.equal(eloChange, 8)
done()
it "Should return 8 for winning team 1 if elos are 1400 and 1600", (done) ->
sinon.stub(game, 'getTeamElos').callsArgWith(0, null, [1400, 1600])
game.calculateEloChange 1, (err, eloChange) ->
assert.equal(eloChange, 8)
done()
it "Should return 24 for winning team 0 if elos are 1600 and 1400", (done) ->
sinon.stub(game, 'getTeamElos').callsArgWith(0, null, [1600, 1400])
game.calculateEloChange 1, (err, eloChange) ->
assert.equal(eloChange, 24)
done()
it "Should return 24 for winning team 0 if elos are 1400 and 1600", (done) ->
sinon.stub(game, 'getTeamElos').callsArgWith(0, null, [1400, 1600])
game.calculateEloChange 0, (err, eloChange) ->
assert.equal(eloChange, 24)
done()
describe "getTeamElos", ->
it "Should return the average elo for each team", (done) ->
players = [
{id: 1, team: 0, get: -> 1100}
{id: 2, team: 0, get: -> 1200}
{id: 3, team: 0, get: -> 1300}
{id: 4, team: 1, get: -> 1700}
{id: 5, team: 1, get: -> 1800}
{id: 6, team: 1, get: -> 1750}
]
game.players = players
sinon.stub(UserMock, 'findById', (id, callback) -> callback(null, players[id-1]))
game.getTeamElos (err, teamElos) ->
if err then return done(err)
assert.equal(teamElos[0], 1200)
assert.equal(teamElos[1], 1750)
UserMock.findById.restore()
done()
describe "allocatePlayerTeams", ->
it "Should put 3 players on team 1 and 3 on team 2, grouped with those they matchmade with", (done) ->
game.matchId = "123"
data = [
{userIds: ['a', 'b', 'c']}
{userIds: ['d', 'e', 'f']}
]
queuers = data.map((q) -> {data: q, get: (name) -> @data[name]})
sinon.stub(QueuerMock, 'findAllByMatchId').callsArgWith(1, null, queuers)
game.allocatePlayerTeams (err, result) ->
assert.deepEqual game.playerTeamAllocations, {a: 0, b: 0, c: 0, d: 1, e: 1, f: 1}
QueuerMock.findAllByMatchId.restore()
done()
it "Should work with teams of 2 + 1", (done) ->
game.matchId = "123"
data = [
{userIds: ['a', 'b']}
{userIds: ['d', 'e']}
{userIds: ['c']}
{userIds: ['f']}
]
queuers = data.map((q) -> {data: q, get: (name) -> @data[name]})
sinon.stub(QueuerMock, 'findAllByMatchId').callsArgWith(1, null, queuers)
game.allocatePlayerTeams (err, result) ->
assert.deepEqual game.playerTeamAllocations, {a: 0, b: 0, c: 0, d: 1, e: 1, f: 1}
QueuerMock.findAllByMatchId.restore()
done()
it "Should work with teams of 2 + 1 in a strange order", (done) ->
game.matchId = "123"
data = [
{userIds: ['c']}
{userIds: ['a', 'b']}
{userIds: ['d', 'e']}
{userIds: ['f']}
]
queuers = data.map((q) -> {data: q, get: (name) -> @data[name]})
sinon.stub(QueuerMock, 'findAllByMatchId').callsArgWith(1, null, queuers)
game.allocatePlayerTeams (err, result) ->
assert.deepEqual game.playerTeamAllocations, {a: 0, b: 0, c: 0, d: 1, e: 1, f: 1}
QueuerMock.findAllByMatchId.restore()
done()
describe "allocateRandomRaces", ->
it "Should set all players who have a null race to a valid race", ->
game.isCustomGame = -> false
game.players = [
{race: 'shadow', team: 0}
{race: 'crusaders', team: 0}
{race: null, team: 0, setRace: (@race) ->}
]
game.allocateRandomRaces()
assert.equal(game.players[0].race, 'shadow')
assert.equal(game.players[1].race, 'crusaders')
assert(game.players[2].race != null)
| true | assert = require 'assert'
sinon = require 'sinon'
proxyquire = require 'proxyquire'
Player = require '../../../lib/player'
config = require 'config/general'
serverConfig = require 'config/gameserver'
Dispatcher = require '../dispatcher-mock'
GameModel = require '../mocks/game-model-mock'
gameMsg = require 'config/game-messages'
netMsg = require 'config/net-messages'
UserMock = {
findById: -> {}
}
QueuerMock = {
findAllByMatchId: -> []
}
noop = ->
class ModelMock
data: {}
set: (item, value) -> @data[item] = value
get: (item) -> @data[item]
save: (callback = noop) -> callback()
dbMock = {
models: {
User: UserMock
Queuer: QueuerMock
Model: ModelMock
}
}
Game = proxyquire '../../../models/game', {
'game': IGMock
'game/lib/game/main': IGGameMock
'database': dbMock
}
Game.register = ->
Game.updateState = ->
Game.postToLobby = ->
game = null
describe "Server Game", ->
beforeEach ->
app =
settings:
socketIO: null
game = new Game(app)
game.log = {
debug: ->
info: ->
warn: ->
erro: ->
}
game.data.startTime = 0
game.data.ticks = {};
game.socket = {
emit: ->
}
describe "init", ->
beforeEach ->
game.bindSockets = -> assert true
game.bindDispatcher = -> assert true
game.bindIGDispatcher = -> assert true
game.checkSomeoneConnected = -> assert true
game.checkEveryoneConnected = -> assert true
game.autoAddBots = -> assert true
game.start = -> assert true
it "should set the state to lobby", (done) ->
game.init ->
assert.equal(game.data.state, config.states.lobby)
done()
it "should set ticks to {}", (done) ->
game.init ->
assert.deepEqual(game.data.ticks, {})
done()
describe "call checkSomeoneConnected", ->
calledCheckSomeoneConnected = false
beforeEach (done) ->
game.hostId = "123"
serverConfig.waitForHostToConnectTime = 0.1;
game.checkSomeoneConnected = ->
calledCheckSomeoneConnected = true
done();
game.init()
it "should call checkSomeoneConnected after waitForHostToConnectTime seconds", ->
assert.equal calledCheckSomeoneConnected, true
describe "bindSockets", ->
describe "registerWithLobb" , ->
describe "autoAddBots", ->
it "Should call addBot twice with team 0 and three times with team 1", (done) ->
serverConfig.autoAddBots = true
game.hostId = '123'
addBot = sinon.stub(game, 'addBot').callsArgWith(1, 0)
game.autoAddBots (err, botNums) ->
assert.deepEqual addBot.getCall(0).args[0], {team: 1}
assert.deepEqual addBot.getCall(1).args[0], {team: 0}
assert.deepEqual addBot.getCall(2).args[0], {team: 1}
assert.deepEqual addBot.getCall(3).args[0], {team: 0}
assert.deepEqual addBot.getCall(4).args[0], {team: 1}
addBot.restore()
done()
describe "userConnected", ->
describe "checkPlayersAreLoaded", ->
describe "checkSomeoneConnected", ->
beforeEach ->
game.end = -> assert true
it "Should end the game if total players is 0", ->
game.totalPlayers = 0
calledEnd = false
game.end = ->
calledEnd = true
game.checkSomeoneConnected();
assert.equal calledEnd, true
it "Should not end the game if total players is greater than 0", ->
game.totalPlayers = 1
calledEnd = false
game.end = ->
calledEnd = true
game.checkSomeoneConnected();
assert.equal calledEnd, false
describe "checkEveryoneConnected", ->
beforeEach ->
game.cancel = -> true
game.log = {
info: -> true
warn: -> true
error: -> true
}
it "Should emit a warning if totalConnectedPlayers is 0 because it could just be a game that all players didn't accept", ->
game.getTotalConnectedPlayers = -> 0
sinon.stub(game.log, 'warn')
game.checkEveryoneConnected()
assert game.log.warn.calledOnce
it "Should emit an error if totalConnectedPlayers is > 0 && < 6 because something fucked up", ->
game.getTotalConnectedPlayers = -> 3
sinon.stub(game.log, 'error')
game.checkEveryoneConnected()
assert game.log.error.calledOnce
describe "start", ->
describe "begin", ->
describe "cancel", ->
beforeEach ->
game.socket = {emit: ->}
game.end = ->
it "Should send game cancelled message to all players", () ->
sinon.stub(game.socket, 'emit')
game.cancel()
assert game.socket.emit.calledWith(netMsg.game.didNotConnect)
game.socket.emit.restore()
it "Should call end", () ->
sinon.stub(game, 'end')
game.cancel()
assert game.end.calledOnce
game.end.restore()
describe "end", ->
beforeEach ->
game.deleteSelf = -> assert true
game.updatePlayerProfilesAtEnd = -> assert true
it "should set game state to finished", ->
game.data.state = config.states.begun;
game.end();
assert.equal game.data.state, config.states.finished
it "should return false if the state is already finished", ->
game.data.state = config.states.finished
funcReturn = game.end();
assert.equal funcReturn, false
describe "broadcastDetails", ->
it "Should return false if state is finished", ->
game.data.state = config.states.finished
returnCode = game.broadcastDetails();
assert.equal returnCode, false
describe "processPlayerActions", ->
it "Should add all the actions players have done to one array", (done) ->
game.players = [
{lastAction: {type: "minions", data: {xPos: 1, yPos: 2, type: "goblin"}}},
{lastAction: {type: "minions", data: {xPos: 9, yPos: 10, type: "ogre"}}},
{lastAction: {type: "towers", data: {xPos: 3, yPos: 8, type: "crossbow"}}},
]
sinon.stub(game, 'processTick');
game.processPlayerActions(5);
game.processTick.calledWith(5, {
"minions": [
data: {xPos: 1, yPos: 2, type: "goblin"},
data: {xPos: 9, yPos: 10, type: "ogre"},
],
"towers": [
data: {xPos: 3, yPos: 8, type: "crossbow"}
]
});
game.processPlayerActions = ->
done();
describe "processTick", ->
beforeEach ->
global.metricsServer = {
addMetric: -> true
}
it "Should send the tick to each player", ->
it "Should not store the tick but should set currentTick if there is no data", ->
game.set('ticks', {})
tick = 4
commandsDone = null
gameStateHash = 23823212902;
game.processTick tick, commandsDone, gameStateHash
assert !game.get('ticks')[tick]?
assert.equal game.get('currentTick'), 4
it "Should store the tick in ticks if it has data", ->
game.set('ticks', {})
tick = 19
commandsDone = "TestCommands"
gameStateHash = 23823212902;
game.processTick tick, commandsDone, gameStateHash
assert game.get('ticks')[tick]?
assert.equal game.get('ticks')[tick], commandsDone
assert.equal game.get('currentTick'), 19
it "Should create a copy of actionsDone instead of reference it directly", ->
describe "reportGameSnapshot", ->
it "Should set snapshot and snapshotHash and save them out to the db", ->
sinon.stub(game, 'save')
snapshot = {minions: {'one': 1}}
snapshotHash = 'abc123'
game.reportGameSnapshot(1, snapshot, snapshotHash)
assert.deepEqual game.data.snapshot, {tick: 1, hash: snapshotHash, data: JSON.stringify(snapshot)}
describe "setState", ->
describe "setMode", ->
describe "getMode", ->
describe "reportInvalidState", ->
describe "getPlayerTeam", ->
it "Should return team 0 if there are no players in the match yet", ->
game.players = []
assert.equal game.getPlayerTeam(), 0
it "Should allocate for team 0 when there are already many players on it if playerTeamAllocations says so", ->
game.players = [{team: 0}]
game.playerTeamAllocations = {'abc': 0, 'def': 0, 'gyy': 0}
assert.equal game.getPlayerTeam('abc'), 0
assert.equal game.getPlayerTeam('def'), 0
assert.equal game.getPlayerTeam('gyy'), 0
it "Should return playerTeamAllocation if it's set for this player", ->
game.playerTeamAllocations = {'abc': 1}
assert.equal game.getPlayerTeam('abc'), 1
it "Should add player to team with least players", ->
game.players = [{team: 0}]
assert.equal game.getPlayerTeam(), 1
describe "findFirstBot", ->
describe "playerJoin", ->
player = null
addPlayerArgs = null
callbackArgs = null
socket = "SockYea!"
socketArgs = null
joinedGame = false
beforeEach ->
player = new Player();
callback = ->
callbackArgs = arguments
game.addPlayer = ->
addPlayerArgs = arguments;
player.setSocket = ->
socketArgs = arguments;
player.joinGame = ->
joinedGame = true
player.sendDetails = -> assert true
game.dispatcher = new Dispatcher();
game.kickPlayer = -> assert true
game.isCustomGame = -> true
game.broadcastDetails = sinon.stub()
game.playerJoin(player, socket, callback)
it "Should call addplayer with the player", ->
assert addPlayerArgs?
assert.deepEqual addPlayerArgs[0], player
it "Should set players team and socket and call joinGame", ->
assert.equal player.team, 0
assert socketArgs?
assert.equal socketArgs[0], socket
assert.equal joinedGame, true
it "Should add players to teams equally as more are added", ->
it "Should call sendDetails", ->
sendDetailsCalled = false
player.sendDetails = ->
sendDetailsCalled = true
game.playerJoin player, socket
assert.equal sendDetailsCalled, true
it "Should trigger broadcastDetails", ->
assert game.broadcastDetails.calledOnce
it "Should report game is full if the game is in the lobby and total players is more than max and there are no bots in the game", ->
game.data.state = config.states.lobby
game.maxPlayers = 6
game.totalPlayers = 6
game.players = []
for i in [0...6]
game.players.push({isBot: false})
emitArgs = null
socket =
emit: () -> emitArgs = arguments
game.playerJoin(player, socket)
assert emitArgs?
assert.equal emitArgs[0], netMsg.game.error
assert.deepEqual emitArgs[1], {error: netMsg.game.full}
it "Should not report game is full if it is at max players but there are bots in the game", ->
game.data.state = config.states.lobby
game.maxPlayers = 6
game.totalPlayers = 6
game.players = []
for i in [0...6]
game.players.push({isBot: !!(i % 2)})
emitArgs = null
socket =
emit: () -> emitArgs = arguments
game.playerJoin(player, socket)
assert !emitArgs?
it "Should not report game is full if the game has started and total players is more than max", ->
game.data.state = config.states.started
game.maxPlayers = 6
game.totalPlayers = 6
emitArgs = null
socket =
emit: () -> emitArgs = arguments
game.playerJoin(player, socket)
assert !emitArgs?
it "Should call syncData on player if gamestate is begun", ->
calledSyncData = false
player.syncData = -> calledSyncData = true
game.data.state = config.states.init
game.playerJoin(player, socket)
assert.equal calledSyncData, false
game.data.state = config.states.begun
game.playerJoin(player, socket)
assert.equal calledSyncData, true
describe "addPlayer", ->
beforeEach ->
game.dispatcher = new Dispatcher();
describe "deletePlayer", ->
it "Should return false immediately if the game is finished", ->
### This is here because sometimes clients will send a disconnect
after the game is alredy over and make the game crash due to everything
being deleted already. ###
game.data.state = config.states.finished
player = {id: 5, disconnect: ->}
game.players = [player]
funcReturn = game.deletePlayer(player)
assert.equal funcReturn, false
it "Should end the game if the game is in lobby state and there are no players left", ->
endCalled = false
game.end = ->
endCalled = true
game.data.state = config.states.lobby
game.totalPlayers = 0
game.deletePlayer("testPlayerId")
assert.equal endCalled, true
describe "playerConnected", ->
it "should set gameEndCheck to null", ->
game.gameEndCheck = "test"
game.playerConnected({id: 5})
assert.equal game.gameEndCheck, null
describe "playerDisconnected", ->
beforeEach ->
game.checkIfGameShouldEnd = -> assert true
it "Should create a gameEndCheck if all players are disconnected and state is more than lobby", ->
game.data.state = config.states.begun
game.players = [{id: 5, disconnected: true}, {id: 6, disconnected: true}]
game.playerDisconnected(null)
assert game.gameEndCheck?
it "Should not create a gameEndCheck if all players are disconnected and state is lobby", ->
game.data.state = config.states.lobby
game.players = [{id: 5, disconnected: true}, {id: 6, disconnected: true}]
game.playerDisconnected(null)
assert.equal game.gameEndCheck, null
it "Should not create a gameEndCheck if all players are disconnected and state is started", ->
game.data.state = config.states.started
game.players = [{id: 5, disconnected: true}, {id: 6, disconnected: true}]
game.playerDisconnected(null)
assert.equal game.gameEndCheck, null
it "Sould not create a gameEndCheck if players list has connected people in it", ->
game.data.state = config.states.begun
game.players = [{id: 5, disconnected: false}, {id: 6, disconnected: true}]
game.playerDisconnected(null)
assert.equal game.gameEndCheck, null
it "Should not create a gameEndCheck if one already exists", ->
game.gameEndCheck = {mew: 5}
game.data.state = config.states.begun
game.players = [{id: 5, disconnected: true}, {id: 6, disconnected: true}]
game.playerDisconnected(null)
assert.deepEqual game.gameEndCheck, {mew: 5}
describe "addBot", ->
it "Should return false if the state is not lobby", ->
game.data.state = config.states.started
callback = sinon.stub()
game.addBot({}, callback);
assert callback.calledOnce
it "Should send a request to the bot master to add a bot to this game", ->
# game.data.state = config.states.lobby
# game.addBot();
describe "getPlayers", ->
it "Should get a list of players containing id, name, race, team for each", ->
playersList = [
{
id: 0,
name: "PI:NAME:<NAME>END_PI",
race: "shadow",
team: 0
isBot: false
ready: false
loaded: false
},
{
id: 1,
name: "PI:NAME:<NAME>END_PI",
race: "druids",
team: 1
isBot: false
ready: false
loaded: false
}
]
game.players = playersList
playersReturn = game.getPlayers()
assert.deepEqual playersList, playersReturn
describe "update", ->
describe "checkIfGameShouldEnd", ->
beforeEach ->
game.end = -> assert true
it "Should set gameEndCheck to null", ->
game.gameEndCheck = {mew: 4}
game.checkIfGameShouldEnd()
assert.equal game.gameEndCheck, null
it "Should end the game if all players are disconnected", ->
game.players = [{id: 1, disconnected: true}]
endCalled = false
game.end = ->
endCalled = true
game.checkIfGameShouldEnd();
assert.equal endCalled, true
it "Should not end the game if players have reconnected", ->
game.players = [{id: 6, disconnected: false}, {id: 8, disconnected: true}]
endCalled = false
game.end = ->
endCalled = true
game.checkIfGameShouldEnd();
assert.equal endCalled, false
describe "updatePlayerProfilesAtEnd", ->
it "Should callback false if the winningTeam is undefined", (done) ->
game.updatePlayerProfilesAtEnd undefined, (err, result) ->
assert.equal result, false
done()
it "Should call calculateEloChange if winningTeam is 0", (done) ->
sinon.stub(game, "calculateEloChange")
game.updatePlayerProfilesAtEnd 0, (err, result) ->
assert game.calculateEloChange.calledWith(0)
game.calculateEloChange.restore()
done()
it "Should call calculateEloChange if winningTeam is 1", (done) ->
sinon.stub(game, "calculateEloChange")
game.updatePlayerProfilesAtEnd 1, (err, result) ->
assert game.calculateEloChange.calledWith(1)
game.calculateEloChange.restore()
done()
describe "calculateEloChange", ->
it "Should return 8 for winning team 0 if elos are 1600 and 1400", (done) ->
sinon.stub(game, 'getTeamElos').callsArgWith(0, null, [1600, 1400])
game.calculateEloChange 0, (err, eloChange) ->
assert.equal(eloChange, 8)
done()
it "Should return 8 for winning team 1 if elos are 1400 and 1600", (done) ->
sinon.stub(game, 'getTeamElos').callsArgWith(0, null, [1400, 1600])
game.calculateEloChange 1, (err, eloChange) ->
assert.equal(eloChange, 8)
done()
it "Should return 24 for winning team 0 if elos are 1600 and 1400", (done) ->
sinon.stub(game, 'getTeamElos').callsArgWith(0, null, [1600, 1400])
game.calculateEloChange 1, (err, eloChange) ->
assert.equal(eloChange, 24)
done()
it "Should return 24 for winning team 0 if elos are 1400 and 1600", (done) ->
sinon.stub(game, 'getTeamElos').callsArgWith(0, null, [1400, 1600])
game.calculateEloChange 0, (err, eloChange) ->
assert.equal(eloChange, 24)
done()
describe "getTeamElos", ->
it "Should return the average elo for each team", (done) ->
players = [
{id: 1, team: 0, get: -> 1100}
{id: 2, team: 0, get: -> 1200}
{id: 3, team: 0, get: -> 1300}
{id: 4, team: 1, get: -> 1700}
{id: 5, team: 1, get: -> 1800}
{id: 6, team: 1, get: -> 1750}
]
game.players = players
sinon.stub(UserMock, 'findById', (id, callback) -> callback(null, players[id-1]))
game.getTeamElos (err, teamElos) ->
if err then return done(err)
assert.equal(teamElos[0], 1200)
assert.equal(teamElos[1], 1750)
UserMock.findById.restore()
done()
describe "allocatePlayerTeams", ->
it "Should put 3 players on team 1 and 3 on team 2, grouped with those they matchmade with", (done) ->
game.matchId = "123"
data = [
{userIds: ['a', 'b', 'c']}
{userIds: ['d', 'e', 'f']}
]
queuers = data.map((q) -> {data: q, get: (name) -> @data[name]})
sinon.stub(QueuerMock, 'findAllByMatchId').callsArgWith(1, null, queuers)
game.allocatePlayerTeams (err, result) ->
assert.deepEqual game.playerTeamAllocations, {a: 0, b: 0, c: 0, d: 1, e: 1, f: 1}
QueuerMock.findAllByMatchId.restore()
done()
it "Should work with teams of 2 + 1", (done) ->
game.matchId = "123"
data = [
{userIds: ['a', 'b']}
{userIds: ['d', 'e']}
{userIds: ['c']}
{userIds: ['f']}
]
queuers = data.map((q) -> {data: q, get: (name) -> @data[name]})
sinon.stub(QueuerMock, 'findAllByMatchId').callsArgWith(1, null, queuers)
game.allocatePlayerTeams (err, result) ->
assert.deepEqual game.playerTeamAllocations, {a: 0, b: 0, c: 0, d: 1, e: 1, f: 1}
QueuerMock.findAllByMatchId.restore()
done()
it "Should work with teams of 2 + 1 in a strange order", (done) ->
game.matchId = "123"
data = [
{userIds: ['c']}
{userIds: ['a', 'b']}
{userIds: ['d', 'e']}
{userIds: ['f']}
]
queuers = data.map((q) -> {data: q, get: (name) -> @data[name]})
sinon.stub(QueuerMock, 'findAllByMatchId').callsArgWith(1, null, queuers)
game.allocatePlayerTeams (err, result) ->
assert.deepEqual game.playerTeamAllocations, {a: 0, b: 0, c: 0, d: 1, e: 1, f: 1}
QueuerMock.findAllByMatchId.restore()
done()
describe "allocateRandomRaces", ->
it "Should set all players who have a null race to a valid race", ->
game.isCustomGame = -> false
game.players = [
{race: 'shadow', team: 0}
{race: 'crusaders', team: 0}
{race: null, team: 0, setRace: (@race) ->}
]
game.allocateRandomRaces()
assert.equal(game.players[0].race, 'shadow')
assert.equal(game.players[1].race, 'crusaders')
assert(game.players[2].race != null)
|
[
{
"context": "= redis.createClient()\n\nkeys = {\n token: \"tokens:%s\"\n client: \"clients:%s\"\n refreshToken: \"re",
"end": 139,
"score": 0.7946905493736267,
"start": 130,
"tag": "KEY",
"value": "tokens:%s"
}
] | src/models/oauth2.coffee | aegypius/smarter-tv | 0 | model = module.exports
util = require "util"
redis = require "fakeredis"
db = redis.createClient()
keys = {
token: "tokens:%s"
client: "clients:%s"
refreshToken: "refreshTokens:%s"
grantTypes: "grantTypes:%s"
user: "users:%s"
}
model.getAccessToken = (bearerToken, callback)->
db.hgetall util.format keys.token, bearerToken, (err, token)->
if err
callback err
unless token
callback()
else
callback null, {
accessToken: token.accessToken
clientId: token.clientId
expires: new Date token.expires if token.expires
userId: token.userId
}
model.getClient = (clientId, clientSecret, callback)->
model.getRefreshToken = (bearerToken, callback)->
model.grantTypeAllowed = (clientId, grantType, callback)->
model.saveAccessToken = (accessToken, clientId, expires, user, callback)->
model.saveRefreshToken = (refreshToken, clientId, expires, user, callback)->
model.getUser = (username, password, callback) ->
| 169825 | model = module.exports
util = require "util"
redis = require "fakeredis"
db = redis.createClient()
keys = {
token: "<KEY>"
client: "clients:%s"
refreshToken: "refreshTokens:%s"
grantTypes: "grantTypes:%s"
user: "users:%s"
}
model.getAccessToken = (bearerToken, callback)->
db.hgetall util.format keys.token, bearerToken, (err, token)->
if err
callback err
unless token
callback()
else
callback null, {
accessToken: token.accessToken
clientId: token.clientId
expires: new Date token.expires if token.expires
userId: token.userId
}
model.getClient = (clientId, clientSecret, callback)->
model.getRefreshToken = (bearerToken, callback)->
model.grantTypeAllowed = (clientId, grantType, callback)->
model.saveAccessToken = (accessToken, clientId, expires, user, callback)->
model.saveRefreshToken = (refreshToken, clientId, expires, user, callback)->
model.getUser = (username, password, callback) ->
| true | model = module.exports
util = require "util"
redis = require "fakeredis"
db = redis.createClient()
keys = {
token: "PI:KEY:<KEY>END_PI"
client: "clients:%s"
refreshToken: "refreshTokens:%s"
grantTypes: "grantTypes:%s"
user: "users:%s"
}
model.getAccessToken = (bearerToken, callback)->
db.hgetall util.format keys.token, bearerToken, (err, token)->
if err
callback err
unless token
callback()
else
callback null, {
accessToken: token.accessToken
clientId: token.clientId
expires: new Date token.expires if token.expires
userId: token.userId
}
model.getClient = (clientId, clientSecret, callback)->
model.getRefreshToken = (bearerToken, callback)->
model.grantTypeAllowed = (clientId, grantType, callback)->
model.saveAccessToken = (accessToken, clientId, expires, user, callback)->
model.saveRefreshToken = (refreshToken, clientId, expires, user, callback)->
model.getUser = (username, password, callback) ->
|
[
{
"context": "###\n * cena_auth\n * https://github.com/1egoman/cena_app\n *\n * Copyright (c) 2015 Ryan Gaus\n * Li",
"end": 46,
"score": 0.9984235763549805,
"start": 39,
"tag": "USERNAME",
"value": "1egoman"
},
{
"context": "thub.com/1egoman/cena_app\n *\n * Copyright (c) 2015 Ryan ... | src/routes/auth.coffee | 1egoman/cena_app | 0 | ###
* cena_auth
* https://github.com/1egoman/cena_app
*
* Copyright (c) 2015 Ryan Gaus
* Licensed under the MIT license.
###
'use strict';
passport = require "passport"
bodyParser = require "body-parser"
User = require '../models/user'
module.exports = (app) ->
# login view
app.get "/login", (req, res) ->
res.render "login_dialog", flash_msg: res.locals.flash
# login post route
app.post '/auth/user',
bodyParser.urlencoded(extended: true),
passport.authenticate 'local',
successRedirect: '/account'
failureRedirect: '/login'
failureFlash: true
# logout route
app.get '/logout', (req, res) ->
req.logout()
res.redirect '/'
| 126426 | ###
* cena_auth
* https://github.com/1egoman/cena_app
*
* Copyright (c) 2015 <NAME>
* Licensed under the MIT license.
###
'use strict';
passport = require "passport"
bodyParser = require "body-parser"
User = require '../models/user'
module.exports = (app) ->
# login view
app.get "/login", (req, res) ->
res.render "login_dialog", flash_msg: res.locals.flash
# login post route
app.post '/auth/user',
bodyParser.urlencoded(extended: true),
passport.authenticate 'local',
successRedirect: '/account'
failureRedirect: '/login'
failureFlash: true
# logout route
app.get '/logout', (req, res) ->
req.logout()
res.redirect '/'
| true | ###
* cena_auth
* https://github.com/1egoman/cena_app
*
* Copyright (c) 2015 PI:NAME:<NAME>END_PI
* Licensed under the MIT license.
###
'use strict';
passport = require "passport"
bodyParser = require "body-parser"
User = require '../models/user'
module.exports = (app) ->
# login view
app.get "/login", (req, res) ->
res.render "login_dialog", flash_msg: res.locals.flash
# login post route
app.post '/auth/user',
bodyParser.urlencoded(extended: true),
passport.authenticate 'local',
successRedirect: '/account'
failureRedirect: '/login'
failureFlash: true
# logout route
app.get '/logout', (req, res) ->
req.logout()
res.redirect '/'
|
[
{
"context": "###\n# @author Jinzulen\n# @license Apache 2.0\n# @copyright Copyright 2020",
"end": 22,
"score": 0.9998658299446106,
"start": 14,
"tag": "NAME",
"value": "Jinzulen"
},
{
"context": "\n# @license Apache 2.0\n# @copyright Copyright 2020 Khalil G. <https://github.com/Jinz... | src/API/EmojiAPI.coffee | DiaxManPl/DEmojiJS | 24 | ###
# @author Jinzulen
# @license Apache 2.0
# @copyright Copyright 2020 Khalil G. <https://github.com/Jinzulen>
###
HTTPS = require "https"
Cache = require "./EmojiCache"
exports.GrabCategories = () ->
if !Cache.getCache "/Categories"
this.contactAPI "https://emoji.gg/api/?request=categories", (Error, Data) ->
if Error
throw Error
exports.contactAPI = (Endpoint, Callback) ->
try
Stores = {
"https://emoji.gg/api/": "/Emoji",
"https://emoji.gg/api/packs": "/Packs",
"https://emoji.gg/api/?request=stats": "/Stats",
"https://emoji.gg/api/?request=categories": "/Categories"
}
Key = Cache.getCache Stores[Endpoint]
if !Key
HTTPS.get Endpoint, (Response) ->
Error = ""
rawData = ""
Code = Response.statusCode
Type = Response.headers["content-type"]
if Code != 200
Error = "# [DEmojiJS] Could not issue request @ " + Endpoint
if Error
Response.resume()
Callback Error
Response.setEncoding "utf8"
Response.on "data", (Buffer) ->
rawData += JSON.parse JSON.stringify Buffer
Response.on "end", () ->
try
Data = rawData
Cache.setCache Stores[Endpoint], Data
catch E
throw E
Callback Error, JSON.parse Data
else
Callback null, JSON.parse Key
catch E
throw E
| 187760 | ###
# @author <NAME>
# @license Apache 2.0
# @copyright Copyright 2020 <NAME>. <https://github.com/Jinzulen>
###
HTTPS = require "https"
Cache = require "./EmojiCache"
exports.GrabCategories = () ->
if !Cache.getCache "/Categories"
this.contactAPI "https://emoji.gg/api/?request=categories", (Error, Data) ->
if Error
throw Error
exports.contactAPI = (Endpoint, Callback) ->
try
Stores = {
"https://emoji.gg/api/": "/Emoji",
"https://emoji.gg/api/packs": "/Packs",
"https://emoji.gg/api/?request=stats": "/Stats",
"https://emoji.gg/api/?request=categories": "/Categories"
}
Key = Cache.getCache Stores[Endpoint]
if !Key
HTTPS.get Endpoint, (Response) ->
Error = ""
rawData = ""
Code = Response.statusCode
Type = Response.headers["content-type"]
if Code != 200
Error = "# [DEmojiJS] Could not issue request @ " + Endpoint
if Error
Response.resume()
Callback Error
Response.setEncoding "utf8"
Response.on "data", (Buffer) ->
rawData += JSON.parse JSON.stringify Buffer
Response.on "end", () ->
try
Data = rawData
Cache.setCache Stores[Endpoint], Data
catch E
throw E
Callback Error, JSON.parse Data
else
Callback null, JSON.parse Key
catch E
throw E
| true | ###
# @author PI:NAME:<NAME>END_PI
# @license Apache 2.0
# @copyright Copyright 2020 PI:NAME:<NAME>END_PI. <https://github.com/Jinzulen>
###
HTTPS = require "https"
Cache = require "./EmojiCache"
exports.GrabCategories = () ->
if !Cache.getCache "/Categories"
this.contactAPI "https://emoji.gg/api/?request=categories", (Error, Data) ->
if Error
throw Error
exports.contactAPI = (Endpoint, Callback) ->
try
Stores = {
"https://emoji.gg/api/": "/Emoji",
"https://emoji.gg/api/packs": "/Packs",
"https://emoji.gg/api/?request=stats": "/Stats",
"https://emoji.gg/api/?request=categories": "/Categories"
}
Key = Cache.getCache Stores[Endpoint]
if !Key
HTTPS.get Endpoint, (Response) ->
Error = ""
rawData = ""
Code = Response.statusCode
Type = Response.headers["content-type"]
if Code != 200
Error = "# [DEmojiJS] Could not issue request @ " + Endpoint
if Error
Response.resume()
Callback Error
Response.setEncoding "utf8"
Response.on "data", (Buffer) ->
rawData += JSON.parse JSON.stringify Buffer
Response.on "end", () ->
try
Data = rawData
Cache.setCache Stores[Endpoint], Data
catch E
throw E
Callback Error, JSON.parse Data
else
Callback null, JSON.parse Key
catch E
throw E
|
[
{
"context": "\n }\n auth.login(server, {username: \"Viewer\", password:\"password\"}, 200, \n (res)->",
"end": 906,
"score": 0.7239108085632324,
"start": 900,
"tag": "USERNAME",
"value": "Viewer"
},
{
"context": "auth.login(server, {username: \"Viewer\", pas... | test/services_tests/test_permission_viewer_services.coffee | ureport-web/ureport-s | 3 | #load application models
server = require('../../app')
_ = require('underscore');
invTest = require('../api_objects/investigated_test_api_object')
assignment = require('../api_objects/assignment_api_object')
dashboard = require('../api_objects/dashboard_api_object')
setting = require('../api_objects/setting_api_object')
build = require('../api_objects/build_api_object')
auth = require('../api_objects/auth_api_object')
user_api = require('../api_objects/user_api_object')
mongoose = require('mongoose')
chai = require('chai')
chaiHttp = require('chai-http')
moment = require('moment')
should = chai.should()
chai.use chaiHttp
describe 'User with Viewer permission', ->
existInvestigatedTest = undefined;
cookies = undefined;
before (done) ->
payload = {
product: 'SeedProductPermission',
type: "UI"
}
auth.login(server, {username: "Viewer", password:"password"}, 200,
(res)->
cookies = res.headers['set-cookie'].pop().split(';')[0];
done()
)
return
#investigated test
describe 'should not ', ->
it 'create new outage', (done) ->
payload={
pattern: '^\s*Nullpointer exception\s*$',
search_type: 'regex',
caused_by: 'System Error',
tracking: {
'number' : 'JIRA-2234'
},
exceptions: [
'TEST2234', 'TEST2235'
],
impact_test:{
fail: 6,
skip: 4,
warning: 0
}
}
build.addOutage(server, cookies,
"NONE",
payload,
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'create new investigated test', (done) ->
payload = {
uid: 'AAA12345',
product: "GreatProject",
type: "API",
failure: {
message: "some message",
token: "AA_AA",
stack_trace: "trace"
},
tracking: {
'number' : 'JIRA-2234'
}
}
invTest.create(server, cookies, payload, 403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update investigated test', (done) ->
payload = {
# _id: existInvestigatedTest._id
uid: 'AAA12345',
product: "SeedProductUpdate",
type: "API",
failure: {
message: "some updated message",
token: "AA_AA",
stack_trace: "trace"
}
}
invTest.create(server, cookies, payload, 403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'delete investigated test', (done) ->
invTest.delete(server, cookies, "111", 403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
#settings
describe 'should not', ->
it 'create a new setting', (done) ->
payload = {
'product' : 'TestProductData',
'type' : 'API'
}
setting.create(server, cookies,
payload,
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update setting', (done) ->
setting.update(server, cookies,
"NONE", {},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'delete setting', (done) ->
setting.delete(server, cookies,
"NONE",
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
#dashboard
describe 'should not', ->
it 'create a new dashboard', (done) ->
payload = {
"user": "5c6e06d76525937d6d7389ef",
"name": "my dashboard EEEEE",
"widgets": [{
"name": "someName",
"type": "asdfasdfasdf",
"cols": 1, "rows": 1, "y": 11, "x": 8, "dragEnabled": false, "resizeEnabled": false,
"pattern": {
"status": {
"all": true,
"rerun": false,
"pass": false,
"fail": false,
"skip": false,
"ki": false
},
"relations" : {},
},
"status": {"name" : "AAAAA"}
}]
}
dashboard.create(server, cookies,
payload,
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update dashboard', (done) ->
dashboard.update(server, cookies,
"NONE", { user : "5c6e06d76525937d6d7389ef"},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update widget dashboard', (done) ->
dashboard.updateWidget(server, cookies,
"NONE", { user : "5c6e06d76525937d6d7389ef"},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'delete dashboard', (done) ->
dashboard.delete(server, cookies,
"NONE",{ user : "5c6e06d76525937d6d7389ef"},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
#assignemnts
describe 'should not', ->
it 'create a new assignment', (done) ->
payload = {
'product' : 'TestProductData',
'type' : 'API',
'user' : '5c6e06d76525937d6d7389ef',
'username' : 'TESTAAAA',
'uid' : '1245',
'failure': {
'reason': '1111',
'stackTrace': 'this is a stack trace',
'token': 'AAAA'
}
}
assignment.create(server, cookies,
payload,
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update assignment', (done) ->
assignment.unassign(server, cookies,
"NONE", {},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'delete assignment', (done) ->
assignment.delete(server, cookies,
"NONE",
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
#perefernce
describe 'should not', ->
operator = null
before (done) ->
auth.login(server, {username: "admin@test.com", password:"password"}, 200,
(res)->
# login as admin to get a id of operator
user_api.search(server,res.headers['set-cookie'].pop().split(';')[0],{username:"test@test.com"},200,
(res) ->
operator = res.body[0]
done()
)
)
return
it 'update other user preference - theme', (done) ->
payload = {
"user" : operator._id,
"theme" : {
"111": "aaa",
"2222": "bbb"
}
}
user_api.updatePreference(server, cookies,
payload,
403,
'theme',
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update other user preference - language', (done) ->
payload = {
"user" : operator._id,
"language" : 'en'
}
user_api.updatePreference(server, cookies,
payload,
403,
'language',
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update other user preference - report', (done) ->
payload = {
"user" : operator._id,
"language" : 'en'
}
user_api.updatePreference(server, cookies,
payload,
403,
'report',
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update other user preference - dashboard', (done) ->
payload = {
"user" : operator._id,
"report" : 'en'
}
user_api.updatePreference(server, cookies,
payload,
403,
'dashboard',
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
#builds
describe 'should not', ->
existbuild = undefined;
existbuildWithCommentAndOutage = undefined;
before (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "UpdateProduct" },
{ "product" : "UpdateCommentAndOutage" }
],
"type" : [
{ "type" : "API" }
],
"team" : [
{ "team" : "UpdateTeam" }
],
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
#only two builds should be returned
if(res.body[0].product == 'UpdateProduct')
existbuild = res.body[0]
existbuildWithCommentAndOutage = res.body[1]
else
existbuild = res.body[1]
existbuildWithCommentAndOutage = res.body[0]
done()
)
return
it 'update a build parameter', (done) ->
date = new Date("2015-03-25T12:00:00.000Z")
build.update(server,cookies,
existbuild._id,
{
device: 'update device',
start_time: date,
end_time: date
owner: 'Tester'
},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update a build pass status', (done) ->
build.updateStatus(server,cookies,
existbuild._id,
{
pass: 18,
fail: undefined,
skip: "4",
warning: null
},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update a build status', (done) ->
build.updateStatus(server,cookies,
existbuild._id,
{
pass: 8,
fail: 2,
skip: 4,
warning: 0
},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update a build comments', (done) ->
build.update(server,cookies,
existbuildWithCommentAndOutage._id,
{
comments: [{
user: 'Update user',
message: 'this is just a updated message.',
time: moment().add(4, 'hour').format()
},{
user: 'Update user',
message: 'this is just another updated message.',
time: moment().add(4, 'hour').format()
}]
},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return | 69868 | #load application models
server = require('../../app')
_ = require('underscore');
invTest = require('../api_objects/investigated_test_api_object')
assignment = require('../api_objects/assignment_api_object')
dashboard = require('../api_objects/dashboard_api_object')
setting = require('../api_objects/setting_api_object')
build = require('../api_objects/build_api_object')
auth = require('../api_objects/auth_api_object')
user_api = require('../api_objects/user_api_object')
mongoose = require('mongoose')
chai = require('chai')
chaiHttp = require('chai-http')
moment = require('moment')
should = chai.should()
chai.use chaiHttp
describe 'User with Viewer permission', ->
existInvestigatedTest = undefined;
cookies = undefined;
before (done) ->
payload = {
product: 'SeedProductPermission',
type: "UI"
}
auth.login(server, {username: "Viewer", password:"<PASSWORD>"}, 200,
(res)->
cookies = res.headers['set-cookie'].pop().split(';')[0];
done()
)
return
#investigated test
describe 'should not ', ->
it 'create new outage', (done) ->
payload={
pattern: '^\s*Nullpointer exception\s*$',
search_type: 'regex',
caused_by: 'System Error',
tracking: {
'number' : 'JIRA-2234'
},
exceptions: [
'TEST2234', 'TEST2235'
],
impact_test:{
fail: 6,
skip: 4,
warning: 0
}
}
build.addOutage(server, cookies,
"NONE",
payload,
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'create new investigated test', (done) ->
payload = {
uid: 'AAA12345',
product: "GreatProject",
type: "API",
failure: {
message: "some message",
token: "<KEY>",
stack_trace: "trace"
},
tracking: {
'number' : 'JIRA-2234'
}
}
invTest.create(server, cookies, payload, 403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update investigated test', (done) ->
payload = {
# _id: existInvestigatedTest._id
uid: 'AAA12345',
product: "SeedProductUpdate",
type: "API",
failure: {
message: "some updated message",
token: "<KEY>",
stack_trace: "trace"
}
}
invTest.create(server, cookies, payload, 403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'delete investigated test', (done) ->
invTest.delete(server, cookies, "111", 403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
#settings
describe 'should not', ->
it 'create a new setting', (done) ->
payload = {
'product' : 'TestProductData',
'type' : 'API'
}
setting.create(server, cookies,
payload,
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update setting', (done) ->
setting.update(server, cookies,
"NONE", {},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'delete setting', (done) ->
setting.delete(server, cookies,
"NONE",
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
#dashboard
describe 'should not', ->
it 'create a new dashboard', (done) ->
payload = {
"user": "5<PASSWORD>",
"name": "my dashboard EEEEE",
"widgets": [{
"name": "someName",
"type": "asdfasdfasdf",
"cols": 1, "rows": 1, "y": 11, "x": 8, "dragEnabled": false, "resizeEnabled": false,
"pattern": {
"status": {
"all": true,
"rerun": false,
"pass": false,
"fail": false,
"skip": false,
"ki": false
},
"relations" : {},
},
"status": {"name" : "AAAAA"}
}]
}
dashboard.create(server, cookies,
payload,
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update dashboard', (done) ->
dashboard.update(server, cookies,
"NONE", { user : "5<PASSWORD>"},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update widget dashboard', (done) ->
dashboard.updateWidget(server, cookies,
"NONE", { user : "5<PASSWORD>"},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'delete dashboard', (done) ->
dashboard.delete(server, cookies,
"NONE",{ user : "5<PASSWORD>"},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
#assignemnts
describe 'should not', ->
it 'create a new assignment', (done) ->
payload = {
'product' : 'TestProductData',
'type' : 'API',
'user' : '5c6e06d76525937d6d7389ef',
'username' : 'TESTAAAA',
'uid' : '1245',
'failure': {
'reason': '1111',
'stackTrace': 'this is a stack trace',
'token': '<KEY>'
}
}
assignment.create(server, cookies,
payload,
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update assignment', (done) ->
assignment.unassign(server, cookies,
"NONE", {},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'delete assignment', (done) ->
assignment.delete(server, cookies,
"NONE",
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
#perefernce
describe 'should not', ->
operator = null
before (done) ->
auth.login(server, {username: "<EMAIL>", password:"<PASSWORD>"}, 200,
(res)->
# login as admin to get a id of operator
user_api.search(server,res.headers['set-cookie'].pop().split(';')[0],{username:"<EMAIL>"},200,
(res) ->
operator = res.body[0]
done()
)
)
return
it 'update other user preference - theme', (done) ->
payload = {
"user" : operator._id,
"theme" : {
"111": "aaa",
"2222": "bbb"
}
}
user_api.updatePreference(server, cookies,
payload,
403,
'theme',
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update other user preference - language', (done) ->
payload = {
"user" : operator._id,
"language" : 'en'
}
user_api.updatePreference(server, cookies,
payload,
403,
'language',
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update other user preference - report', (done) ->
payload = {
"user" : operator._id,
"language" : 'en'
}
user_api.updatePreference(server, cookies,
payload,
403,
'report',
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update other user preference - dashboard', (done) ->
payload = {
"user" : operator._id,
"report" : 'en'
}
user_api.updatePreference(server, cookies,
payload,
403,
'dashboard',
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
#builds
describe 'should not', ->
existbuild = undefined;
existbuildWithCommentAndOutage = undefined;
before (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "UpdateProduct" },
{ "product" : "UpdateCommentAndOutage" }
],
"type" : [
{ "type" : "API" }
],
"team" : [
{ "team" : "UpdateTeam" }
],
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
#only two builds should be returned
if(res.body[0].product == 'UpdateProduct')
existbuild = res.body[0]
existbuildWithCommentAndOutage = res.body[1]
else
existbuild = res.body[1]
existbuildWithCommentAndOutage = res.body[0]
done()
)
return
it 'update a build parameter', (done) ->
date = new Date("2015-03-25T12:00:00.000Z")
build.update(server,cookies,
existbuild._id,
{
device: 'update device',
start_time: date,
end_time: date
owner: 'Tester'
},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update a build pass status', (done) ->
build.updateStatus(server,cookies,
existbuild._id,
{
pass: 18,
fail: undefined,
skip: "4",
warning: null
},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update a build status', (done) ->
build.updateStatus(server,cookies,
existbuild._id,
{
pass: 8,
fail: 2,
skip: 4,
warning: 0
},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update a build comments', (done) ->
build.update(server,cookies,
existbuildWithCommentAndOutage._id,
{
comments: [{
user: 'Update user',
message: 'this is just a updated message.',
time: moment().add(4, 'hour').format()
},{
user: 'Update user',
message: 'this is just another updated message.',
time: moment().add(4, 'hour').format()
}]
},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return | true | #load application models
server = require('../../app')
_ = require('underscore');
invTest = require('../api_objects/investigated_test_api_object')
assignment = require('../api_objects/assignment_api_object')
dashboard = require('../api_objects/dashboard_api_object')
setting = require('../api_objects/setting_api_object')
build = require('../api_objects/build_api_object')
auth = require('../api_objects/auth_api_object')
user_api = require('../api_objects/user_api_object')
mongoose = require('mongoose')
chai = require('chai')
chaiHttp = require('chai-http')
moment = require('moment')
should = chai.should()
chai.use chaiHttp
describe 'User with Viewer permission', ->
existInvestigatedTest = undefined;
cookies = undefined;
before (done) ->
payload = {
product: 'SeedProductPermission',
type: "UI"
}
auth.login(server, {username: "Viewer", password:"PI:PASSWORD:<PASSWORD>END_PI"}, 200,
(res)->
cookies = res.headers['set-cookie'].pop().split(';')[0];
done()
)
return
#investigated test
describe 'should not ', ->
it 'create new outage', (done) ->
payload={
pattern: '^\s*Nullpointer exception\s*$',
search_type: 'regex',
caused_by: 'System Error',
tracking: {
'number' : 'JIRA-2234'
},
exceptions: [
'TEST2234', 'TEST2235'
],
impact_test:{
fail: 6,
skip: 4,
warning: 0
}
}
build.addOutage(server, cookies,
"NONE",
payload,
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'create new investigated test', (done) ->
payload = {
uid: 'AAA12345',
product: "GreatProject",
type: "API",
failure: {
message: "some message",
token: "PI:KEY:<KEY>END_PI",
stack_trace: "trace"
},
tracking: {
'number' : 'JIRA-2234'
}
}
invTest.create(server, cookies, payload, 403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update investigated test', (done) ->
payload = {
# _id: existInvestigatedTest._id
uid: 'AAA12345',
product: "SeedProductUpdate",
type: "API",
failure: {
message: "some updated message",
token: "PI:KEY:<KEY>END_PI",
stack_trace: "trace"
}
}
invTest.create(server, cookies, payload, 403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'delete investigated test', (done) ->
invTest.delete(server, cookies, "111", 403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
#settings
describe 'should not', ->
it 'create a new setting', (done) ->
payload = {
'product' : 'TestProductData',
'type' : 'API'
}
setting.create(server, cookies,
payload,
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update setting', (done) ->
setting.update(server, cookies,
"NONE", {},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'delete setting', (done) ->
setting.delete(server, cookies,
"NONE",
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
#dashboard
describe 'should not', ->
it 'create a new dashboard', (done) ->
payload = {
"user": "5PI:PASSWORD:<PASSWORD>END_PI",
"name": "my dashboard EEEEE",
"widgets": [{
"name": "someName",
"type": "asdfasdfasdf",
"cols": 1, "rows": 1, "y": 11, "x": 8, "dragEnabled": false, "resizeEnabled": false,
"pattern": {
"status": {
"all": true,
"rerun": false,
"pass": false,
"fail": false,
"skip": false,
"ki": false
},
"relations" : {},
},
"status": {"name" : "AAAAA"}
}]
}
dashboard.create(server, cookies,
payload,
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update dashboard', (done) ->
dashboard.update(server, cookies,
"NONE", { user : "5PI:PASSWORD:<PASSWORD>END_PI"},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update widget dashboard', (done) ->
dashboard.updateWidget(server, cookies,
"NONE", { user : "5PI:PASSWORD:<PASSWORD>END_PI"},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'delete dashboard', (done) ->
dashboard.delete(server, cookies,
"NONE",{ user : "5PI:PASSWORD:<PASSWORD>END_PI"},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
#assignemnts
describe 'should not', ->
it 'create a new assignment', (done) ->
payload = {
'product' : 'TestProductData',
'type' : 'API',
'user' : '5c6e06d76525937d6d7389ef',
'username' : 'TESTAAAA',
'uid' : '1245',
'failure': {
'reason': '1111',
'stackTrace': 'this is a stack trace',
'token': 'PI:KEY:<KEY>END_PI'
}
}
assignment.create(server, cookies,
payload,
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update assignment', (done) ->
assignment.unassign(server, cookies,
"NONE", {},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'delete assignment', (done) ->
assignment.delete(server, cookies,
"NONE",
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
#perefernce
describe 'should not', ->
operator = null
before (done) ->
auth.login(server, {username: "PI:EMAIL:<EMAIL>END_PI", password:"PI:PASSWORD:<PASSWORD>END_PI"}, 200,
(res)->
# login as admin to get a id of operator
user_api.search(server,res.headers['set-cookie'].pop().split(';')[0],{username:"PI:EMAIL:<EMAIL>END_PI"},200,
(res) ->
operator = res.body[0]
done()
)
)
return
it 'update other user preference - theme', (done) ->
payload = {
"user" : operator._id,
"theme" : {
"111": "aaa",
"2222": "bbb"
}
}
user_api.updatePreference(server, cookies,
payload,
403,
'theme',
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update other user preference - language', (done) ->
payload = {
"user" : operator._id,
"language" : 'en'
}
user_api.updatePreference(server, cookies,
payload,
403,
'language',
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update other user preference - report', (done) ->
payload = {
"user" : operator._id,
"language" : 'en'
}
user_api.updatePreference(server, cookies,
payload,
403,
'report',
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update other user preference - dashboard', (done) ->
payload = {
"user" : operator._id,
"report" : 'en'
}
user_api.updatePreference(server, cookies,
payload,
403,
'dashboard',
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
#builds
describe 'should not', ->
existbuild = undefined;
existbuildWithCommentAndOutage = undefined;
before (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "UpdateProduct" },
{ "product" : "UpdateCommentAndOutage" }
],
"type" : [
{ "type" : "API" }
],
"team" : [
{ "team" : "UpdateTeam" }
],
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
#only two builds should be returned
if(res.body[0].product == 'UpdateProduct')
existbuild = res.body[0]
existbuildWithCommentAndOutage = res.body[1]
else
existbuild = res.body[1]
existbuildWithCommentAndOutage = res.body[0]
done()
)
return
it 'update a build parameter', (done) ->
date = new Date("2015-03-25T12:00:00.000Z")
build.update(server,cookies,
existbuild._id,
{
device: 'update device',
start_time: date,
end_time: date
owner: 'Tester'
},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update a build pass status', (done) ->
build.updateStatus(server,cookies,
existbuild._id,
{
pass: 18,
fail: undefined,
skip: "4",
warning: null
},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update a build status', (done) ->
build.updateStatus(server,cookies,
existbuild._id,
{
pass: 8,
fail: 2,
skip: 4,
warning: 0
},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return
it 'update a build comments', (done) ->
build.update(server,cookies,
existbuildWithCommentAndOutage._id,
{
comments: [{
user: 'Update user',
message: 'this is just a updated message.',
time: moment().add(4, 'hour').format()
},{
user: 'Update user',
message: 'this is just another updated message.',
time: moment().add(4, 'hour').format()
}]
},
403,
(res) ->
res.body.error.should.equal "You don't have permission to perform this action"
done()
)
return |
[
{
"context": "ported\n beforeEach -> @clever = Clever {token: 'DEMO_TOKEN'}\n\n it 'can get Events', (done)->\n @clever.Ev",
"end": 285,
"score": 0.9343662261962891,
"start": 275,
"tag": "PASSWORD",
"value": "DEMO_TOKEN"
}
] | test/events.coffee | Clever/clever-js | 10 | assert = require 'assert'
_ = require 'underscore'
Clever = require "#{__dirname}/../index"
##
# Tests the Events functionality
##
describe '/events endpoint', ->
# Build Clever API tool, only Tokens are supported
beforeEach -> @clever = Clever {token: 'DEMO_TOKEN'}
it 'can get Events', (done)->
@clever.Event.find().limit(1).exec (err, events)->
assert _.isArray(events), "Expected returned events to be an array, got #{typeof events} = #{JSON.stringify events}"
#assert.equal events.length, 1
done()
| 108883 | assert = require 'assert'
_ = require 'underscore'
Clever = require "#{__dirname}/../index"
##
# Tests the Events functionality
##
describe '/events endpoint', ->
# Build Clever API tool, only Tokens are supported
beforeEach -> @clever = Clever {token: '<PASSWORD>'}
it 'can get Events', (done)->
@clever.Event.find().limit(1).exec (err, events)->
assert _.isArray(events), "Expected returned events to be an array, got #{typeof events} = #{JSON.stringify events}"
#assert.equal events.length, 1
done()
| true | assert = require 'assert'
_ = require 'underscore'
Clever = require "#{__dirname}/../index"
##
# Tests the Events functionality
##
describe '/events endpoint', ->
# Build Clever API tool, only Tokens are supported
beforeEach -> @clever = Clever {token: 'PI:PASSWORD:<PASSWORD>END_PI'}
it 'can get Events', (done)->
@clever.Event.find().limit(1).exec (err, events)->
assert _.isArray(events), "Expected returned events to be an array, got #{typeof events} = #{JSON.stringify events}"
#assert.equal events.length, 1
done()
|
[
{
"context": "nal notes required for the script>\n#\n# Author:\n# AJ Jordan <alex@strugee.net>\n\nresponses = ['yum!', '*catche",
"end": 259,
"score": 0.9998312592506409,
"start": 250,
"tag": "NAME",
"value": "AJ Jordan"
},
{
"context": "quired for the script>\n#\n# Author:\n# AJ... | src/botsnack.coffee | strugee/hubot-botsnack | 0 | # Description
# botsnack command implementation for Hubot
#
# Configuration:
# LIST_OF_ENV_VARS_TO_SET
#
# Commands:
# hubot botsnack - give the bot a snack for being good
#
# Notes:
# <optional notes required for the script>
#
# Author:
# AJ Jordan <alex@strugee.net>
responses = ['yum!', '*catches the botsnack in midair*']
module.exports = (robot) ->
robot.respond /botsnack/, (res) ->
res.reply res.random responses
| 66377 | # Description
# botsnack command implementation for Hubot
#
# Configuration:
# LIST_OF_ENV_VARS_TO_SET
#
# Commands:
# hubot botsnack - give the bot a snack for being good
#
# Notes:
# <optional notes required for the script>
#
# Author:
# <NAME> <<EMAIL>>
responses = ['yum!', '*catches the botsnack in midair*']
module.exports = (robot) ->
robot.respond /botsnack/, (res) ->
res.reply res.random responses
| true | # Description
# botsnack command implementation for Hubot
#
# Configuration:
# LIST_OF_ENV_VARS_TO_SET
#
# Commands:
# hubot botsnack - give the bot a snack for being good
#
# Notes:
# <optional notes required for the script>
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
responses = ['yum!', '*catches the botsnack in midair*']
module.exports = (robot) ->
robot.respond /botsnack/, (res) ->
res.reply res.random responses
|
[
{
"context": " = service.where(predicate)\n if refKey is 'product'\n request.staged(true)\n request.f",
"end": 28708,
"score": 0.5735903978347778,
"start": 28701,
"tag": "KEY",
"value": "product"
}
] | lib/product-import.coffee | sphereio/sphere-product-import | 5 | _ = require 'underscore'
_.mixin require 'underscore-mixins'
debug = require('debug')('sphere-product-import')
Mutex = require('await-mutex').default
Promise = require 'bluebird'
slugify = require 'underscore.string/slugify'
{SphereClient, ProductSync} = require 'sphere-node-sdk'
{Repeater} = require 'sphere-node-utils'
fs = require 'fs-extra'
path = require 'path'
{serializeError} = require 'serialize-error'
EnumValidator = require './enum-validator'
UnknownAttributesFilter = require './unknown-attributes-filter'
CommonUtils = require './common-utils'
EnsureDefaultAttributes = require './ensure-default-attributes'
util = require 'util'
Reassignment = require('commercetools-node-variant-reassignment').default
class ProductImport
constructor: (@logger, options = {}) ->
@sync = new ProductSync
if options.blackList and ProductSync.actionGroups
@sync.config @_configureSync(options.blackList)
@errorCallback = options.errorCallback or @_errorLogger
@beforeCreateCallback = options.beforeCreateCallback or Promise.resolve
@beforeUpdateCallback = options.beforeUpdateCallback or Promise.resolve
@ensureEnums = options.ensureEnums or false
@filterUnknownAttributes = options.filterUnknownAttributes or false
@ignoreSlugUpdates = options.ignoreSlugUpdates or false
@batchSize = options.batchSize or 30
@failOnDuplicateAttr = options.failOnDuplicateAttr or false
@logOnDuplicateAttr = if options.logOnDuplicateAttr? then options.logOnDuplicateAttr else true
@commonUtils = new CommonUtils @logger
@client = new SphereClient @commonUtils.extendUserAgent options.clientConfig
@enumValidator = new EnumValidator @logger
@unknownAttributesFilter = new UnknownAttributesFilter @logger
@filterActions = if _.isFunction(options.filterActions)
options.filterActions
else if _.isArray(options.filterActions)
(action) -> !_.contains(options.filterActions, action.action)
else
(action) -> true
# default web server url limit in bytes
# count starts after protocol (eg. https:// does not count)
@urlLimit = 8192
if options.defaultAttributes
@defaultAttributesService = new EnsureDefaultAttributes @logger, options.defaultAttributes
# possible values:
# always, publishedOnly, stagedAndPublishedOnly
@publishingStrategy = options.publishingStrategy or false
@matchVariantsByAttr = options.matchVariantsByAttr or undefined
@variantReassignmentOptions = options.variantReassignmentOptions or {}
if @variantReassignmentOptions.enabled
@reassignmentLock = new Mutex()
@reassignmentTriggerActions = ['removeVariant']
@reassignmentService = new Reassignment(@client, @logger,
(error) => @_handleErrorResponse(error),
@variantReassignmentOptions.retainExistingData,
@variantReassignmentOptions.allowedLocales)
@_configErrorHandling(options)
@_resetCache()
@_resetSummary()
debug "Product Importer initialized with config -> errorDir: #{@errorDir}, errorLimit: #{@errorLimit}, blacklist actions: #{options.blackList}, ensureEnums: #{@ensureEnums}"
_configureSync: (blackList) =>
@_validateSyncConfig(blackList)
debug "Product sync config validated"
_.difference(ProductSync.actionGroups, blackList)
.map (type) -> {type: type, group: 'white'}
.concat(blackList.map (type) -> {type: type, group: 'black'})
_validateSyncConfig: (blackList) ->
for actionGroup in blackList
if not _.contains(ProductSync.actionGroups, actionGroup)
throw ("invalid product sync action group: #{actionGroup}")
_configErrorHandling: (options) =>
if options.errorDir
@errorDir = options.errorDir
else
@errorDir = path.join(__dirname,'../errors')
fs.emptyDirSync(@errorDir)
if options.errorLimit
@errorLimit = options.errorLimit
else
@errorLimit = 30
_resetCache: ->
@_cache =
productType: {}
categories: {}
taxCategory: {}
_resetSummary: ->
@_summary =
productsWithMissingSKU: 0
created: 0
updated: 0
failed: 0
productTypeUpdated: 0
errorDir: @errorDir
if @filterUnknownAttributes then @_summary.unknownAttributeNames = []
if @variantReassignmentOptions.enabled
@_summary.variantReassignment = null
@reassignmentService._resetStats()
summaryReport: (filename) ->
message = "Summary: there were #{@_summary.created + @_summary.updated} imported products " +
"(#{@_summary.created} were new and #{@_summary.updated} were updates)."
if @_summary.productsWithMissingSKU > 0
message += "\nFound #{@_summary.productsWithMissingSKU} product(s) which do not have SKU and won't be imported."
message += " '#{filename}'" if filename
if @_summary.failed > 0
message += "\n #{@_summary.failed} product imports failed. Error reports stored at: #{@errorDir}"
report = {
reportMessage: message
detailedSummary: @_summary
}
report
_filterOutProductsBySkus: (products, blacklistSkus) ->
return products.filter (product) =>
variants = product.variants.concat(product.masterVariant)
variantSkus = variants.map (v) -> v.sku
# check if at least one SKU from product is in the blacklist
isProductBlacklisted = variantSkus.find (sku) ->
blacklistSkus.indexOf(sku) >= 0
# filter only products which are NOT blacklisted
not isProductBlacklisted
performStream: (chunk, cb) ->
@_processBatches(chunk).then -> cb()
_processBatches: (products) ->
batchedList = _.batchList(products, @batchSize) # max parallel elem to process
Promise.map batchedList, (productsToProcess) =>
debug 'Ensuring existence of product type in memory.'
@_ensureProductTypesInMemory(productsToProcess)
.then =>
if @ensureEnums
debug 'Ensuring existence of enum keys in product type.'
enumUpdateActions = @_validateEnums(productsToProcess)
uniqueEnumUpdateActions = @_filterUniqueUpdateActions(enumUpdateActions)
@_updateProductType(uniqueEnumUpdateActions)
.then =>
# filter out products which do not have SKUs on all variants
originalLength = productsToProcess.length
productsToProcess = productsToProcess.filter(@_doesProductHaveSkus)
filteredProductsLength = originalLength - productsToProcess.length
# if there are some products which do not have SKU
if filteredProductsLength
@logger.warn "Filtering out #{filteredProductsLength} product(s) which do not have SKU"
@_summary.productsWithMissingSKU += filteredProductsLength
.then () =>
@_getExistingProductsForSkus(@_extractUniqueSkus(productsToProcess))
.then (queriedEntries) =>
if @defaultAttributesService
debug 'Ensuring default attributes'
@_ensureDefaultAttributesInProducts(productsToProcess, queriedEntries)
.then ->
queriedEntries
else
queriedEntries
.then (queriedEntries) =>
@_createOrUpdate productsToProcess, queriedEntries
.then (results) =>
_.each results, (r) =>
if r.isFulfilled()
@_handleFulfilledResponse(r)
else if r.isRejected()
@_handleErrorResponse(r.reason())
Promise.resolve(@_summary)
, { concurrency: 1 } # run 1 batch at a time
.tap =>
if @variantReassignmentOptions.enabled
@_summary.variantReassignment = @reassignmentService.statistics
_getWhereQueryLimit: ->
client = @client.productProjections
.where('a')
.staged(true)
url = _.clone(@client.productProjections._rest._options.uri)
url = url.replace(/.*?:\/\//g, "")
url += @client.productProjections._currentEndpoint
url += "?" + @client.productProjections._queryString()
@client.productProjections._setDefaults()
# subtract 1 since we added 'a' as the where query
return @urlLimit - Buffer.byteLength((url),'utf-8') - 1
_getExistingProductsForSkus: (skus) =>
new Promise (resolve, reject) =>
if skus.length == 0
return resolve([])
skuChunks = @commonUtils._separateSkusChunksIntoSmallerChunks(
skus,
@_getWhereQueryLimit()
)
Promise.map(skuChunks, (skus) =>
predicate = @_createProductFetchBySkuQueryPredicate(skus)
@client.productProjections
.where(predicate)
.staged(true)
.perPage(200)
.all()
.fetch()
.then (res) ->
res.body.results
, { concurrency: 30 })
.then (results) ->
debug 'Fetched products: %j', results
uniqueProducts = _.uniq(_.compact(_.flatten(results)), (product) -> product.id)
resolve(uniqueProducts)
.catch (err) -> reject(err)
_errorLogger: (res, logger) =>
if @_summary.failed < @errorLimit or @errorLimit is 0
logger.error(util.inspect(res, false, 20, false), "Skipping product due to an error")
else if !@errorLimitHasBeenCommunicated
@errorLimitHasBeenCommunicated = true
logger.warn "
Error not logged as error limit of #{@errorLimit} has reached.
"
_handleErrorResponse: (error) =>
error = serializeError error
@_summary.failed++
if @errorDir
errorFile = path.join(@errorDir, "error-#{@_summary.failed}.json")
fs.outputJsonSync(errorFile, error, {spaces: 2})
if _.isFunction(@errorCallback)
@errorCallback(error, @logger)
else
@logger.error "Error callback has to be a function!"
_handleFulfilledResponse: (res) =>
switch res.value()?.statusCode
when 201 then @_summary.created++
when 200 then @_summary.updated++
_createProductFetchBySkuQueryPredicate: (skus) ->
skuString = "sku in (#{skus.map((val) -> JSON.stringify(val))})"
"masterVariant(#{skuString}) or variants(#{skuString})"
_doesProductHaveSkus: (product) ->
if product.masterVariant and not product.masterVariant.sku
return false
if product.variants?.length
for variant in product.variants
if not variant.sku
return false
true
_extractUniqueSkus: (products) ->
skus = []
for product in products
if product.masterVariant?.sku
skus.push(product.masterVariant.sku)
if product.variants?.length
for variant in product.variants
if variant.sku
skus.push(variant.sku)
return _.uniq(skus,false)
_getProductsMatchingByProductSkus: (prodToProcess, existingProducts) ->
prodToProcessSkus = @_extractUniqueSkus([prodToProcess])
_.filter existingProducts, (existingEntry) =>
existingProductSkus = @_extractUniqueSkus([existingEntry])
matchingSkus = _.intersection(prodToProcessSkus,existingProductSkus)
matchingSkus.length > 0
_updateProductRepeater: (prodToProcess, existingProducts, reassignmentRetries) ->
repeater = new Repeater {attempts: 5}
repeater.execute =>
@_updateProduct(prodToProcess, existingProducts, false, reassignmentRetries)
, (e) =>
if e.statusCode isnt 409 # concurrent modification
return Promise.reject e
@logger.warn "Recovering from 409 concurrentModification error on product '#{existingProducts[0].id}'"
Promise.resolve => # next task must be a function
@client.productProjections.staged(true).byId(existingProducts[0].id).fetch()
.then (result) =>
@_updateProduct(prodToProcess, [result.body], true, reassignmentRetries)
_getProductTypeIdByName: (name) ->
@_resolveReference(@client.productTypes, 'productType', { id: name }, "name=\"#{name}\"")
_runReassignmentForProduct: (product) ->
@logger.info(
"Running reassignment for a product with masterVariant.sku \"#{product.masterVariant.sku}\" - locking"
)
@reassignmentLock.lock()
.then (unlock) =>
@reassignmentService.execute([product], @_cache.productType)
.finally =>
@logger.info(
"Finished reassignment for a product with masterVariant.sku \"#{product.masterVariant.sku}\" - unlocking"
)
unlock()
_runReassignmentBeforeCreateOrUpdate: (product, reassignmentRetries = 0) ->
if reassignmentRetries > 5
masterSku = product.masterVariant.sku
return Promise.reject(
new Error("Error - too many reassignment retries for a product with masterVariant.sku \"#{masterSku}\"")
)
@_runReassignmentForProduct product
.then((res) =>
# if the product which failed during reassignment, remove it from processing
if(res.badRequestSKUs.length)
@logger.error(
"Removing product with SKUs \"#{res.badRequestSKUs}\" from processing due to a reassignment error"
)
return
# run createOrUpdate again the original prodToProcess object
@_createOrUpdateProduct(product, null, ++reassignmentRetries)
)
_updateProduct: (prodToProcess, existingProducts, productIsPrepared, reassignmentRetries) ->
existingProduct = existingProducts[0]
Promise.all([
@_fetchSameForAllAttributesOfProductType(prodToProcess.productType),
if productIsPrepared then prodToProcess else @_prepareUpdateProduct(prodToProcess, existingProduct),
@_getProductTypeIdByName(prodToProcess.productType.id)
])
.then ([sameForAllAttributes, preparedProduct, newProductTypeId]) =>
synced = @sync.buildActions(preparedProduct, existingProduct, sameForAllAttributes, @matchVariantsByAttr)
.filterActions (action) =>
@filterActions(action, existingProduct, preparedProduct)
hasProductTypeChanged = newProductTypeId != existingProduct.productType.id
# do not proceed if there are no update actions
if not ((hasProductTypeChanged and @variantReassignmentOptions.enabled) or synced.shouldUpdate())
return Promise.resolve statusCode: 304
updateRequest = synced.getUpdatePayload()
updateId = synced.getUpdateId()
if @variantReassignmentOptions.enabled
# more than one existing product
shouldRunReassignment = existingProducts.length > 1 or
# or productType changed
hasProductTypeChanged or
# or there is some listed update action for reassignment
updateRequest.actions.find (action) =>
action.action in @reassignmentTriggerActions
if shouldRunReassignment
return @_runReassignmentBeforeCreateOrUpdate(prodToProcess, reassignmentRetries)
# if reassignment is off or if there are no actions which triggers reassignment, run normal update
return Promise.resolve(@beforeUpdateCallback(existingProducts, prodToProcess, updateRequest))
.then () =>
@_updateInBatches(updateId, updateRequest)
_updateInBatches: (id, updateRequest) ->
latestVersion = updateRequest.version
batchedActions = _.batchList(updateRequest.actions, 500) # max 500 actions per update request
Promise.mapSeries batchedActions, (actions) =>
request =
version: latestVersion
actions: actions
@client.products
.byId(id)
.update(request)
.tap (res) ->
latestVersion = res.body.version
.then _.last # return only the last result
_cleanVariantAttributes: (variant) ->
attributeMap = []
if _.isArray(variant.attributes)
variant.attributes = variant.attributes.filter (attribute) =>
isDuplicate = attributeMap.indexOf(attribute.name) >= 0
attributeMap.push(attribute.name)
if isDuplicate
msg = "Variant with SKU '#{variant.sku}' has duplicate attributes with name '#{attribute.name}'."
if @failOnDuplicateAttr
throw new Error(msg)
else if @logOnDuplicateAttr
@logger.warn msg
# filter out duplicate attributes
not isDuplicate
_cleanDuplicateAttributes: (prodToProcess) ->
prodToProcess.variants = prodToProcess.variants || []
@_cleanVariantAttributes prodToProcess.masterVariant
prodToProcess.variants.forEach (variant) =>
@_cleanVariantAttributes variant
_canErrorBeFixedByReassignment: (err) ->
# if at least one error has code DuplicateField with field containing SKU or SLUG
(err?.body?.errors or []).find (error) ->
error.code == 'DuplicateField' and (error.field.indexOf 'slug' >= 0 or error.field.indexOf 'sku' >= 0)
_createOrUpdateProduct: (prodToProcess, existingProducts, reassignmentRetries = 0) ->
Promise.resolve(existingProducts)
# if the existing products were not fetched, load them from API
.then (existingProducts) =>
existingProducts or @_getExistingProductsForSkus(@_extractUniqueSkus([prodToProcess]))
.then (existingProducts) =>
if existingProducts.length
@_updateProductRepeater(prodToProcess, existingProducts, reassignmentRetries)
else
@_prepareNewProduct(prodToProcess)
.then (product) =>
Promise.resolve(@beforeCreateCallback(product))
.then () -> product
.then (product) =>
@client.products.create(product)
.catch (err) =>
# if the error can be handled by reassignment and it is enabled
if reassignmentRetries <= 5 and @variantReassignmentOptions.enabled and @_canErrorBeFixedByReassignment(err)
@_runReassignmentBeforeCreateOrUpdate(prodToProcess, reassignmentRetries)
else
throw err
_createOrUpdate: (productsToProcess, existingProducts) ->
debug 'Products to process: %j', {toProcess: productsToProcess, existing: existingProducts}
posts = _.map productsToProcess, (product) =>
# will filter out duplicate attributes
@_filterAttributes(product)
.then (product) =>
# should be inside of a Promise because it throws error in case of duplicate fields
@_cleanDuplicateAttributes(product)
matchingExistingProducts = @_getProductsMatchingByProductSkus(product, existingProducts)
@_createOrUpdateProduct(product, matchingExistingProducts)
debug 'About to send %s requests', _.size(posts)
Promise.settle(posts)
_filterAttributes: (product) =>
new Promise (resolve) =>
if @filterUnknownAttributes
@unknownAttributesFilter.filter(@_cache.productType[product.productType.id],product, @_summary.unknownAttributeNames)
.then (filteredProduct) ->
resolve(filteredProduct)
else
resolve(product)
# updateActions are of the form:
# { productTypeId: [{updateAction},{updateAction},...],
# productTypeId: [{updateAction},{updateAction},...]
# }
_filterUniqueUpdateActions: (updateActions) =>
_.reduce _.keys(updateActions), (acc, productTypeId) =>
actions = updateActions[productTypeId]
uniqueActions = @commonUtils.uniqueObjectFilter actions
acc[productTypeId] = uniqueActions
acc
, {}
_ensureProductTypesInMemory: (products) =>
Promise.map products, (product) =>
@_ensureProductTypeInMemory(product.productType.id)
, {concurrency: 1}
_ensureDefaultAttributesInProducts: (products, queriedEntries) =>
if queriedEntries
queriedEntries = _.compact(queriedEntries)
Promise.map products, (product) =>
if queriedEntries?.length > 0
uniqueSkus = @_extractUniqueSkus([product])
productFromServer = _.find(queriedEntries, (entry) =>
serverUniqueSkus = @_extractUniqueSkus([entry])
intersection = _.intersection(uniqueSkus, serverUniqueSkus)
return _.compact(intersection).length > 0
)
@defaultAttributesService.ensureDefaultAttributesInProduct(product, productFromServer)
, {concurrency: 1}
_ensureProductTypeInMemory: (productTypeId) =>
if @_cache.productType[productTypeId]
Promise.resolve()
else
productType =
id: productTypeId
@_resolveReference(@client.productTypes, 'productType', productType, "name=\"#{productType?.id}\"")
_validateEnums: (products) =>
enumUpdateActions = {}
_.each products, (product) =>
updateActions = @enumValidator.validateProduct(product, @_cache.productType[product.productType.id])
if updateActions and _.size(updateActions.actions) > 0 then @_updateEnumUpdateActions(enumUpdateActions, updateActions)
enumUpdateActions
_updateProductType: (enumUpdateActions) =>
if _.isEmpty(enumUpdateActions)
Promise.resolve()
else
debug "Updating product type(s): #{_.keys(enumUpdateActions)}"
Promise.map _.keys(enumUpdateActions), (productTypeId) =>
updateRequest =
version: @_cache.productType[productTypeId].version
actions: enumUpdateActions[productTypeId]
@client.productTypes.byId(@_cache.productType[productTypeId].id).update(updateRequest)
.then (updatedProductType) =>
@_cache.productType[productTypeId] = updatedProductType.body
@_summary.productTypeUpdated++
_updateEnumUpdateActions: (enumUpdateActions, updateActions) ->
if enumUpdateActions[updateActions.productTypeId]
enumUpdateActions[updateActions.productTypeId] = enumUpdateActions[updateActions.productTypeId].concat(updateActions.actions)
else
enumUpdateActions[updateActions.productTypeId] = updateActions.actions
_fetchSameForAllAttributesOfProductType: (productType) =>
if @_cache.productType["#{productType.id}_sameForAllAttributes"]
Promise.resolve(@_cache.productType["#{productType.id}_sameForAllAttributes"])
else
@_resolveReference(@client.productTypes, 'productType', productType, "name=\"#{productType?.id}\"")
.then =>
sameValueAttributes = _.where(@_cache.productType[productType.id].attributes, {attributeConstraint: "SameForAll"})
sameValueAttributeNames = _.pluck(sameValueAttributes, 'name')
@_cache.productType["#{productType.id}_sameForAllAttributes"] = sameValueAttributeNames
Promise.resolve(sameValueAttributeNames)
_ensureVariantDefaults: (variant = {}) ->
variantDefaults =
attributes: []
prices: []
images: []
_.defaults(variant, variantDefaults)
_ensureDefaults: (product) =>
debug 'ensuring default fields in variants.'
_.defaults product,
masterVariant: @_ensureVariantDefaults(product.masterVariant)
variants: _.map product.variants, (variant) => @_ensureVariantDefaults(variant)
return product
_prepareUpdateProduct: (productToProcess, existingProduct) ->
productToProcess = @_ensureDefaults(productToProcess)
Promise.all [
@_resolveProductCategories(productToProcess.categories)
@_resolveReference(@client.taxCategories, 'taxCategory', productToProcess.taxCategory, "name=\"#{productToProcess.taxCategory?.id}\"")
@_fetchAndResolveCustomReferences(productToProcess)
]
.spread (prodCatsIds, taxCatId) =>
if taxCatId
productToProcess.taxCategory =
id: taxCatId
typeId: 'tax-category'
if prodCatsIds
productToProcess.categories = _.map prodCatsIds, (catId) ->
id: catId
typeId: 'category'
productToProcess.slug = @_updateProductSlug productToProcess, existingProduct
Promise.resolve productToProcess
_updateProductSlug: (productToProcess, existingProduct) =>
if @ignoreSlugUpdates
slug = existingProduct.slug
else if not productToProcess.slug
debug 'slug missing in product to process, assigning same as existing product: %s', existingProduct.slug
slug = existingProduct.slug # to prevent removing slug from existing product.
else
slug = productToProcess.slug
slug
_prepareNewProduct: (product) ->
product = @_ensureDefaults(product)
Promise.all [
@_resolveReference(@client.productTypes, 'productType', product.productType, "name=\"#{product.productType?.id}\"")
@_resolveProductCategories(product.categories)
@_resolveReference(@client.taxCategories, 'taxCategory', product.taxCategory, "name=\"#{product.taxCategory?.id}\"")
@_fetchAndResolveCustomReferences(product)
]
.spread (prodTypeId, prodCatsIds, taxCatId) =>
if prodTypeId
product.productType =
id: prodTypeId
typeId: 'product-type'
if taxCatId
product.taxCategory =
id: taxCatId
typeId: 'tax-category'
if prodCatsIds
product.categories = _.map prodCatsIds, (catId) ->
id: catId
typeId: 'category'
if not product.slug
if product.name
#Promise.reject 'Product name is required.'
product.slug = @_generateSlug product.name
Promise.resolve product
_generateSlug: (name) ->
slugs = _.mapObject name, (val) =>
uniqueToken = @_generateUniqueToken()
return slugify(val).concat("-#{uniqueToken}").substring(0, 256)
return slugs
_generateUniqueToken: ->
_.uniqueId "#{new Date().getTime()}"
_fetchAndResolveCustomReferences: (product) =>
Promise.all [
@_fetchAndResolveCustomReferencesByVariant(product.masterVariant),
Promise.map product.variants, (variant) =>
@_fetchAndResolveCustomReferencesByVariant(variant)
,{concurrency: 5}
]
.spread (masterVariant, variants) ->
Promise.resolve _.extend(product, { masterVariant, variants })
_fetchAndResolveCustomAttributeReferences: (variant) ->
if variant.attributes and not _.isEmpty(variant.attributes)
Promise.map variant.attributes, (attribute) =>
if attribute and _.isArray(attribute.value)
if _.every(attribute.value, @_isReferenceTypeAttribute)
@_resolveCustomReferenceSet(attribute.value)
.then (result) ->
attribute.value = result
Promise.resolve(attribute)
else Promise.resolve(attribute)
else
if attribute and @_isReferenceTypeAttribute(attribute)
@_resolveCustomReference(attribute)
.then (refId) ->
Promise.resolve
name: attribute.name
value:
id: refId
typeId: attribute.type.referenceTypeId
else Promise.resolve(attribute)
.then (attributes) ->
Promise.resolve _.extend(variant, { attributes })
else
Promise.resolve(variant)
_fetchAndResolveCustomPriceReferences: (variant) ->
if variant.prices and not _.isEmpty(variant.prices)
Promise.map variant.prices, (price) =>
if price and price.custom and price.custom.type and price.custom.type.id
service = @client.types
ref = { id: price.custom.type.id}
@_resolveReference(service, "types", ref, "key=\"#{ref.id}\"")
.then (refId) ->
price.custom.type.id = refId
Promise.resolve(price)
else
Promise.resolve(price)
.then (prices) ->
Promise.resolve _.extend(variant, { prices })
else
Promise.resolve(variant)
_fetchAndResolveCustomReferencesByVariant: (variant) ->
@_fetchAndResolveCustomAttributeReferences(variant)
.then (variant) =>
@_fetchAndResolveCustomPriceReferences(variant)
_resolveCustomReferenceSet: (attributeValue) ->
Promise.map attributeValue, (referenceObject) =>
@_resolveCustomReference(referenceObject)
_isReferenceTypeAttribute: (attribute) ->
_.has(attribute, 'type') and attribute.type.name is 'reference'
_resolveCustomReference: (referenceObject) ->
service = switch referenceObject.type.referenceTypeId
when 'product' then @client.productProjections
# TODO: map also other references
refKey = referenceObject.type.referenceTypeId
ref = _.deepClone referenceObject
ref.id = referenceObject.value
predicate = referenceObject._custom.predicate
@_resolveReference service, refKey, ref, predicate
_resolveProductCategories: (cats) ->
new Promise (resolve, reject) =>
if _.isEmpty(cats)
resolve()
else
Promise.all cats.map (cat) =>
@_resolveReference(@client.categories, 'categories', cat, "externalId=\"#{cat.id}\"")
.then (result) -> resolve(result.filter (c) -> c)
.catch (err) -> reject(err)
_resolveReference: (service, refKey, ref, predicate) ->
new Promise (resolve, reject) =>
if not ref
resolve()
if not @_cache[refKey]
@_cache[refKey] = {}
if @_cache[refKey][ref.id]
resolve(@_cache[refKey][ref.id].id)
else
request = service.where(predicate)
if refKey is 'product'
request.staged(true)
request.fetch()
.then (result) =>
if result.body.count is 0
reject "Didn't find any match while resolving #{refKey} (#{predicate})"
else
if _.size(result.body.results) > 1
@logger.warn "Found more than 1 #{refKey} for #{ref.id}"
if _.isEmpty(result.body.results)
reject "Inconsistency between body.count and body.results.length. Result is #{JSON.stringify(result)}"
@_cache[refKey][ref.id] = result.body.results[0]
@_cache[refKey][result.body.results[0].id] = result.body.results[0]
resolve(result.body.results[0].id)
module.exports = ProductImport
| 5481 | _ = require 'underscore'
_.mixin require 'underscore-mixins'
debug = require('debug')('sphere-product-import')
Mutex = require('await-mutex').default
Promise = require 'bluebird'
slugify = require 'underscore.string/slugify'
{SphereClient, ProductSync} = require 'sphere-node-sdk'
{Repeater} = require 'sphere-node-utils'
fs = require 'fs-extra'
path = require 'path'
{serializeError} = require 'serialize-error'
EnumValidator = require './enum-validator'
UnknownAttributesFilter = require './unknown-attributes-filter'
CommonUtils = require './common-utils'
EnsureDefaultAttributes = require './ensure-default-attributes'
util = require 'util'
Reassignment = require('commercetools-node-variant-reassignment').default
class ProductImport
constructor: (@logger, options = {}) ->
@sync = new ProductSync
if options.blackList and ProductSync.actionGroups
@sync.config @_configureSync(options.blackList)
@errorCallback = options.errorCallback or @_errorLogger
@beforeCreateCallback = options.beforeCreateCallback or Promise.resolve
@beforeUpdateCallback = options.beforeUpdateCallback or Promise.resolve
@ensureEnums = options.ensureEnums or false
@filterUnknownAttributes = options.filterUnknownAttributes or false
@ignoreSlugUpdates = options.ignoreSlugUpdates or false
@batchSize = options.batchSize or 30
@failOnDuplicateAttr = options.failOnDuplicateAttr or false
@logOnDuplicateAttr = if options.logOnDuplicateAttr? then options.logOnDuplicateAttr else true
@commonUtils = new CommonUtils @logger
@client = new SphereClient @commonUtils.extendUserAgent options.clientConfig
@enumValidator = new EnumValidator @logger
@unknownAttributesFilter = new UnknownAttributesFilter @logger
@filterActions = if _.isFunction(options.filterActions)
options.filterActions
else if _.isArray(options.filterActions)
(action) -> !_.contains(options.filterActions, action.action)
else
(action) -> true
# default web server url limit in bytes
# count starts after protocol (eg. https:// does not count)
@urlLimit = 8192
if options.defaultAttributes
@defaultAttributesService = new EnsureDefaultAttributes @logger, options.defaultAttributes
# possible values:
# always, publishedOnly, stagedAndPublishedOnly
@publishingStrategy = options.publishingStrategy or false
@matchVariantsByAttr = options.matchVariantsByAttr or undefined
@variantReassignmentOptions = options.variantReassignmentOptions or {}
if @variantReassignmentOptions.enabled
@reassignmentLock = new Mutex()
@reassignmentTriggerActions = ['removeVariant']
@reassignmentService = new Reassignment(@client, @logger,
(error) => @_handleErrorResponse(error),
@variantReassignmentOptions.retainExistingData,
@variantReassignmentOptions.allowedLocales)
@_configErrorHandling(options)
@_resetCache()
@_resetSummary()
debug "Product Importer initialized with config -> errorDir: #{@errorDir}, errorLimit: #{@errorLimit}, blacklist actions: #{options.blackList}, ensureEnums: #{@ensureEnums}"
_configureSync: (blackList) =>
@_validateSyncConfig(blackList)
debug "Product sync config validated"
_.difference(ProductSync.actionGroups, blackList)
.map (type) -> {type: type, group: 'white'}
.concat(blackList.map (type) -> {type: type, group: 'black'})
_validateSyncConfig: (blackList) ->
for actionGroup in blackList
if not _.contains(ProductSync.actionGroups, actionGroup)
throw ("invalid product sync action group: #{actionGroup}")
_configErrorHandling: (options) =>
if options.errorDir
@errorDir = options.errorDir
else
@errorDir = path.join(__dirname,'../errors')
fs.emptyDirSync(@errorDir)
if options.errorLimit
@errorLimit = options.errorLimit
else
@errorLimit = 30
_resetCache: ->
@_cache =
productType: {}
categories: {}
taxCategory: {}
_resetSummary: ->
@_summary =
productsWithMissingSKU: 0
created: 0
updated: 0
failed: 0
productTypeUpdated: 0
errorDir: @errorDir
if @filterUnknownAttributes then @_summary.unknownAttributeNames = []
if @variantReassignmentOptions.enabled
@_summary.variantReassignment = null
@reassignmentService._resetStats()
summaryReport: (filename) ->
message = "Summary: there were #{@_summary.created + @_summary.updated} imported products " +
"(#{@_summary.created} were new and #{@_summary.updated} were updates)."
if @_summary.productsWithMissingSKU > 0
message += "\nFound #{@_summary.productsWithMissingSKU} product(s) which do not have SKU and won't be imported."
message += " '#{filename}'" if filename
if @_summary.failed > 0
message += "\n #{@_summary.failed} product imports failed. Error reports stored at: #{@errorDir}"
report = {
reportMessage: message
detailedSummary: @_summary
}
report
_filterOutProductsBySkus: (products, blacklistSkus) ->
return products.filter (product) =>
variants = product.variants.concat(product.masterVariant)
variantSkus = variants.map (v) -> v.sku
# check if at least one SKU from product is in the blacklist
isProductBlacklisted = variantSkus.find (sku) ->
blacklistSkus.indexOf(sku) >= 0
# filter only products which are NOT blacklisted
not isProductBlacklisted
performStream: (chunk, cb) ->
@_processBatches(chunk).then -> cb()
_processBatches: (products) ->
batchedList = _.batchList(products, @batchSize) # max parallel elem to process
Promise.map batchedList, (productsToProcess) =>
debug 'Ensuring existence of product type in memory.'
@_ensureProductTypesInMemory(productsToProcess)
.then =>
if @ensureEnums
debug 'Ensuring existence of enum keys in product type.'
enumUpdateActions = @_validateEnums(productsToProcess)
uniqueEnumUpdateActions = @_filterUniqueUpdateActions(enumUpdateActions)
@_updateProductType(uniqueEnumUpdateActions)
.then =>
# filter out products which do not have SKUs on all variants
originalLength = productsToProcess.length
productsToProcess = productsToProcess.filter(@_doesProductHaveSkus)
filteredProductsLength = originalLength - productsToProcess.length
# if there are some products which do not have SKU
if filteredProductsLength
@logger.warn "Filtering out #{filteredProductsLength} product(s) which do not have SKU"
@_summary.productsWithMissingSKU += filteredProductsLength
.then () =>
@_getExistingProductsForSkus(@_extractUniqueSkus(productsToProcess))
.then (queriedEntries) =>
if @defaultAttributesService
debug 'Ensuring default attributes'
@_ensureDefaultAttributesInProducts(productsToProcess, queriedEntries)
.then ->
queriedEntries
else
queriedEntries
.then (queriedEntries) =>
@_createOrUpdate productsToProcess, queriedEntries
.then (results) =>
_.each results, (r) =>
if r.isFulfilled()
@_handleFulfilledResponse(r)
else if r.isRejected()
@_handleErrorResponse(r.reason())
Promise.resolve(@_summary)
, { concurrency: 1 } # run 1 batch at a time
.tap =>
if @variantReassignmentOptions.enabled
@_summary.variantReassignment = @reassignmentService.statistics
_getWhereQueryLimit: ->
client = @client.productProjections
.where('a')
.staged(true)
url = _.clone(@client.productProjections._rest._options.uri)
url = url.replace(/.*?:\/\//g, "")
url += @client.productProjections._currentEndpoint
url += "?" + @client.productProjections._queryString()
@client.productProjections._setDefaults()
# subtract 1 since we added 'a' as the where query
return @urlLimit - Buffer.byteLength((url),'utf-8') - 1
_getExistingProductsForSkus: (skus) =>
new Promise (resolve, reject) =>
if skus.length == 0
return resolve([])
skuChunks = @commonUtils._separateSkusChunksIntoSmallerChunks(
skus,
@_getWhereQueryLimit()
)
Promise.map(skuChunks, (skus) =>
predicate = @_createProductFetchBySkuQueryPredicate(skus)
@client.productProjections
.where(predicate)
.staged(true)
.perPage(200)
.all()
.fetch()
.then (res) ->
res.body.results
, { concurrency: 30 })
.then (results) ->
debug 'Fetched products: %j', results
uniqueProducts = _.uniq(_.compact(_.flatten(results)), (product) -> product.id)
resolve(uniqueProducts)
.catch (err) -> reject(err)
_errorLogger: (res, logger) =>
if @_summary.failed < @errorLimit or @errorLimit is 0
logger.error(util.inspect(res, false, 20, false), "Skipping product due to an error")
else if !@errorLimitHasBeenCommunicated
@errorLimitHasBeenCommunicated = true
logger.warn "
Error not logged as error limit of #{@errorLimit} has reached.
"
_handleErrorResponse: (error) =>
error = serializeError error
@_summary.failed++
if @errorDir
errorFile = path.join(@errorDir, "error-#{@_summary.failed}.json")
fs.outputJsonSync(errorFile, error, {spaces: 2})
if _.isFunction(@errorCallback)
@errorCallback(error, @logger)
else
@logger.error "Error callback has to be a function!"
_handleFulfilledResponse: (res) =>
switch res.value()?.statusCode
when 201 then @_summary.created++
when 200 then @_summary.updated++
_createProductFetchBySkuQueryPredicate: (skus) ->
skuString = "sku in (#{skus.map((val) -> JSON.stringify(val))})"
"masterVariant(#{skuString}) or variants(#{skuString})"
_doesProductHaveSkus: (product) ->
if product.masterVariant and not product.masterVariant.sku
return false
if product.variants?.length
for variant in product.variants
if not variant.sku
return false
true
_extractUniqueSkus: (products) ->
skus = []
for product in products
if product.masterVariant?.sku
skus.push(product.masterVariant.sku)
if product.variants?.length
for variant in product.variants
if variant.sku
skus.push(variant.sku)
return _.uniq(skus,false)
_getProductsMatchingByProductSkus: (prodToProcess, existingProducts) ->
prodToProcessSkus = @_extractUniqueSkus([prodToProcess])
_.filter existingProducts, (existingEntry) =>
existingProductSkus = @_extractUniqueSkus([existingEntry])
matchingSkus = _.intersection(prodToProcessSkus,existingProductSkus)
matchingSkus.length > 0
_updateProductRepeater: (prodToProcess, existingProducts, reassignmentRetries) ->
repeater = new Repeater {attempts: 5}
repeater.execute =>
@_updateProduct(prodToProcess, existingProducts, false, reassignmentRetries)
, (e) =>
if e.statusCode isnt 409 # concurrent modification
return Promise.reject e
@logger.warn "Recovering from 409 concurrentModification error on product '#{existingProducts[0].id}'"
Promise.resolve => # next task must be a function
@client.productProjections.staged(true).byId(existingProducts[0].id).fetch()
.then (result) =>
@_updateProduct(prodToProcess, [result.body], true, reassignmentRetries)
_getProductTypeIdByName: (name) ->
@_resolveReference(@client.productTypes, 'productType', { id: name }, "name=\"#{name}\"")
_runReassignmentForProduct: (product) ->
@logger.info(
"Running reassignment for a product with masterVariant.sku \"#{product.masterVariant.sku}\" - locking"
)
@reassignmentLock.lock()
.then (unlock) =>
@reassignmentService.execute([product], @_cache.productType)
.finally =>
@logger.info(
"Finished reassignment for a product with masterVariant.sku \"#{product.masterVariant.sku}\" - unlocking"
)
unlock()
_runReassignmentBeforeCreateOrUpdate: (product, reassignmentRetries = 0) ->
if reassignmentRetries > 5
masterSku = product.masterVariant.sku
return Promise.reject(
new Error("Error - too many reassignment retries for a product with masterVariant.sku \"#{masterSku}\"")
)
@_runReassignmentForProduct product
.then((res) =>
# if the product which failed during reassignment, remove it from processing
if(res.badRequestSKUs.length)
@logger.error(
"Removing product with SKUs \"#{res.badRequestSKUs}\" from processing due to a reassignment error"
)
return
# run createOrUpdate again the original prodToProcess object
@_createOrUpdateProduct(product, null, ++reassignmentRetries)
)
_updateProduct: (prodToProcess, existingProducts, productIsPrepared, reassignmentRetries) ->
existingProduct = existingProducts[0]
Promise.all([
@_fetchSameForAllAttributesOfProductType(prodToProcess.productType),
if productIsPrepared then prodToProcess else @_prepareUpdateProduct(prodToProcess, existingProduct),
@_getProductTypeIdByName(prodToProcess.productType.id)
])
.then ([sameForAllAttributes, preparedProduct, newProductTypeId]) =>
synced = @sync.buildActions(preparedProduct, existingProduct, sameForAllAttributes, @matchVariantsByAttr)
.filterActions (action) =>
@filterActions(action, existingProduct, preparedProduct)
hasProductTypeChanged = newProductTypeId != existingProduct.productType.id
# do not proceed if there are no update actions
if not ((hasProductTypeChanged and @variantReassignmentOptions.enabled) or synced.shouldUpdate())
return Promise.resolve statusCode: 304
updateRequest = synced.getUpdatePayload()
updateId = synced.getUpdateId()
if @variantReassignmentOptions.enabled
# more than one existing product
shouldRunReassignment = existingProducts.length > 1 or
# or productType changed
hasProductTypeChanged or
# or there is some listed update action for reassignment
updateRequest.actions.find (action) =>
action.action in @reassignmentTriggerActions
if shouldRunReassignment
return @_runReassignmentBeforeCreateOrUpdate(prodToProcess, reassignmentRetries)
# if reassignment is off or if there are no actions which triggers reassignment, run normal update
return Promise.resolve(@beforeUpdateCallback(existingProducts, prodToProcess, updateRequest))
.then () =>
@_updateInBatches(updateId, updateRequest)
_updateInBatches: (id, updateRequest) ->
latestVersion = updateRequest.version
batchedActions = _.batchList(updateRequest.actions, 500) # max 500 actions per update request
Promise.mapSeries batchedActions, (actions) =>
request =
version: latestVersion
actions: actions
@client.products
.byId(id)
.update(request)
.tap (res) ->
latestVersion = res.body.version
.then _.last # return only the last result
_cleanVariantAttributes: (variant) ->
attributeMap = []
if _.isArray(variant.attributes)
variant.attributes = variant.attributes.filter (attribute) =>
isDuplicate = attributeMap.indexOf(attribute.name) >= 0
attributeMap.push(attribute.name)
if isDuplicate
msg = "Variant with SKU '#{variant.sku}' has duplicate attributes with name '#{attribute.name}'."
if @failOnDuplicateAttr
throw new Error(msg)
else if @logOnDuplicateAttr
@logger.warn msg
# filter out duplicate attributes
not isDuplicate
_cleanDuplicateAttributes: (prodToProcess) ->
prodToProcess.variants = prodToProcess.variants || []
@_cleanVariantAttributes prodToProcess.masterVariant
prodToProcess.variants.forEach (variant) =>
@_cleanVariantAttributes variant
_canErrorBeFixedByReassignment: (err) ->
# if at least one error has code DuplicateField with field containing SKU or SLUG
(err?.body?.errors or []).find (error) ->
error.code == 'DuplicateField' and (error.field.indexOf 'slug' >= 0 or error.field.indexOf 'sku' >= 0)
_createOrUpdateProduct: (prodToProcess, existingProducts, reassignmentRetries = 0) ->
Promise.resolve(existingProducts)
# if the existing products were not fetched, load them from API
.then (existingProducts) =>
existingProducts or @_getExistingProductsForSkus(@_extractUniqueSkus([prodToProcess]))
.then (existingProducts) =>
if existingProducts.length
@_updateProductRepeater(prodToProcess, existingProducts, reassignmentRetries)
else
@_prepareNewProduct(prodToProcess)
.then (product) =>
Promise.resolve(@beforeCreateCallback(product))
.then () -> product
.then (product) =>
@client.products.create(product)
.catch (err) =>
# if the error can be handled by reassignment and it is enabled
if reassignmentRetries <= 5 and @variantReassignmentOptions.enabled and @_canErrorBeFixedByReassignment(err)
@_runReassignmentBeforeCreateOrUpdate(prodToProcess, reassignmentRetries)
else
throw err
_createOrUpdate: (productsToProcess, existingProducts) ->
debug 'Products to process: %j', {toProcess: productsToProcess, existing: existingProducts}
posts = _.map productsToProcess, (product) =>
# will filter out duplicate attributes
@_filterAttributes(product)
.then (product) =>
# should be inside of a Promise because it throws error in case of duplicate fields
@_cleanDuplicateAttributes(product)
matchingExistingProducts = @_getProductsMatchingByProductSkus(product, existingProducts)
@_createOrUpdateProduct(product, matchingExistingProducts)
debug 'About to send %s requests', _.size(posts)
Promise.settle(posts)
_filterAttributes: (product) =>
new Promise (resolve) =>
if @filterUnknownAttributes
@unknownAttributesFilter.filter(@_cache.productType[product.productType.id],product, @_summary.unknownAttributeNames)
.then (filteredProduct) ->
resolve(filteredProduct)
else
resolve(product)
# updateActions are of the form:
# { productTypeId: [{updateAction},{updateAction},...],
# productTypeId: [{updateAction},{updateAction},...]
# }
_filterUniqueUpdateActions: (updateActions) =>
_.reduce _.keys(updateActions), (acc, productTypeId) =>
actions = updateActions[productTypeId]
uniqueActions = @commonUtils.uniqueObjectFilter actions
acc[productTypeId] = uniqueActions
acc
, {}
_ensureProductTypesInMemory: (products) =>
Promise.map products, (product) =>
@_ensureProductTypeInMemory(product.productType.id)
, {concurrency: 1}
_ensureDefaultAttributesInProducts: (products, queriedEntries) =>
if queriedEntries
queriedEntries = _.compact(queriedEntries)
Promise.map products, (product) =>
if queriedEntries?.length > 0
uniqueSkus = @_extractUniqueSkus([product])
productFromServer = _.find(queriedEntries, (entry) =>
serverUniqueSkus = @_extractUniqueSkus([entry])
intersection = _.intersection(uniqueSkus, serverUniqueSkus)
return _.compact(intersection).length > 0
)
@defaultAttributesService.ensureDefaultAttributesInProduct(product, productFromServer)
, {concurrency: 1}
_ensureProductTypeInMemory: (productTypeId) =>
if @_cache.productType[productTypeId]
Promise.resolve()
else
productType =
id: productTypeId
@_resolveReference(@client.productTypes, 'productType', productType, "name=\"#{productType?.id}\"")
_validateEnums: (products) =>
enumUpdateActions = {}
_.each products, (product) =>
updateActions = @enumValidator.validateProduct(product, @_cache.productType[product.productType.id])
if updateActions and _.size(updateActions.actions) > 0 then @_updateEnumUpdateActions(enumUpdateActions, updateActions)
enumUpdateActions
_updateProductType: (enumUpdateActions) =>
if _.isEmpty(enumUpdateActions)
Promise.resolve()
else
debug "Updating product type(s): #{_.keys(enumUpdateActions)}"
Promise.map _.keys(enumUpdateActions), (productTypeId) =>
updateRequest =
version: @_cache.productType[productTypeId].version
actions: enumUpdateActions[productTypeId]
@client.productTypes.byId(@_cache.productType[productTypeId].id).update(updateRequest)
.then (updatedProductType) =>
@_cache.productType[productTypeId] = updatedProductType.body
@_summary.productTypeUpdated++
_updateEnumUpdateActions: (enumUpdateActions, updateActions) ->
if enumUpdateActions[updateActions.productTypeId]
enumUpdateActions[updateActions.productTypeId] = enumUpdateActions[updateActions.productTypeId].concat(updateActions.actions)
else
enumUpdateActions[updateActions.productTypeId] = updateActions.actions
_fetchSameForAllAttributesOfProductType: (productType) =>
if @_cache.productType["#{productType.id}_sameForAllAttributes"]
Promise.resolve(@_cache.productType["#{productType.id}_sameForAllAttributes"])
else
@_resolveReference(@client.productTypes, 'productType', productType, "name=\"#{productType?.id}\"")
.then =>
sameValueAttributes = _.where(@_cache.productType[productType.id].attributes, {attributeConstraint: "SameForAll"})
sameValueAttributeNames = _.pluck(sameValueAttributes, 'name')
@_cache.productType["#{productType.id}_sameForAllAttributes"] = sameValueAttributeNames
Promise.resolve(sameValueAttributeNames)
_ensureVariantDefaults: (variant = {}) ->
variantDefaults =
attributes: []
prices: []
images: []
_.defaults(variant, variantDefaults)
_ensureDefaults: (product) =>
debug 'ensuring default fields in variants.'
_.defaults product,
masterVariant: @_ensureVariantDefaults(product.masterVariant)
variants: _.map product.variants, (variant) => @_ensureVariantDefaults(variant)
return product
_prepareUpdateProduct: (productToProcess, existingProduct) ->
productToProcess = @_ensureDefaults(productToProcess)
Promise.all [
@_resolveProductCategories(productToProcess.categories)
@_resolveReference(@client.taxCategories, 'taxCategory', productToProcess.taxCategory, "name=\"#{productToProcess.taxCategory?.id}\"")
@_fetchAndResolveCustomReferences(productToProcess)
]
.spread (prodCatsIds, taxCatId) =>
if taxCatId
productToProcess.taxCategory =
id: taxCatId
typeId: 'tax-category'
if prodCatsIds
productToProcess.categories = _.map prodCatsIds, (catId) ->
id: catId
typeId: 'category'
productToProcess.slug = @_updateProductSlug productToProcess, existingProduct
Promise.resolve productToProcess
_updateProductSlug: (productToProcess, existingProduct) =>
if @ignoreSlugUpdates
slug = existingProduct.slug
else if not productToProcess.slug
debug 'slug missing in product to process, assigning same as existing product: %s', existingProduct.slug
slug = existingProduct.slug # to prevent removing slug from existing product.
else
slug = productToProcess.slug
slug
_prepareNewProduct: (product) ->
product = @_ensureDefaults(product)
Promise.all [
@_resolveReference(@client.productTypes, 'productType', product.productType, "name=\"#{product.productType?.id}\"")
@_resolveProductCategories(product.categories)
@_resolveReference(@client.taxCategories, 'taxCategory', product.taxCategory, "name=\"#{product.taxCategory?.id}\"")
@_fetchAndResolveCustomReferences(product)
]
.spread (prodTypeId, prodCatsIds, taxCatId) =>
if prodTypeId
product.productType =
id: prodTypeId
typeId: 'product-type'
if taxCatId
product.taxCategory =
id: taxCatId
typeId: 'tax-category'
if prodCatsIds
product.categories = _.map prodCatsIds, (catId) ->
id: catId
typeId: 'category'
if not product.slug
if product.name
#Promise.reject 'Product name is required.'
product.slug = @_generateSlug product.name
Promise.resolve product
_generateSlug: (name) ->
slugs = _.mapObject name, (val) =>
uniqueToken = @_generateUniqueToken()
return slugify(val).concat("-#{uniqueToken}").substring(0, 256)
return slugs
_generateUniqueToken: ->
_.uniqueId "#{new Date().getTime()}"
_fetchAndResolveCustomReferences: (product) =>
Promise.all [
@_fetchAndResolveCustomReferencesByVariant(product.masterVariant),
Promise.map product.variants, (variant) =>
@_fetchAndResolveCustomReferencesByVariant(variant)
,{concurrency: 5}
]
.spread (masterVariant, variants) ->
Promise.resolve _.extend(product, { masterVariant, variants })
_fetchAndResolveCustomAttributeReferences: (variant) ->
if variant.attributes and not _.isEmpty(variant.attributes)
Promise.map variant.attributes, (attribute) =>
if attribute and _.isArray(attribute.value)
if _.every(attribute.value, @_isReferenceTypeAttribute)
@_resolveCustomReferenceSet(attribute.value)
.then (result) ->
attribute.value = result
Promise.resolve(attribute)
else Promise.resolve(attribute)
else
if attribute and @_isReferenceTypeAttribute(attribute)
@_resolveCustomReference(attribute)
.then (refId) ->
Promise.resolve
name: attribute.name
value:
id: refId
typeId: attribute.type.referenceTypeId
else Promise.resolve(attribute)
.then (attributes) ->
Promise.resolve _.extend(variant, { attributes })
else
Promise.resolve(variant)
_fetchAndResolveCustomPriceReferences: (variant) ->
if variant.prices and not _.isEmpty(variant.prices)
Promise.map variant.prices, (price) =>
if price and price.custom and price.custom.type and price.custom.type.id
service = @client.types
ref = { id: price.custom.type.id}
@_resolveReference(service, "types", ref, "key=\"#{ref.id}\"")
.then (refId) ->
price.custom.type.id = refId
Promise.resolve(price)
else
Promise.resolve(price)
.then (prices) ->
Promise.resolve _.extend(variant, { prices })
else
Promise.resolve(variant)
_fetchAndResolveCustomReferencesByVariant: (variant) ->
@_fetchAndResolveCustomAttributeReferences(variant)
.then (variant) =>
@_fetchAndResolveCustomPriceReferences(variant)
_resolveCustomReferenceSet: (attributeValue) ->
Promise.map attributeValue, (referenceObject) =>
@_resolveCustomReference(referenceObject)
_isReferenceTypeAttribute: (attribute) ->
_.has(attribute, 'type') and attribute.type.name is 'reference'
_resolveCustomReference: (referenceObject) ->
service = switch referenceObject.type.referenceTypeId
when 'product' then @client.productProjections
# TODO: map also other references
refKey = referenceObject.type.referenceTypeId
ref = _.deepClone referenceObject
ref.id = referenceObject.value
predicate = referenceObject._custom.predicate
@_resolveReference service, refKey, ref, predicate
_resolveProductCategories: (cats) ->
new Promise (resolve, reject) =>
if _.isEmpty(cats)
resolve()
else
Promise.all cats.map (cat) =>
@_resolveReference(@client.categories, 'categories', cat, "externalId=\"#{cat.id}\"")
.then (result) -> resolve(result.filter (c) -> c)
.catch (err) -> reject(err)
_resolveReference: (service, refKey, ref, predicate) ->
new Promise (resolve, reject) =>
if not ref
resolve()
if not @_cache[refKey]
@_cache[refKey] = {}
if @_cache[refKey][ref.id]
resolve(@_cache[refKey][ref.id].id)
else
request = service.where(predicate)
if refKey is '<KEY>'
request.staged(true)
request.fetch()
.then (result) =>
if result.body.count is 0
reject "Didn't find any match while resolving #{refKey} (#{predicate})"
else
if _.size(result.body.results) > 1
@logger.warn "Found more than 1 #{refKey} for #{ref.id}"
if _.isEmpty(result.body.results)
reject "Inconsistency between body.count and body.results.length. Result is #{JSON.stringify(result)}"
@_cache[refKey][ref.id] = result.body.results[0]
@_cache[refKey][result.body.results[0].id] = result.body.results[0]
resolve(result.body.results[0].id)
module.exports = ProductImport
| true | _ = require 'underscore'
_.mixin require 'underscore-mixins'
debug = require('debug')('sphere-product-import')
Mutex = require('await-mutex').default
Promise = require 'bluebird'
slugify = require 'underscore.string/slugify'
{SphereClient, ProductSync} = require 'sphere-node-sdk'
{Repeater} = require 'sphere-node-utils'
fs = require 'fs-extra'
path = require 'path'
{serializeError} = require 'serialize-error'
EnumValidator = require './enum-validator'
UnknownAttributesFilter = require './unknown-attributes-filter'
CommonUtils = require './common-utils'
EnsureDefaultAttributes = require './ensure-default-attributes'
util = require 'util'
Reassignment = require('commercetools-node-variant-reassignment').default
class ProductImport
constructor: (@logger, options = {}) ->
@sync = new ProductSync
if options.blackList and ProductSync.actionGroups
@sync.config @_configureSync(options.blackList)
@errorCallback = options.errorCallback or @_errorLogger
@beforeCreateCallback = options.beforeCreateCallback or Promise.resolve
@beforeUpdateCallback = options.beforeUpdateCallback or Promise.resolve
@ensureEnums = options.ensureEnums or false
@filterUnknownAttributes = options.filterUnknownAttributes or false
@ignoreSlugUpdates = options.ignoreSlugUpdates or false
@batchSize = options.batchSize or 30
@failOnDuplicateAttr = options.failOnDuplicateAttr or false
@logOnDuplicateAttr = if options.logOnDuplicateAttr? then options.logOnDuplicateAttr else true
@commonUtils = new CommonUtils @logger
@client = new SphereClient @commonUtils.extendUserAgent options.clientConfig
@enumValidator = new EnumValidator @logger
@unknownAttributesFilter = new UnknownAttributesFilter @logger
@filterActions = if _.isFunction(options.filterActions)
options.filterActions
else if _.isArray(options.filterActions)
(action) -> !_.contains(options.filterActions, action.action)
else
(action) -> true
# default web server url limit in bytes
# count starts after protocol (eg. https:// does not count)
@urlLimit = 8192
if options.defaultAttributes
@defaultAttributesService = new EnsureDefaultAttributes @logger, options.defaultAttributes
# possible values:
# always, publishedOnly, stagedAndPublishedOnly
@publishingStrategy = options.publishingStrategy or false
@matchVariantsByAttr = options.matchVariantsByAttr or undefined
@variantReassignmentOptions = options.variantReassignmentOptions or {}
if @variantReassignmentOptions.enabled
@reassignmentLock = new Mutex()
@reassignmentTriggerActions = ['removeVariant']
@reassignmentService = new Reassignment(@client, @logger,
(error) => @_handleErrorResponse(error),
@variantReassignmentOptions.retainExistingData,
@variantReassignmentOptions.allowedLocales)
@_configErrorHandling(options)
@_resetCache()
@_resetSummary()
debug "Product Importer initialized with config -> errorDir: #{@errorDir}, errorLimit: #{@errorLimit}, blacklist actions: #{options.blackList}, ensureEnums: #{@ensureEnums}"
_configureSync: (blackList) =>
@_validateSyncConfig(blackList)
debug "Product sync config validated"
_.difference(ProductSync.actionGroups, blackList)
.map (type) -> {type: type, group: 'white'}
.concat(blackList.map (type) -> {type: type, group: 'black'})
_validateSyncConfig: (blackList) ->
for actionGroup in blackList
if not _.contains(ProductSync.actionGroups, actionGroup)
throw ("invalid product sync action group: #{actionGroup}")
_configErrorHandling: (options) =>
if options.errorDir
@errorDir = options.errorDir
else
@errorDir = path.join(__dirname,'../errors')
fs.emptyDirSync(@errorDir)
if options.errorLimit
@errorLimit = options.errorLimit
else
@errorLimit = 30
_resetCache: ->
@_cache =
productType: {}
categories: {}
taxCategory: {}
_resetSummary: ->
@_summary =
productsWithMissingSKU: 0
created: 0
updated: 0
failed: 0
productTypeUpdated: 0
errorDir: @errorDir
if @filterUnknownAttributes then @_summary.unknownAttributeNames = []
if @variantReassignmentOptions.enabled
@_summary.variantReassignment = null
@reassignmentService._resetStats()
summaryReport: (filename) ->
message = "Summary: there were #{@_summary.created + @_summary.updated} imported products " +
"(#{@_summary.created} were new and #{@_summary.updated} were updates)."
if @_summary.productsWithMissingSKU > 0
message += "\nFound #{@_summary.productsWithMissingSKU} product(s) which do not have SKU and won't be imported."
message += " '#{filename}'" if filename
if @_summary.failed > 0
message += "\n #{@_summary.failed} product imports failed. Error reports stored at: #{@errorDir}"
report = {
reportMessage: message
detailedSummary: @_summary
}
report
_filterOutProductsBySkus: (products, blacklistSkus) ->
return products.filter (product) =>
variants = product.variants.concat(product.masterVariant)
variantSkus = variants.map (v) -> v.sku
# check if at least one SKU from product is in the blacklist
isProductBlacklisted = variantSkus.find (sku) ->
blacklistSkus.indexOf(sku) >= 0
# filter only products which are NOT blacklisted
not isProductBlacklisted
performStream: (chunk, cb) ->
@_processBatches(chunk).then -> cb()
_processBatches: (products) ->
batchedList = _.batchList(products, @batchSize) # max parallel elem to process
Promise.map batchedList, (productsToProcess) =>
debug 'Ensuring existence of product type in memory.'
@_ensureProductTypesInMemory(productsToProcess)
.then =>
if @ensureEnums
debug 'Ensuring existence of enum keys in product type.'
enumUpdateActions = @_validateEnums(productsToProcess)
uniqueEnumUpdateActions = @_filterUniqueUpdateActions(enumUpdateActions)
@_updateProductType(uniqueEnumUpdateActions)
.then =>
# filter out products which do not have SKUs on all variants
originalLength = productsToProcess.length
productsToProcess = productsToProcess.filter(@_doesProductHaveSkus)
filteredProductsLength = originalLength - productsToProcess.length
# if there are some products which do not have SKU
if filteredProductsLength
@logger.warn "Filtering out #{filteredProductsLength} product(s) which do not have SKU"
@_summary.productsWithMissingSKU += filteredProductsLength
.then () =>
@_getExistingProductsForSkus(@_extractUniqueSkus(productsToProcess))
.then (queriedEntries) =>
if @defaultAttributesService
debug 'Ensuring default attributes'
@_ensureDefaultAttributesInProducts(productsToProcess, queriedEntries)
.then ->
queriedEntries
else
queriedEntries
.then (queriedEntries) =>
@_createOrUpdate productsToProcess, queriedEntries
.then (results) =>
_.each results, (r) =>
if r.isFulfilled()
@_handleFulfilledResponse(r)
else if r.isRejected()
@_handleErrorResponse(r.reason())
Promise.resolve(@_summary)
, { concurrency: 1 } # run 1 batch at a time
.tap =>
if @variantReassignmentOptions.enabled
@_summary.variantReassignment = @reassignmentService.statistics
_getWhereQueryLimit: ->
client = @client.productProjections
.where('a')
.staged(true)
url = _.clone(@client.productProjections._rest._options.uri)
url = url.replace(/.*?:\/\//g, "")
url += @client.productProjections._currentEndpoint
url += "?" + @client.productProjections._queryString()
@client.productProjections._setDefaults()
# subtract 1 since we added 'a' as the where query
return @urlLimit - Buffer.byteLength((url),'utf-8') - 1
_getExistingProductsForSkus: (skus) =>
new Promise (resolve, reject) =>
if skus.length == 0
return resolve([])
skuChunks = @commonUtils._separateSkusChunksIntoSmallerChunks(
skus,
@_getWhereQueryLimit()
)
Promise.map(skuChunks, (skus) =>
predicate = @_createProductFetchBySkuQueryPredicate(skus)
@client.productProjections
.where(predicate)
.staged(true)
.perPage(200)
.all()
.fetch()
.then (res) ->
res.body.results
, { concurrency: 30 })
.then (results) ->
debug 'Fetched products: %j', results
uniqueProducts = _.uniq(_.compact(_.flatten(results)), (product) -> product.id)
resolve(uniqueProducts)
.catch (err) -> reject(err)
_errorLogger: (res, logger) =>
if @_summary.failed < @errorLimit or @errorLimit is 0
logger.error(util.inspect(res, false, 20, false), "Skipping product due to an error")
else if !@errorLimitHasBeenCommunicated
@errorLimitHasBeenCommunicated = true
logger.warn "
Error not logged as error limit of #{@errorLimit} has reached.
"
_handleErrorResponse: (error) =>
error = serializeError error
@_summary.failed++
if @errorDir
errorFile = path.join(@errorDir, "error-#{@_summary.failed}.json")
fs.outputJsonSync(errorFile, error, {spaces: 2})
if _.isFunction(@errorCallback)
@errorCallback(error, @logger)
else
@logger.error "Error callback has to be a function!"
_handleFulfilledResponse: (res) =>
switch res.value()?.statusCode
when 201 then @_summary.created++
when 200 then @_summary.updated++
_createProductFetchBySkuQueryPredicate: (skus) ->
skuString = "sku in (#{skus.map((val) -> JSON.stringify(val))})"
"masterVariant(#{skuString}) or variants(#{skuString})"
_doesProductHaveSkus: (product) ->
if product.masterVariant and not product.masterVariant.sku
return false
if product.variants?.length
for variant in product.variants
if not variant.sku
return false
true
_extractUniqueSkus: (products) ->
skus = []
for product in products
if product.masterVariant?.sku
skus.push(product.masterVariant.sku)
if product.variants?.length
for variant in product.variants
if variant.sku
skus.push(variant.sku)
return _.uniq(skus,false)
_getProductsMatchingByProductSkus: (prodToProcess, existingProducts) ->
prodToProcessSkus = @_extractUniqueSkus([prodToProcess])
_.filter existingProducts, (existingEntry) =>
existingProductSkus = @_extractUniqueSkus([existingEntry])
matchingSkus = _.intersection(prodToProcessSkus,existingProductSkus)
matchingSkus.length > 0
_updateProductRepeater: (prodToProcess, existingProducts, reassignmentRetries) ->
repeater = new Repeater {attempts: 5}
repeater.execute =>
@_updateProduct(prodToProcess, existingProducts, false, reassignmentRetries)
, (e) =>
if e.statusCode isnt 409 # concurrent modification
return Promise.reject e
@logger.warn "Recovering from 409 concurrentModification error on product '#{existingProducts[0].id}'"
Promise.resolve => # next task must be a function
@client.productProjections.staged(true).byId(existingProducts[0].id).fetch()
.then (result) =>
@_updateProduct(prodToProcess, [result.body], true, reassignmentRetries)
_getProductTypeIdByName: (name) ->
@_resolveReference(@client.productTypes, 'productType', { id: name }, "name=\"#{name}\"")
_runReassignmentForProduct: (product) ->
@logger.info(
"Running reassignment for a product with masterVariant.sku \"#{product.masterVariant.sku}\" - locking"
)
@reassignmentLock.lock()
.then (unlock) =>
@reassignmentService.execute([product], @_cache.productType)
.finally =>
@logger.info(
"Finished reassignment for a product with masterVariant.sku \"#{product.masterVariant.sku}\" - unlocking"
)
unlock()
_runReassignmentBeforeCreateOrUpdate: (product, reassignmentRetries = 0) ->
if reassignmentRetries > 5
masterSku = product.masterVariant.sku
return Promise.reject(
new Error("Error - too many reassignment retries for a product with masterVariant.sku \"#{masterSku}\"")
)
@_runReassignmentForProduct product
.then((res) =>
# if the product which failed during reassignment, remove it from processing
if(res.badRequestSKUs.length)
@logger.error(
"Removing product with SKUs \"#{res.badRequestSKUs}\" from processing due to a reassignment error"
)
return
# run createOrUpdate again the original prodToProcess object
@_createOrUpdateProduct(product, null, ++reassignmentRetries)
)
_updateProduct: (prodToProcess, existingProducts, productIsPrepared, reassignmentRetries) ->
existingProduct = existingProducts[0]
Promise.all([
@_fetchSameForAllAttributesOfProductType(prodToProcess.productType),
if productIsPrepared then prodToProcess else @_prepareUpdateProduct(prodToProcess, existingProduct),
@_getProductTypeIdByName(prodToProcess.productType.id)
])
.then ([sameForAllAttributes, preparedProduct, newProductTypeId]) =>
synced = @sync.buildActions(preparedProduct, existingProduct, sameForAllAttributes, @matchVariantsByAttr)
.filterActions (action) =>
@filterActions(action, existingProduct, preparedProduct)
hasProductTypeChanged = newProductTypeId != existingProduct.productType.id
# do not proceed if there are no update actions
if not ((hasProductTypeChanged and @variantReassignmentOptions.enabled) or synced.shouldUpdate())
return Promise.resolve statusCode: 304
updateRequest = synced.getUpdatePayload()
updateId = synced.getUpdateId()
if @variantReassignmentOptions.enabled
# more than one existing product
shouldRunReassignment = existingProducts.length > 1 or
# or productType changed
hasProductTypeChanged or
# or there is some listed update action for reassignment
updateRequest.actions.find (action) =>
action.action in @reassignmentTriggerActions
if shouldRunReassignment
return @_runReassignmentBeforeCreateOrUpdate(prodToProcess, reassignmentRetries)
# if reassignment is off or if there are no actions which triggers reassignment, run normal update
return Promise.resolve(@beforeUpdateCallback(existingProducts, prodToProcess, updateRequest))
.then () =>
@_updateInBatches(updateId, updateRequest)
_updateInBatches: (id, updateRequest) ->
latestVersion = updateRequest.version
batchedActions = _.batchList(updateRequest.actions, 500) # max 500 actions per update request
Promise.mapSeries batchedActions, (actions) =>
request =
version: latestVersion
actions: actions
@client.products
.byId(id)
.update(request)
.tap (res) ->
latestVersion = res.body.version
.then _.last # return only the last result
_cleanVariantAttributes: (variant) ->
attributeMap = []
if _.isArray(variant.attributes)
variant.attributes = variant.attributes.filter (attribute) =>
isDuplicate = attributeMap.indexOf(attribute.name) >= 0
attributeMap.push(attribute.name)
if isDuplicate
msg = "Variant with SKU '#{variant.sku}' has duplicate attributes with name '#{attribute.name}'."
if @failOnDuplicateAttr
throw new Error(msg)
else if @logOnDuplicateAttr
@logger.warn msg
# filter out duplicate attributes
not isDuplicate
_cleanDuplicateAttributes: (prodToProcess) ->
prodToProcess.variants = prodToProcess.variants || []
@_cleanVariantAttributes prodToProcess.masterVariant
prodToProcess.variants.forEach (variant) =>
@_cleanVariantAttributes variant
_canErrorBeFixedByReassignment: (err) ->
# if at least one error has code DuplicateField with field containing SKU or SLUG
(err?.body?.errors or []).find (error) ->
error.code == 'DuplicateField' and (error.field.indexOf 'slug' >= 0 or error.field.indexOf 'sku' >= 0)
_createOrUpdateProduct: (prodToProcess, existingProducts, reassignmentRetries = 0) ->
Promise.resolve(existingProducts)
# if the existing products were not fetched, load them from API
.then (existingProducts) =>
existingProducts or @_getExistingProductsForSkus(@_extractUniqueSkus([prodToProcess]))
.then (existingProducts) =>
if existingProducts.length
@_updateProductRepeater(prodToProcess, existingProducts, reassignmentRetries)
else
@_prepareNewProduct(prodToProcess)
.then (product) =>
Promise.resolve(@beforeCreateCallback(product))
.then () -> product
.then (product) =>
@client.products.create(product)
.catch (err) =>
# if the error can be handled by reassignment and it is enabled
if reassignmentRetries <= 5 and @variantReassignmentOptions.enabled and @_canErrorBeFixedByReassignment(err)
@_runReassignmentBeforeCreateOrUpdate(prodToProcess, reassignmentRetries)
else
throw err
_createOrUpdate: (productsToProcess, existingProducts) ->
debug 'Products to process: %j', {toProcess: productsToProcess, existing: existingProducts}
posts = _.map productsToProcess, (product) =>
# will filter out duplicate attributes
@_filterAttributes(product)
.then (product) =>
# should be inside of a Promise because it throws error in case of duplicate fields
@_cleanDuplicateAttributes(product)
matchingExistingProducts = @_getProductsMatchingByProductSkus(product, existingProducts)
@_createOrUpdateProduct(product, matchingExistingProducts)
debug 'About to send %s requests', _.size(posts)
Promise.settle(posts)
_filterAttributes: (product) =>
new Promise (resolve) =>
if @filterUnknownAttributes
@unknownAttributesFilter.filter(@_cache.productType[product.productType.id],product, @_summary.unknownAttributeNames)
.then (filteredProduct) ->
resolve(filteredProduct)
else
resolve(product)
# updateActions are of the form:
# { productTypeId: [{updateAction},{updateAction},...],
# productTypeId: [{updateAction},{updateAction},...]
# }
_filterUniqueUpdateActions: (updateActions) =>
_.reduce _.keys(updateActions), (acc, productTypeId) =>
actions = updateActions[productTypeId]
uniqueActions = @commonUtils.uniqueObjectFilter actions
acc[productTypeId] = uniqueActions
acc
, {}
_ensureProductTypesInMemory: (products) =>
Promise.map products, (product) =>
@_ensureProductTypeInMemory(product.productType.id)
, {concurrency: 1}
_ensureDefaultAttributesInProducts: (products, queriedEntries) =>
if queriedEntries
queriedEntries = _.compact(queriedEntries)
Promise.map products, (product) =>
if queriedEntries?.length > 0
uniqueSkus = @_extractUniqueSkus([product])
productFromServer = _.find(queriedEntries, (entry) =>
serverUniqueSkus = @_extractUniqueSkus([entry])
intersection = _.intersection(uniqueSkus, serverUniqueSkus)
return _.compact(intersection).length > 0
)
@defaultAttributesService.ensureDefaultAttributesInProduct(product, productFromServer)
, {concurrency: 1}
_ensureProductTypeInMemory: (productTypeId) =>
if @_cache.productType[productTypeId]
Promise.resolve()
else
productType =
id: productTypeId
@_resolveReference(@client.productTypes, 'productType', productType, "name=\"#{productType?.id}\"")
_validateEnums: (products) =>
enumUpdateActions = {}
_.each products, (product) =>
updateActions = @enumValidator.validateProduct(product, @_cache.productType[product.productType.id])
if updateActions and _.size(updateActions.actions) > 0 then @_updateEnumUpdateActions(enumUpdateActions, updateActions)
enumUpdateActions
_updateProductType: (enumUpdateActions) =>
if _.isEmpty(enumUpdateActions)
Promise.resolve()
else
debug "Updating product type(s): #{_.keys(enumUpdateActions)}"
Promise.map _.keys(enumUpdateActions), (productTypeId) =>
updateRequest =
version: @_cache.productType[productTypeId].version
actions: enumUpdateActions[productTypeId]
@client.productTypes.byId(@_cache.productType[productTypeId].id).update(updateRequest)
.then (updatedProductType) =>
@_cache.productType[productTypeId] = updatedProductType.body
@_summary.productTypeUpdated++
_updateEnumUpdateActions: (enumUpdateActions, updateActions) ->
if enumUpdateActions[updateActions.productTypeId]
enumUpdateActions[updateActions.productTypeId] = enumUpdateActions[updateActions.productTypeId].concat(updateActions.actions)
else
enumUpdateActions[updateActions.productTypeId] = updateActions.actions
_fetchSameForAllAttributesOfProductType: (productType) =>
if @_cache.productType["#{productType.id}_sameForAllAttributes"]
Promise.resolve(@_cache.productType["#{productType.id}_sameForAllAttributes"])
else
@_resolveReference(@client.productTypes, 'productType', productType, "name=\"#{productType?.id}\"")
.then =>
sameValueAttributes = _.where(@_cache.productType[productType.id].attributes, {attributeConstraint: "SameForAll"})
sameValueAttributeNames = _.pluck(sameValueAttributes, 'name')
@_cache.productType["#{productType.id}_sameForAllAttributes"] = sameValueAttributeNames
Promise.resolve(sameValueAttributeNames)
_ensureVariantDefaults: (variant = {}) ->
variantDefaults =
attributes: []
prices: []
images: []
_.defaults(variant, variantDefaults)
_ensureDefaults: (product) =>
debug 'ensuring default fields in variants.'
_.defaults product,
masterVariant: @_ensureVariantDefaults(product.masterVariant)
variants: _.map product.variants, (variant) => @_ensureVariantDefaults(variant)
return product
_prepareUpdateProduct: (productToProcess, existingProduct) ->
productToProcess = @_ensureDefaults(productToProcess)
Promise.all [
@_resolveProductCategories(productToProcess.categories)
@_resolveReference(@client.taxCategories, 'taxCategory', productToProcess.taxCategory, "name=\"#{productToProcess.taxCategory?.id}\"")
@_fetchAndResolveCustomReferences(productToProcess)
]
.spread (prodCatsIds, taxCatId) =>
if taxCatId
productToProcess.taxCategory =
id: taxCatId
typeId: 'tax-category'
if prodCatsIds
productToProcess.categories = _.map prodCatsIds, (catId) ->
id: catId
typeId: 'category'
productToProcess.slug = @_updateProductSlug productToProcess, existingProduct
Promise.resolve productToProcess
_updateProductSlug: (productToProcess, existingProduct) =>
if @ignoreSlugUpdates
slug = existingProduct.slug
else if not productToProcess.slug
debug 'slug missing in product to process, assigning same as existing product: %s', existingProduct.slug
slug = existingProduct.slug # to prevent removing slug from existing product.
else
slug = productToProcess.slug
slug
_prepareNewProduct: (product) ->
product = @_ensureDefaults(product)
Promise.all [
@_resolveReference(@client.productTypes, 'productType', product.productType, "name=\"#{product.productType?.id}\"")
@_resolveProductCategories(product.categories)
@_resolveReference(@client.taxCategories, 'taxCategory', product.taxCategory, "name=\"#{product.taxCategory?.id}\"")
@_fetchAndResolveCustomReferences(product)
]
.spread (prodTypeId, prodCatsIds, taxCatId) =>
if prodTypeId
product.productType =
id: prodTypeId
typeId: 'product-type'
if taxCatId
product.taxCategory =
id: taxCatId
typeId: 'tax-category'
if prodCatsIds
product.categories = _.map prodCatsIds, (catId) ->
id: catId
typeId: 'category'
if not product.slug
if product.name
#Promise.reject 'Product name is required.'
product.slug = @_generateSlug product.name
Promise.resolve product
_generateSlug: (name) ->
slugs = _.mapObject name, (val) =>
uniqueToken = @_generateUniqueToken()
return slugify(val).concat("-#{uniqueToken}").substring(0, 256)
return slugs
_generateUniqueToken: ->
_.uniqueId "#{new Date().getTime()}"
_fetchAndResolveCustomReferences: (product) =>
Promise.all [
@_fetchAndResolveCustomReferencesByVariant(product.masterVariant),
Promise.map product.variants, (variant) =>
@_fetchAndResolveCustomReferencesByVariant(variant)
,{concurrency: 5}
]
.spread (masterVariant, variants) ->
Promise.resolve _.extend(product, { masterVariant, variants })
_fetchAndResolveCustomAttributeReferences: (variant) ->
if variant.attributes and not _.isEmpty(variant.attributes)
Promise.map variant.attributes, (attribute) =>
if attribute and _.isArray(attribute.value)
if _.every(attribute.value, @_isReferenceTypeAttribute)
@_resolveCustomReferenceSet(attribute.value)
.then (result) ->
attribute.value = result
Promise.resolve(attribute)
else Promise.resolve(attribute)
else
if attribute and @_isReferenceTypeAttribute(attribute)
@_resolveCustomReference(attribute)
.then (refId) ->
Promise.resolve
name: attribute.name
value:
id: refId
typeId: attribute.type.referenceTypeId
else Promise.resolve(attribute)
.then (attributes) ->
Promise.resolve _.extend(variant, { attributes })
else
Promise.resolve(variant)
_fetchAndResolveCustomPriceReferences: (variant) ->
if variant.prices and not _.isEmpty(variant.prices)
Promise.map variant.prices, (price) =>
if price and price.custom and price.custom.type and price.custom.type.id
service = @client.types
ref = { id: price.custom.type.id}
@_resolveReference(service, "types", ref, "key=\"#{ref.id}\"")
.then (refId) ->
price.custom.type.id = refId
Promise.resolve(price)
else
Promise.resolve(price)
.then (prices) ->
Promise.resolve _.extend(variant, { prices })
else
Promise.resolve(variant)
_fetchAndResolveCustomReferencesByVariant: (variant) ->
@_fetchAndResolveCustomAttributeReferences(variant)
.then (variant) =>
@_fetchAndResolveCustomPriceReferences(variant)
_resolveCustomReferenceSet: (attributeValue) ->
Promise.map attributeValue, (referenceObject) =>
@_resolveCustomReference(referenceObject)
_isReferenceTypeAttribute: (attribute) ->
_.has(attribute, 'type') and attribute.type.name is 'reference'
_resolveCustomReference: (referenceObject) ->
service = switch referenceObject.type.referenceTypeId
when 'product' then @client.productProjections
# TODO: map also other references
refKey = referenceObject.type.referenceTypeId
ref = _.deepClone referenceObject
ref.id = referenceObject.value
predicate = referenceObject._custom.predicate
@_resolveReference service, refKey, ref, predicate
_resolveProductCategories: (cats) ->
new Promise (resolve, reject) =>
if _.isEmpty(cats)
resolve()
else
Promise.all cats.map (cat) =>
@_resolveReference(@client.categories, 'categories', cat, "externalId=\"#{cat.id}\"")
.then (result) -> resolve(result.filter (c) -> c)
.catch (err) -> reject(err)
_resolveReference: (service, refKey, ref, predicate) ->
new Promise (resolve, reject) =>
if not ref
resolve()
if not @_cache[refKey]
@_cache[refKey] = {}
if @_cache[refKey][ref.id]
resolve(@_cache[refKey][ref.id].id)
else
request = service.where(predicate)
if refKey is 'PI:KEY:<KEY>END_PI'
request.staged(true)
request.fetch()
.then (result) =>
if result.body.count is 0
reject "Didn't find any match while resolving #{refKey} (#{predicate})"
else
if _.size(result.body.results) > 1
@logger.warn "Found more than 1 #{refKey} for #{ref.id}"
if _.isEmpty(result.body.results)
reject "Inconsistency between body.count and body.results.length. Result is #{JSON.stringify(result)}"
@_cache[refKey][ref.id] = result.body.results[0]
@_cache[refKey][result.body.results[0].id] = result.body.results[0]
resolve(result.body.results[0].id)
module.exports = ProductImport
|
[
{
"context": "op=\"author\">\n <meta itemprop=\"name\" content=\"Mr. Bees\" />\n <meta itemprop=\"url\" content=\"htt",
"end": 1874,
"score": 0.5682551860809326,
"start": 1872,
"tag": "NAME",
"value": "Mr"
},
{
"context": "\"author\">\n <meta itemprop=\"name\" content=... | allUtils/TheDrang/Aloha-Editor-master/Aloha-Editor-master/src/plugins/oer/media-embed/lib/media-embed-plugin.coffee | sunjerry019/sites | 0 | define [
'aloha'
'aloha/plugin'
'jquery'
'aloha/ephemera'
'ui/ui'
'ui/button'
'figure/figure-plugin'
'semanticblock/semanticblock-plugin'
'css!media-embed/css/media-embed-plugin.css'], (Aloha, Plugin, jQuery, Ephemera, UI, Button, Figure, semanticBlock) ->
DIALOG = '''
<div id="mediaEmbedDialog" class="modal hide fade" tabindex="-1" role="dialog" data-backdrop="false">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Add video, slides or other media</h3>
</div>
<div class="modal-body">
<form>
<label style="display: inline-block">
URL:
<input type="text" name="videoUrl" size="90">
</label>
<button class="btn">Go</button>
<div class="text-error hide">
We could not determine how to include the media. Please check the URL for the media and try again or cancel.
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal">Cancel</button>
</div>
</div>
'''
CONFIRM_DIALOG = '''
<div id="mediaConfirmEmbedDialog" class="modal hide fade" tabindex="-1" role="dialog" data-backdrop="false">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Add video, slides or other media</h3>
</div>
<div class="modal-body">
<div class="embed-preview"></div>
</div>
<div class="modal-footer">
<button class="btn cancel">Back</button>
<button class="btn primary embed">Insert Now</button>
</div>
</div>
'''
TEMPLATE = '''
<figure>
<div data-type="title"></div>
<div data-type="alternates">
</div>
<meta itemprop="url" content=""/>
<span itemscope="itemscope" itemtype="http://schema.org/Person" itemprop="author">
<meta itemprop="name" content="Mr. Bees" />
<meta itemprop="url" content="http://www.flickr.com/photos/bees/" />
</span>
<meta itemprop="accessibilityFeature" content="captions" />
<figcaption>
<a itemprop="url" href="">Source</a>: by
<a itemprop="author" href=""></a>
</figcaption>
</figure>
'''
endpoints =
default: 'http://noembed.com/embed'
#vimeo: 'http://vimeo.com/api/oembed.json'
#slideshare: 'http://www.slideshare.net/api/oembed/2'
#flickr: 'http://www.flickr.com/services/oembed'
embed = Plugin.create 'mediaEmbed',
placeholder: null # Keep track of an inserted place holder
ignore: '[data-type="title"],[data-type="alternates"],.noembed-embed,.noembed-embed *'
create: (thing) ->
$thing = $(TEMPLATE)
$thing.find('[data-type="title"]').text(thing.title)
$thing.find('[itemprop="url"]').attr('content', thing.url)
$thing.find('[itemprop="author"] [itemprop="name"]').attr('content', thing.author)
$thing.find('[itemprop="author"] [itemprop="url"]').attr('content', thing.authorUrl)
$thing.find('a[itemprop="author"]').attr('href', thing.authorUrl)
$thing.find('a[itemprop="author"]').text(thing.author)
$thing.find('figcaption').append(thing.caption)
$thing.find('[data-type="alternates"]').html(thing.html)
$caption = $thing.find('figcaption').remove()
$figure = Figure.insertOverPlaceholder($thing.contents(), @placeholder)
@placeholder = null
$figure.find('figcaption').find('.aloha-editable').html($caption.contents())
confirm: (thing) =>
$dialog = $('#mediaConfirmEmbedDialog')
$dialog = $(CONFIRM_DIALOG) if not $dialog.length
$dialog.find('.embed-preview').empty().append(thing.html)
if $dialog.find('iframe').attr('height') > 350
$dialog.find('iframe').attr('height', 350)
if $dialog.find('iframe').attr('width') > 500
$dialog.find('iframe').attr('width', 500)
$dialog.find('input,textarea').val('')
$dialog.find('input[name="figureTitle"]').val(thing.title) if thing.title
$dialog.find('.cancel').off('click').on 'click', (e) ->
e.preventDefault(true)
$dialog.modal 'hide'
embed.showDialog()
$dialog.find('.embed').off('.embed').on 'click', (e) ->
e.preventDefault(true)
$dialog.modal 'hide'
embed.create
url: thing.url
html: thing.html
author: thing.author
authorUrl: thing.authorUrl
$dialog.find('[data-dismiss]').on 'click', (e) ->
embed.placeholder.remove()
embed.placeholder = null
$dialog.on 'keyup.dismiss.modal', (e) =>
if e.which == 27
@placeholder.remove()
@placeholder = null
$dialog.modal {show: true}
embedByUrl: (url) =>
bits = url.match(/(?:https?:\/\/)?(?:www\.)?([^\.]*)/)
promise = new $.Deferred()
if bits.length == 2
domain = bits[1]
endpoint = endpoints[domain] || endpoints['default']
$.ajax(
url: endpoint,
data: {format: 'json', url: url}
dataType: 'json'
)
.done (data) ->
if data.error
promise.reject()
else
promise.resolve()
embed.confirm
url: data.url || url
html: data.html
title: data.title
author: data.author_name
authorUrl: data.author_url
.fail () =>
promise.reject()
promise
showDialog: () ->
$dialog = $('#mediaEmbedDialog')
$dialog = $(DIALOG) if not $dialog.length
$dialog.find('.text-error').hide()
$dialog.find('input').val('')
$dialog.find('form').off('submit').submit (e) =>
e.preventDefault(true)
@embedByUrl($dialog.find('input[name="videoUrl"]').val())
.done ->
$dialog.modal 'hide'
.fail ->
$dialog.find('.text-error').show()
$dialog.find('[data-dismiss]').on 'click', (e) =>
@placeholder.remove()
@placeholder = null
$dialog.on 'keyup.dismiss.modal', (e) =>
if e.which == 27
@placeholder.remove()
@placeholder = null
$dialog.modal 'show'
init: () ->
# Add a listener
UI.adopt "insert-mediaEmbed", Button,
click: =>
@showDialog()
# For legacy toolbars
UI.adopt "insertMediaEmbed", Button,
click: =>
@placeholder = Figure.insertPlaceholder()
@showDialog()
semanticBlock.register(this)
| 117078 | define [
'aloha'
'aloha/plugin'
'jquery'
'aloha/ephemera'
'ui/ui'
'ui/button'
'figure/figure-plugin'
'semanticblock/semanticblock-plugin'
'css!media-embed/css/media-embed-plugin.css'], (Aloha, Plugin, jQuery, Ephemera, UI, Button, Figure, semanticBlock) ->
DIALOG = '''
<div id="mediaEmbedDialog" class="modal hide fade" tabindex="-1" role="dialog" data-backdrop="false">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Add video, slides or other media</h3>
</div>
<div class="modal-body">
<form>
<label style="display: inline-block">
URL:
<input type="text" name="videoUrl" size="90">
</label>
<button class="btn">Go</button>
<div class="text-error hide">
We could not determine how to include the media. Please check the URL for the media and try again or cancel.
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal">Cancel</button>
</div>
</div>
'''
CONFIRM_DIALOG = '''
<div id="mediaConfirmEmbedDialog" class="modal hide fade" tabindex="-1" role="dialog" data-backdrop="false">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Add video, slides or other media</h3>
</div>
<div class="modal-body">
<div class="embed-preview"></div>
</div>
<div class="modal-footer">
<button class="btn cancel">Back</button>
<button class="btn primary embed">Insert Now</button>
</div>
</div>
'''
TEMPLATE = '''
<figure>
<div data-type="title"></div>
<div data-type="alternates">
</div>
<meta itemprop="url" content=""/>
<span itemscope="itemscope" itemtype="http://schema.org/Person" itemprop="author">
<meta itemprop="name" content="<NAME>. <NAME>" />
<meta itemprop="url" content="http://www.flickr.com/photos/bees/" />
</span>
<meta itemprop="accessibilityFeature" content="captions" />
<figcaption>
<a itemprop="url" href="">Source</a>: by
<a itemprop="author" href=""></a>
</figcaption>
</figure>
'''
endpoints =
default: 'http://noembed.com/embed'
#vimeo: 'http://vimeo.com/api/oembed.json'
#slideshare: 'http://www.slideshare.net/api/oembed/2'
#flickr: 'http://www.flickr.com/services/oembed'
embed = Plugin.create 'mediaEmbed',
placeholder: null # Keep track of an inserted place holder
ignore: '[data-type="title"],[data-type="alternates"],.noembed-embed,.noembed-embed *'
create: (thing) ->
$thing = $(TEMPLATE)
$thing.find('[data-type="title"]').text(thing.title)
$thing.find('[itemprop="url"]').attr('content', thing.url)
$thing.find('[itemprop="author"] [itemprop="name"]').attr('content', thing.author)
$thing.find('[itemprop="author"] [itemprop="url"]').attr('content', thing.authorUrl)
$thing.find('a[itemprop="author"]').attr('href', thing.authorUrl)
$thing.find('a[itemprop="author"]').text(thing.author)
$thing.find('figcaption').append(thing.caption)
$thing.find('[data-type="alternates"]').html(thing.html)
$caption = $thing.find('figcaption').remove()
$figure = Figure.insertOverPlaceholder($thing.contents(), @placeholder)
@placeholder = null
$figure.find('figcaption').find('.aloha-editable').html($caption.contents())
confirm: (thing) =>
$dialog = $('#mediaConfirmEmbedDialog')
$dialog = $(CONFIRM_DIALOG) if not $dialog.length
$dialog.find('.embed-preview').empty().append(thing.html)
if $dialog.find('iframe').attr('height') > 350
$dialog.find('iframe').attr('height', 350)
if $dialog.find('iframe').attr('width') > 500
$dialog.find('iframe').attr('width', 500)
$dialog.find('input,textarea').val('')
$dialog.find('input[name="figureTitle"]').val(thing.title) if thing.title
$dialog.find('.cancel').off('click').on 'click', (e) ->
e.preventDefault(true)
$dialog.modal 'hide'
embed.showDialog()
$dialog.find('.embed').off('.embed').on 'click', (e) ->
e.preventDefault(true)
$dialog.modal 'hide'
embed.create
url: thing.url
html: thing.html
author: thing.author
authorUrl: thing.authorUrl
$dialog.find('[data-dismiss]').on 'click', (e) ->
embed.placeholder.remove()
embed.placeholder = null
$dialog.on 'keyup.dismiss.modal', (e) =>
if e.which == 27
@placeholder.remove()
@placeholder = null
$dialog.modal {show: true}
embedByUrl: (url) =>
bits = url.match(/(?:https?:\/\/)?(?:www\.)?([^\.]*)/)
promise = new $.Deferred()
if bits.length == 2
domain = bits[1]
endpoint = endpoints[domain] || endpoints['default']
$.ajax(
url: endpoint,
data: {format: 'json', url: url}
dataType: 'json'
)
.done (data) ->
if data.error
promise.reject()
else
promise.resolve()
embed.confirm
url: data.url || url
html: data.html
title: data.title
author: data.author_name
authorUrl: data.author_url
.fail () =>
promise.reject()
promise
showDialog: () ->
$dialog = $('#mediaEmbedDialog')
$dialog = $(DIALOG) if not $dialog.length
$dialog.find('.text-error').hide()
$dialog.find('input').val('')
$dialog.find('form').off('submit').submit (e) =>
e.preventDefault(true)
@embedByUrl($dialog.find('input[name="videoUrl"]').val())
.done ->
$dialog.modal 'hide'
.fail ->
$dialog.find('.text-error').show()
$dialog.find('[data-dismiss]').on 'click', (e) =>
@placeholder.remove()
@placeholder = null
$dialog.on 'keyup.dismiss.modal', (e) =>
if e.which == 27
@placeholder.remove()
@placeholder = null
$dialog.modal 'show'
init: () ->
# Add a listener
UI.adopt "insert-mediaEmbed", Button,
click: =>
@showDialog()
# For legacy toolbars
UI.adopt "insertMediaEmbed", Button,
click: =>
@placeholder = Figure.insertPlaceholder()
@showDialog()
semanticBlock.register(this)
| true | define [
'aloha'
'aloha/plugin'
'jquery'
'aloha/ephemera'
'ui/ui'
'ui/button'
'figure/figure-plugin'
'semanticblock/semanticblock-plugin'
'css!media-embed/css/media-embed-plugin.css'], (Aloha, Plugin, jQuery, Ephemera, UI, Button, Figure, semanticBlock) ->
DIALOG = '''
<div id="mediaEmbedDialog" class="modal hide fade" tabindex="-1" role="dialog" data-backdrop="false">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Add video, slides or other media</h3>
</div>
<div class="modal-body">
<form>
<label style="display: inline-block">
URL:
<input type="text" name="videoUrl" size="90">
</label>
<button class="btn">Go</button>
<div class="text-error hide">
We could not determine how to include the media. Please check the URL for the media and try again or cancel.
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal">Cancel</button>
</div>
</div>
'''
CONFIRM_DIALOG = '''
<div id="mediaConfirmEmbedDialog" class="modal hide fade" tabindex="-1" role="dialog" data-backdrop="false">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Add video, slides or other media</h3>
</div>
<div class="modal-body">
<div class="embed-preview"></div>
</div>
<div class="modal-footer">
<button class="btn cancel">Back</button>
<button class="btn primary embed">Insert Now</button>
</div>
</div>
'''
TEMPLATE = '''
<figure>
<div data-type="title"></div>
<div data-type="alternates">
</div>
<meta itemprop="url" content=""/>
<span itemscope="itemscope" itemtype="http://schema.org/Person" itemprop="author">
<meta itemprop="name" content="PI:NAME:<NAME>END_PI. PI:NAME:<NAME>END_PI" />
<meta itemprop="url" content="http://www.flickr.com/photos/bees/" />
</span>
<meta itemprop="accessibilityFeature" content="captions" />
<figcaption>
<a itemprop="url" href="">Source</a>: by
<a itemprop="author" href=""></a>
</figcaption>
</figure>
'''
endpoints =
default: 'http://noembed.com/embed'
#vimeo: 'http://vimeo.com/api/oembed.json'
#slideshare: 'http://www.slideshare.net/api/oembed/2'
#flickr: 'http://www.flickr.com/services/oembed'
embed = Plugin.create 'mediaEmbed',
placeholder: null # Keep track of an inserted place holder
ignore: '[data-type="title"],[data-type="alternates"],.noembed-embed,.noembed-embed *'
create: (thing) ->
$thing = $(TEMPLATE)
$thing.find('[data-type="title"]').text(thing.title)
$thing.find('[itemprop="url"]').attr('content', thing.url)
$thing.find('[itemprop="author"] [itemprop="name"]').attr('content', thing.author)
$thing.find('[itemprop="author"] [itemprop="url"]').attr('content', thing.authorUrl)
$thing.find('a[itemprop="author"]').attr('href', thing.authorUrl)
$thing.find('a[itemprop="author"]').text(thing.author)
$thing.find('figcaption').append(thing.caption)
$thing.find('[data-type="alternates"]').html(thing.html)
$caption = $thing.find('figcaption').remove()
$figure = Figure.insertOverPlaceholder($thing.contents(), @placeholder)
@placeholder = null
$figure.find('figcaption').find('.aloha-editable').html($caption.contents())
confirm: (thing) =>
$dialog = $('#mediaConfirmEmbedDialog')
$dialog = $(CONFIRM_DIALOG) if not $dialog.length
$dialog.find('.embed-preview').empty().append(thing.html)
if $dialog.find('iframe').attr('height') > 350
$dialog.find('iframe').attr('height', 350)
if $dialog.find('iframe').attr('width') > 500
$dialog.find('iframe').attr('width', 500)
$dialog.find('input,textarea').val('')
$dialog.find('input[name="figureTitle"]').val(thing.title) if thing.title
$dialog.find('.cancel').off('click').on 'click', (e) ->
e.preventDefault(true)
$dialog.modal 'hide'
embed.showDialog()
$dialog.find('.embed').off('.embed').on 'click', (e) ->
e.preventDefault(true)
$dialog.modal 'hide'
embed.create
url: thing.url
html: thing.html
author: thing.author
authorUrl: thing.authorUrl
$dialog.find('[data-dismiss]').on 'click', (e) ->
embed.placeholder.remove()
embed.placeholder = null
$dialog.on 'keyup.dismiss.modal', (e) =>
if e.which == 27
@placeholder.remove()
@placeholder = null
$dialog.modal {show: true}
embedByUrl: (url) =>
bits = url.match(/(?:https?:\/\/)?(?:www\.)?([^\.]*)/)
promise = new $.Deferred()
if bits.length == 2
domain = bits[1]
endpoint = endpoints[domain] || endpoints['default']
$.ajax(
url: endpoint,
data: {format: 'json', url: url}
dataType: 'json'
)
.done (data) ->
if data.error
promise.reject()
else
promise.resolve()
embed.confirm
url: data.url || url
html: data.html
title: data.title
author: data.author_name
authorUrl: data.author_url
.fail () =>
promise.reject()
promise
showDialog: () ->
$dialog = $('#mediaEmbedDialog')
$dialog = $(DIALOG) if not $dialog.length
$dialog.find('.text-error').hide()
$dialog.find('input').val('')
$dialog.find('form').off('submit').submit (e) =>
e.preventDefault(true)
@embedByUrl($dialog.find('input[name="videoUrl"]').val())
.done ->
$dialog.modal 'hide'
.fail ->
$dialog.find('.text-error').show()
$dialog.find('[data-dismiss]').on 'click', (e) =>
@placeholder.remove()
@placeholder = null
$dialog.on 'keyup.dismiss.modal', (e) =>
if e.which == 27
@placeholder.remove()
@placeholder = null
$dialog.modal 'show'
init: () ->
# Add a listener
UI.adopt "insert-mediaEmbed", Button,
click: =>
@showDialog()
# For legacy toolbars
UI.adopt "insertMediaEmbed", Button,
click: =>
@placeholder = Figure.insertPlaceholder()
@showDialog()
semanticBlock.register(this)
|
[
{
"context": "#\t> File Name: user.coffee\n#\t> Author: LY\n#\t> Mail: ly.franky@gmail.com\n#\t> Created Time: W",
"end": 41,
"score": 0.9979894161224365,
"start": 39,
"tag": "USERNAME",
"value": "LY"
},
{
"context": "\t> File Name: user.coffee\n#\t> Author: LY\n#\t> Mail: ly.franky@... | server/db/models/user.coffee | wiiliamking/miac-website | 0 | # > File Name: user.coffee
# > Author: LY
# > Mail: ly.franky@gmail.com
# > Created Time: Wednesday, November 19, 2014 PM03:15:46 CST
mongoose = require 'mongoose'
Schema = mongoose.Schema
ObjectId = Schema.Types.ObjectId
util = require '../../common/util.coffee'
UserSchema = new Schema
username: String
password: String
avatar: { type: String, default: 'default.jpg' }
email: String
status: { type: String, default: 'user' } # user or clubMember or admin
createArticles: [{ lastAccessTime: Date, id: ObjectId }]
createShares: [{ lastAccessTime: Date, id: ObjectId }]
createDiscuss: [{ lastAccessTime: Date, id: ObjectId }]
createAlbums: [{ lastAccessTime: Date, id: ObjectId }]
createWorks: [{ lastAccessTime: Date, id: ObjectId }]
UserModel = mongoose.model 'UserModel', UserSchema
###
* if not admin existed, then create a new administrator
* @param callback: the callback function that would execute when function ended
###
UserModel.createAdministrator = (callback)->
callback = callback or ->
UserModel.findOne { status: 'admin' }, (err, admin)->
if not admin
UserModel.create
username: 'admin'
password: util.encrypt 'miac-website'
email: 'ly.franky@gmail.com'
status: 'admin'
, callback
else
callback()
###
* create a user in UserModel with username, password and email
* @param username: the user's name(one and only)
* @param password: the user's password, should be encrypted before saving
* @param email: the user's email
* @param callback: the callback function that would execute when function ended
###
UserModel.createUser = (username, password, email, callback)->
UserModel.create
username: username
password: util.encrypt password
email: email
isAdmin: no
, callback
###
* update email of user
* find a user by userId and update email
* @param email: the email that would replace the old one
* @param userId: the user's id to update email
* @param callback: the callback function that would execute when function ended
###
UserModel.updateEmail = (email, userId, callback)->
UserModel.findOne { _id: userId }, (err, user)->
if user
user.email = email
user.save ->
callback()
###
* update password of user
* find a user by userId and update password
* @param password: the password that would replace the old one
* @param userId: the user's id to update password
* @param callback: the callback function that would execute when function ended
###
UserModel.updatePassword = (password, userId, callback)->
UserModel.findOne { _id: userId }, (err, user)->
if user
user.password = password
user.save ->
callback()
###
* update avatar of user
* find a user by userId and update avatar
* @param fileName: the file's name of avatar's image
* @param userId: the user's id to update avatar
* @param callback: the callback function that would execute when function ended
###
UserModel.updateAvatar = (fileName, userId, callback)->
UserModel.findOne { _id: userId }, (err, user)->
if user
user.avatar = fileName
user.save ->
callback()
###
* drop all the user in UserModel
* @param callback: the callback function that would execute when function ended
###
UserModel.drop = (callback)->
UserModel.remove {}, ->
callback()
module.exports = UserModel
| 110039 | # > File Name: user.coffee
# > Author: LY
# > Mail: <EMAIL>
# > Created Time: Wednesday, November 19, 2014 PM03:15:46 CST
mongoose = require 'mongoose'
Schema = mongoose.Schema
ObjectId = Schema.Types.ObjectId
util = require '../../common/util.coffee'
UserSchema = new Schema
username: String
password: <PASSWORD>
avatar: { type: String, default: 'default.jpg' }
email: String
status: { type: String, default: 'user' } # user or clubMember or admin
createArticles: [{ lastAccessTime: Date, id: ObjectId }]
createShares: [{ lastAccessTime: Date, id: ObjectId }]
createDiscuss: [{ lastAccessTime: Date, id: ObjectId }]
createAlbums: [{ lastAccessTime: Date, id: ObjectId }]
createWorks: [{ lastAccessTime: Date, id: ObjectId }]
UserModel = mongoose.model 'UserModel', UserSchema
###
* if not admin existed, then create a new administrator
* @param callback: the callback function that would execute when function ended
###
UserModel.createAdministrator = (callback)->
callback = callback or ->
UserModel.findOne { status: 'admin' }, (err, admin)->
if not admin
UserModel.create
username: 'admin'
password: util.encrypt '<PASSWORD>'
email: '<EMAIL>'
status: 'admin'
, callback
else
callback()
###
* create a user in UserModel with username, password and email
* @param username: the user's name(one and only)
* @param password: the user's password, should be encrypted before saving
* @param email: the user's email
* @param callback: the callback function that would execute when function ended
###
UserModel.createUser = (username, password, email, callback)->
UserModel.create
username: username
password: <PASSWORD>.encrypt <PASSWORD>
email: email
isAdmin: no
, callback
###
* update email of user
* find a user by userId and update email
* @param email: the email that would replace the old one
* @param userId: the user's id to update email
* @param callback: the callback function that would execute when function ended
###
UserModel.updateEmail = (email, userId, callback)->
UserModel.findOne { _id: userId }, (err, user)->
if user
user.email = email
user.save ->
callback()
###
* update password of user
* find a user by userId and update password
* @param password: the <PASSWORD> that would <PASSWORD> the <PASSWORD> one
* @param userId: the user's id to update password
* @param callback: the callback function that would execute when function ended
###
UserModel.updatePassword = (password, userId, callback)->
UserModel.findOne { _id: userId }, (err, user)->
if user
user.password = <PASSWORD>
user.save ->
callback()
###
* update avatar of user
* find a user by userId and update avatar
* @param fileName: the file's name of avatar's image
* @param userId: the user's id to update avatar
* @param callback: the callback function that would execute when function ended
###
UserModel.updateAvatar = (fileName, userId, callback)->
UserModel.findOne { _id: userId }, (err, user)->
if user
user.avatar = fileName
user.save ->
callback()
###
* drop all the user in UserModel
* @param callback: the callback function that would execute when function ended
###
UserModel.drop = (callback)->
UserModel.remove {}, ->
callback()
module.exports = UserModel
| true | # > File Name: user.coffee
# > Author: LY
# > Mail: PI:EMAIL:<EMAIL>END_PI
# > Created Time: Wednesday, November 19, 2014 PM03:15:46 CST
mongoose = require 'mongoose'
Schema = mongoose.Schema
ObjectId = Schema.Types.ObjectId
util = require '../../common/util.coffee'
UserSchema = new Schema
username: String
password: PI:PASSWORD:<PASSWORD>END_PI
avatar: { type: String, default: 'default.jpg' }
email: String
status: { type: String, default: 'user' } # user or clubMember or admin
createArticles: [{ lastAccessTime: Date, id: ObjectId }]
createShares: [{ lastAccessTime: Date, id: ObjectId }]
createDiscuss: [{ lastAccessTime: Date, id: ObjectId }]
createAlbums: [{ lastAccessTime: Date, id: ObjectId }]
createWorks: [{ lastAccessTime: Date, id: ObjectId }]
UserModel = mongoose.model 'UserModel', UserSchema
###
* if not admin existed, then create a new administrator
* @param callback: the callback function that would execute when function ended
###
UserModel.createAdministrator = (callback)->
callback = callback or ->
UserModel.findOne { status: 'admin' }, (err, admin)->
if not admin
UserModel.create
username: 'admin'
password: util.encrypt 'PI:PASSWORD:<PASSWORD>END_PI'
email: 'PI:EMAIL:<EMAIL>END_PI'
status: 'admin'
, callback
else
callback()
###
* create a user in UserModel with username, password and email
* @param username: the user's name(one and only)
* @param password: the user's password, should be encrypted before saving
* @param email: the user's email
* @param callback: the callback function that would execute when function ended
###
UserModel.createUser = (username, password, email, callback)->
UserModel.create
username: username
password: PI:PASSWORD:<PASSWORD>END_PI.encrypt PI:PASSWORD:<PASSWORD>END_PI
email: email
isAdmin: no
, callback
###
* update email of user
* find a user by userId and update email
* @param email: the email that would replace the old one
* @param userId: the user's id to update email
* @param callback: the callback function that would execute when function ended
###
UserModel.updateEmail = (email, userId, callback)->
UserModel.findOne { _id: userId }, (err, user)->
if user
user.email = email
user.save ->
callback()
###
* update password of user
* find a user by userId and update password
* @param password: the PI:PASSWORD:<PASSWORD>END_PI that would PI:PASSWORD:<PASSWORD>END_PI the PI:PASSWORD:<PASSWORD>END_PI one
* @param userId: the user's id to update password
* @param callback: the callback function that would execute when function ended
###
UserModel.updatePassword = (password, userId, callback)->
UserModel.findOne { _id: userId }, (err, user)->
if user
user.password = PI:PASSWORD:<PASSWORD>END_PI
user.save ->
callback()
###
* update avatar of user
* find a user by userId and update avatar
* @param fileName: the file's name of avatar's image
* @param userId: the user's id to update avatar
* @param callback: the callback function that would execute when function ended
###
UserModel.updateAvatar = (fileName, userId, callback)->
UserModel.findOne { _id: userId }, (err, user)->
if user
user.avatar = fileName
user.save ->
callback()
###
* drop all the user in UserModel
* @param callback: the callback function that would execute when function ended
###
UserModel.drop = (callback)->
UserModel.remove {}, ->
callback()
module.exports = UserModel
|
[
{
"context": "========================================\n# Author: Christian Ebeling\n# Copyright (c) 2018 Fraunhofer Institute for Alg",
"end": 153,
"score": 0.9998322129249573,
"start": 136,
"tag": "NAME",
"value": "Christian Ebeling"
}
] | grammars/bel.cson | cebel/atom-bel-language | 1 | # Syntax highlighting for BEL (Biological Expression Language)
# ============================================================
# Author: Christian Ebeling
# Copyright (c) 2018 Fraunhofer Institute for Algorithms and Scientific Computing SCAI
# BEL 1.0 and 2.0 grammar
scopeName: 'source.bel'
name: 'BEL'
fileTypes: ['bel']
foldingStartMarker: '' # A regular expression that checks for the start of a foldable area (such as `{`).
foldingStopMarker: '' # A regular expression that checks for the end of a foldable area (such as `}`). If both folding markers are matched in the same line, there will be no foldable area.
patterns: [
{
include: '#comments'
}
{
include: '#numbers'
}
{
include: '#strings'
}
{
include: '#keywords'
}
{
include: '#functions'
}
{
include: '#entities'
}
]
repository:
comments:
patterns: [
{
begin: '#'
end: '\\n'
name: 'comment.line.hash.bel'
}
]
numbers:
patterns: [
{
match: '\\b(([0-9]+\\.?[0-9]*)|(\\.[0-9]+))((E|e)(\\+|-)?[0-9]+)?\\b'
name: 'constant.numeric.bel'
}
]
strings:
patterns: [
{
begin: '"'
beginCaptures:
'0':
name: 'punctuation.definition.string.begin.bel'
end: '"(?!")'
endCaptures:
'0':
name: 'punctuation.definition.string.end.bel'
name: 'string.quoted.double.bel'
patterns: [
{
match: '\\\\'
name: 'constant.character.escape.bel'
}
]
}
]
keywords:
patterns: [
{
match: '( (->|=>|-\\||=\\||--|>>|:>|) )|\\b(increases|directlyIncreases|decreases|directlyDecreases|rateLimitingStepOf|causesNoChange|cnc|regulates|reg|negativeCorrelation|neg|positiveCorrelation|pos|association|orthologous|transcribedTo|translatedTo|hasMember|hasComponent|isA|subProcessOf|analogousTo|biomarkerFor|prognosticBiomarkerFor|actsIn|hasProduct|hasVariant|hasModification|reactantIn|translocates|includes|hasMembers|hasComponents)\\b'
name: 'keyword.relations.bel'
}
{
match: '^\\s*SET\\s+(DOCUMENT|Citation|Evidence)\\b'
name: 'keyword.set.bel'
}
{
match: '^\\s*(SET|DEFINE)\\s+(NAMESPACE|ANNOTATION)\\b'
name: 'keyword.set.bel'
}
{
match: '\\s+AS\\s+(URL|PATTERN)(?=\\s+")'
name: 'keyword.set.bel'
}
{
match: '\\s+AS\\s+LIST(?=\\s+\\{\\s*")'
name: 'keyword.set.bel'
}
{
match: '^\\s*SET\\s+(Name|Description|Version|Authors|ContactInfo|Copyright|Licenses)\\b'
name: 'constant.property.bel'
}
{
match: '^\\s*(SET|UNSET)\\b'
name: 'keyword.set.bel'
}
]
functions:
patterns: [
{
match: '\\b(function)\\s+(?:[^=]+=\\s*)?(\\w+)(?:\\s*\\(.*\\))?'
captures:
'1':
name: 'keyword.control.bel'
'2':
name: 'entity.name.function.bel'
name: 'meta.function.bel'
}
{
comment: 'BEL abundance functions'
match: '\\b(a|abundance|g|geneAbundance|m|microRNAAbundance|p|proteinAbundance|r|rnaAbundance|complex)\\b'
name: 'support.function.bel'
}
{
comment: 'Other functions'
match: '\\b(var|variant|cat|catalyticActivity|chap|chaperoneActivity|gtp|gtpBoundActivity|kinaseActivity|kin|pep|peptidaseActivity|phos|phosphataseActivity|ribo|ribosylationActivity|tscript|transcriptionalActivity|tport|transportActivity|act|molecularActivity|composite|cellSurfaceExpression|surf|reaction|rxn|degradation|deg|cellSecretion|sec|translocation|tloc|biologicalProcess|bp|pathology|path|molecularActivity|ma|activity|act|fusion|fus|location|loc|fragment|frag|proteinModification|pmod)\\b'
name: 'support.function.bel'
}
]
entities:
patterns: [
{
match: '(?<=(a|g|m|p|r)\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
{
match: '(?<=abundance\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
{
match: '(?<=geneAbundance\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
{
match: '(?<=microRNAAbundance\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
{
match: '(?<=proteinAbundance\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
{
match: '(?<=rnaAbundance\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
{
match: '(?<=complex\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
{
match: '(?<=path\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
{
match: '(?<=bp\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
]
| 105280 | # Syntax highlighting for BEL (Biological Expression Language)
# ============================================================
# Author: <NAME>
# Copyright (c) 2018 Fraunhofer Institute for Algorithms and Scientific Computing SCAI
# BEL 1.0 and 2.0 grammar
scopeName: 'source.bel'
name: 'BEL'
fileTypes: ['bel']
foldingStartMarker: '' # A regular expression that checks for the start of a foldable area (such as `{`).
foldingStopMarker: '' # A regular expression that checks for the end of a foldable area (such as `}`). If both folding markers are matched in the same line, there will be no foldable area.
patterns: [
{
include: '#comments'
}
{
include: '#numbers'
}
{
include: '#strings'
}
{
include: '#keywords'
}
{
include: '#functions'
}
{
include: '#entities'
}
]
repository:
comments:
patterns: [
{
begin: '#'
end: '\\n'
name: 'comment.line.hash.bel'
}
]
numbers:
patterns: [
{
match: '\\b(([0-9]+\\.?[0-9]*)|(\\.[0-9]+))((E|e)(\\+|-)?[0-9]+)?\\b'
name: 'constant.numeric.bel'
}
]
strings:
patterns: [
{
begin: '"'
beginCaptures:
'0':
name: 'punctuation.definition.string.begin.bel'
end: '"(?!")'
endCaptures:
'0':
name: 'punctuation.definition.string.end.bel'
name: 'string.quoted.double.bel'
patterns: [
{
match: '\\\\'
name: 'constant.character.escape.bel'
}
]
}
]
keywords:
patterns: [
{
match: '( (->|=>|-\\||=\\||--|>>|:>|) )|\\b(increases|directlyIncreases|decreases|directlyDecreases|rateLimitingStepOf|causesNoChange|cnc|regulates|reg|negativeCorrelation|neg|positiveCorrelation|pos|association|orthologous|transcribedTo|translatedTo|hasMember|hasComponent|isA|subProcessOf|analogousTo|biomarkerFor|prognosticBiomarkerFor|actsIn|hasProduct|hasVariant|hasModification|reactantIn|translocates|includes|hasMembers|hasComponents)\\b'
name: 'keyword.relations.bel'
}
{
match: '^\\s*SET\\s+(DOCUMENT|Citation|Evidence)\\b'
name: 'keyword.set.bel'
}
{
match: '^\\s*(SET|DEFINE)\\s+(NAMESPACE|ANNOTATION)\\b'
name: 'keyword.set.bel'
}
{
match: '\\s+AS\\s+(URL|PATTERN)(?=\\s+")'
name: 'keyword.set.bel'
}
{
match: '\\s+AS\\s+LIST(?=\\s+\\{\\s*")'
name: 'keyword.set.bel'
}
{
match: '^\\s*SET\\s+(Name|Description|Version|Authors|ContactInfo|Copyright|Licenses)\\b'
name: 'constant.property.bel'
}
{
match: '^\\s*(SET|UNSET)\\b'
name: 'keyword.set.bel'
}
]
functions:
patterns: [
{
match: '\\b(function)\\s+(?:[^=]+=\\s*)?(\\w+)(?:\\s*\\(.*\\))?'
captures:
'1':
name: 'keyword.control.bel'
'2':
name: 'entity.name.function.bel'
name: 'meta.function.bel'
}
{
comment: 'BEL abundance functions'
match: '\\b(a|abundance|g|geneAbundance|m|microRNAAbundance|p|proteinAbundance|r|rnaAbundance|complex)\\b'
name: 'support.function.bel'
}
{
comment: 'Other functions'
match: '\\b(var|variant|cat|catalyticActivity|chap|chaperoneActivity|gtp|gtpBoundActivity|kinaseActivity|kin|pep|peptidaseActivity|phos|phosphataseActivity|ribo|ribosylationActivity|tscript|transcriptionalActivity|tport|transportActivity|act|molecularActivity|composite|cellSurfaceExpression|surf|reaction|rxn|degradation|deg|cellSecretion|sec|translocation|tloc|biologicalProcess|bp|pathology|path|molecularActivity|ma|activity|act|fusion|fus|location|loc|fragment|frag|proteinModification|pmod)\\b'
name: 'support.function.bel'
}
]
entities:
patterns: [
{
match: '(?<=(a|g|m|p|r)\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
{
match: '(?<=abundance\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
{
match: '(?<=geneAbundance\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
{
match: '(?<=microRNAAbundance\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
{
match: '(?<=proteinAbundance\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
{
match: '(?<=rnaAbundance\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
{
match: '(?<=complex\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
{
match: '(?<=path\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
{
match: '(?<=bp\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
]
| true | # Syntax highlighting for BEL (Biological Expression Language)
# ============================================================
# Author: PI:NAME:<NAME>END_PI
# Copyright (c) 2018 Fraunhofer Institute for Algorithms and Scientific Computing SCAI
# BEL 1.0 and 2.0 grammar
scopeName: 'source.bel'
name: 'BEL'
fileTypes: ['bel']
foldingStartMarker: '' # A regular expression that checks for the start of a foldable area (such as `{`).
foldingStopMarker: '' # A regular expression that checks for the end of a foldable area (such as `}`). If both folding markers are matched in the same line, there will be no foldable area.
patterns: [
{
include: '#comments'
}
{
include: '#numbers'
}
{
include: '#strings'
}
{
include: '#keywords'
}
{
include: '#functions'
}
{
include: '#entities'
}
]
repository:
comments:
patterns: [
{
begin: '#'
end: '\\n'
name: 'comment.line.hash.bel'
}
]
numbers:
patterns: [
{
match: '\\b(([0-9]+\\.?[0-9]*)|(\\.[0-9]+))((E|e)(\\+|-)?[0-9]+)?\\b'
name: 'constant.numeric.bel'
}
]
strings:
patterns: [
{
begin: '"'
beginCaptures:
'0':
name: 'punctuation.definition.string.begin.bel'
end: '"(?!")'
endCaptures:
'0':
name: 'punctuation.definition.string.end.bel'
name: 'string.quoted.double.bel'
patterns: [
{
match: '\\\\'
name: 'constant.character.escape.bel'
}
]
}
]
keywords:
patterns: [
{
match: '( (->|=>|-\\||=\\||--|>>|:>|) )|\\b(increases|directlyIncreases|decreases|directlyDecreases|rateLimitingStepOf|causesNoChange|cnc|regulates|reg|negativeCorrelation|neg|positiveCorrelation|pos|association|orthologous|transcribedTo|translatedTo|hasMember|hasComponent|isA|subProcessOf|analogousTo|biomarkerFor|prognosticBiomarkerFor|actsIn|hasProduct|hasVariant|hasModification|reactantIn|translocates|includes|hasMembers|hasComponents)\\b'
name: 'keyword.relations.bel'
}
{
match: '^\\s*SET\\s+(DOCUMENT|Citation|Evidence)\\b'
name: 'keyword.set.bel'
}
{
match: '^\\s*(SET|DEFINE)\\s+(NAMESPACE|ANNOTATION)\\b'
name: 'keyword.set.bel'
}
{
match: '\\s+AS\\s+(URL|PATTERN)(?=\\s+")'
name: 'keyword.set.bel'
}
{
match: '\\s+AS\\s+LIST(?=\\s+\\{\\s*")'
name: 'keyword.set.bel'
}
{
match: '^\\s*SET\\s+(Name|Description|Version|Authors|ContactInfo|Copyright|Licenses)\\b'
name: 'constant.property.bel'
}
{
match: '^\\s*(SET|UNSET)\\b'
name: 'keyword.set.bel'
}
]
functions:
patterns: [
{
match: '\\b(function)\\s+(?:[^=]+=\\s*)?(\\w+)(?:\\s*\\(.*\\))?'
captures:
'1':
name: 'keyword.control.bel'
'2':
name: 'entity.name.function.bel'
name: 'meta.function.bel'
}
{
comment: 'BEL abundance functions'
match: '\\b(a|abundance|g|geneAbundance|m|microRNAAbundance|p|proteinAbundance|r|rnaAbundance|complex)\\b'
name: 'support.function.bel'
}
{
comment: 'Other functions'
match: '\\b(var|variant|cat|catalyticActivity|chap|chaperoneActivity|gtp|gtpBoundActivity|kinaseActivity|kin|pep|peptidaseActivity|phos|phosphataseActivity|ribo|ribosylationActivity|tscript|transcriptionalActivity|tport|transportActivity|act|molecularActivity|composite|cellSurfaceExpression|surf|reaction|rxn|degradation|deg|cellSecretion|sec|translocation|tloc|biologicalProcess|bp|pathology|path|molecularActivity|ma|activity|act|fusion|fus|location|loc|fragment|frag|proteinModification|pmod)\\b'
name: 'support.function.bel'
}
]
entities:
patterns: [
{
match: '(?<=(a|g|m|p|r)\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
{
match: '(?<=abundance\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
{
match: '(?<=geneAbundance\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
{
match: '(?<=microRNAAbundance\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
{
match: '(?<=proteinAbundance\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
{
match: '(?<=rnaAbundance\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
{
match: '(?<=complex\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
{
match: '(?<=path\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
{
match: '(?<=bp\\()[A-Za-z0-9_]+\\s*(?:)'
name: 'variable.language.bel'
}
]
|
[
{
"context": "t here\t\nNotification_Text = new TextLayer\n\ttext: \"Charlie Pace\"\n\tfontFamily: \"Roboto\"\n\tfontWeight: 500\n\tfontSize",
"end": 2387,
"score": 0.9998750686645508,
"start": 2375,
"tag": "NAME",
"value": "Charlie Pace"
}
] | Android-Components/Notifications/Notification.coffee | iamkeeler/UXTOOLTIME-Framer | 4 | plugin.run = (contents, options) ->
"""
#{contents}
# <fold>
#Notification
Notification = new Layer
width: Screen.width
height: 80
y: -180
shadowY: 2
shadowBlur: 2
shadowSpread: 0
shadowColor: "rgba(0,0,0,0.24)"
shadowY: 0
shadowBlur: 2
shadowSpread: 0
shadowColor: "rgba(0,0,0,0.12)"
backgroundColor: "#fff"
#Initial animation
Notification.animate
y: 0
options:
delay: 1
curve: Bezier.easeInOut
time: 1.5
#Change App Icon here
App_Icon = new Layer
html: '<svg id="message" data-name="message" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15 12.85"><title>message</title><path d="M542.71,530.15H529l2.15,3.93v7.71a1.22,1.22,0,0,0,1.28,1.21h10.28a1.23,1.23,0,0,0,1.29-1.21V531.51A1.35,1.35,0,0,0,542.71,530.15Zm-9,9.69h5v-1h-5Zm0-3h7v-1h-7Zm0-3h8v-1h-8Z" transform="translate(-529 -530.15)" style="fill:#147bc1;fill-rule:evenodd"/></svg>'
height: 11
width: 13
x: Align.left 14
y: 15
backgroundColor: ""
parent: Notification
#Change App Title here
App_Title = new TextLayer
text: "Messenger"
fontFamily: "Roboto"
fontWeight: 500
fontSize: 11
letterSpacing: -0.1
x: Align.left 35
y: 13
color: "#007BC3"
parent: Notification
dotdivider = new TextLayer
text: "•"
x: Align.left 50
fontFamily: "Roboto"
fontWeight: 500
fontSize: 8
letterSpacing: -0.1
x: Align.right 6
y: 1
color: "rgba(0,0,0,0.54)"
parent: App_Title
time = new TextLayer
text: "now"
x: Align.left 50
fontFamily: "Roboto"
fontWeight: 500
fontSize: 11
letterSpacing: -0.1
x: Align.left 5
y: -1
color: "rgba(0,0,0,0.54)"
parent: dotdivider
dropdown_arrow = new Layer
html: '<svg id="dropdownarrow" data-name="dropdownarrow" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 7 4.32"><title>dropdownarrow</title><polygon points="0.82 0 3.5 2.67 6.18 0 7 0.82 3.5 4.32 0 0.82 0.82 0" style="fill:#147bc1;fill-rule:evenodd; opacity: 1.0"/></svg>'
height: 4
width: 6
x: Align.right 10
y: 5
opacity: 1
backgroundColor: ""
parent: time
dropdownhotspot = new Layer
width: 50
height: 32
y: Align.center
x: -10
backgroundColor: ""
parent: time
dropdown_arrow.states.up =
rotation: 180
animationOptions:
curve: "spring"
time: 0.1
dropdown_arrow.states.down =
rotation: 0
animationOptions:
curve: "spring"
time: 0.1
delete dropdown_arrow.states.default
#Change title text here
Notification_Text = new TextLayer
text: "Charlie Pace"
fontFamily: "Roboto"
fontWeight: 500
fontSize: 12
x: Align.left 14
y: 34
color: "#1C1C1C"
parent: Notification
#Change Subtext here
Notification_Subtext = new TextLayer
text: "Do you want to go see a movie tonight?"
fontFamily: "Roboto"
fontWeight: 500
fontSize: 12
x: Align.left 14
y: 52
color: "#rgba(0,0,0,0.54)"
parent: Notification
#Change Avatar here
Avatar = new Layer
width: 35
height: 35
borderRadius: 100
x: Align.right -14
y: Align.bottom -10
parent: Notification
#Action Buttons
NotificationButtonArea = new Layer
height: 50
width: Notification.width
y: Align.bottom
backgroundColor: "#EEEEEE"
opacity: 0.0
parent: Notification
Dialog_ActionButton1 = new TextLayer
text: "REPLY"
fontFamily: "Roboto"
fontWeight: 700
fontSize: 12
x: Align.left 13
y: Align.bottom -18
textAlign: "left"
color: "rgba(54,151,241,1)"
parent: NotificationButtonArea
NotificationButtonArea.states.slide =
y: Align.bottom 49
opacity: 1.0
animationOptions:
curve: "spring"
time: 0.1
NotificationButtonArea.states.slideup =
y: Align.bottom
opacity: 0.0
animationOptions:
curve: "spring"
time: 0.1
Dialog_ActionButton2 = new TextLayer
text: "ARCHIVE"
fontFamily: "Roboto"
fontWeight: 700
fontSize: 12
x: Align.left 70
y: Align.bottom -18
textAlign: "left"
color: "rgba(54,151,241,1)"
parent: NotificationButtonArea
NotificationButtonArea.bringToFront()
Notification.bringToFront()
Notification.placeBefore(NotificationButtonArea)
NotificationButtonArea.states.switchInstant "slide"
dropdown_arrow.states.switchInstant "up"
#swipe down on Notification to show actions
Notification.onSwipeDown ->
NotificationButtonArea.sendToBack()
NotificationButtonArea.animate("slide")
Notification.height= 80
dropdown_arrow.rotation= 180
dropdown_arrow.stateSwitch("up1")
#tap on the chevron at the top to show/hide actions
dropdownhotspot.onTap ->
NotificationButtonArea.stateCycle("slide", "slideup")
Notification.height= 80
dropdown_arrow.stateCycle("up", "down")
#hide notification after tapping action buttons
NotificationButtonArea.onTap ->
Notification.animate
y: -180
options:
curve: Bezier.easeInOut
time: .5
# </fold>
"""
| 119985 | plugin.run = (contents, options) ->
"""
#{contents}
# <fold>
#Notification
Notification = new Layer
width: Screen.width
height: 80
y: -180
shadowY: 2
shadowBlur: 2
shadowSpread: 0
shadowColor: "rgba(0,0,0,0.24)"
shadowY: 0
shadowBlur: 2
shadowSpread: 0
shadowColor: "rgba(0,0,0,0.12)"
backgroundColor: "#fff"
#Initial animation
Notification.animate
y: 0
options:
delay: 1
curve: Bezier.easeInOut
time: 1.5
#Change App Icon here
App_Icon = new Layer
html: '<svg id="message" data-name="message" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15 12.85"><title>message</title><path d="M542.71,530.15H529l2.15,3.93v7.71a1.22,1.22,0,0,0,1.28,1.21h10.28a1.23,1.23,0,0,0,1.29-1.21V531.51A1.35,1.35,0,0,0,542.71,530.15Zm-9,9.69h5v-1h-5Zm0-3h7v-1h-7Zm0-3h8v-1h-8Z" transform="translate(-529 -530.15)" style="fill:#147bc1;fill-rule:evenodd"/></svg>'
height: 11
width: 13
x: Align.left 14
y: 15
backgroundColor: ""
parent: Notification
#Change App Title here
App_Title = new TextLayer
text: "Messenger"
fontFamily: "Roboto"
fontWeight: 500
fontSize: 11
letterSpacing: -0.1
x: Align.left 35
y: 13
color: "#007BC3"
parent: Notification
dotdivider = new TextLayer
text: "•"
x: Align.left 50
fontFamily: "Roboto"
fontWeight: 500
fontSize: 8
letterSpacing: -0.1
x: Align.right 6
y: 1
color: "rgba(0,0,0,0.54)"
parent: App_Title
time = new TextLayer
text: "now"
x: Align.left 50
fontFamily: "Roboto"
fontWeight: 500
fontSize: 11
letterSpacing: -0.1
x: Align.left 5
y: -1
color: "rgba(0,0,0,0.54)"
parent: dotdivider
dropdown_arrow = new Layer
html: '<svg id="dropdownarrow" data-name="dropdownarrow" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 7 4.32"><title>dropdownarrow</title><polygon points="0.82 0 3.5 2.67 6.18 0 7 0.82 3.5 4.32 0 0.82 0.82 0" style="fill:#147bc1;fill-rule:evenodd; opacity: 1.0"/></svg>'
height: 4
width: 6
x: Align.right 10
y: 5
opacity: 1
backgroundColor: ""
parent: time
dropdownhotspot = new Layer
width: 50
height: 32
y: Align.center
x: -10
backgroundColor: ""
parent: time
dropdown_arrow.states.up =
rotation: 180
animationOptions:
curve: "spring"
time: 0.1
dropdown_arrow.states.down =
rotation: 0
animationOptions:
curve: "spring"
time: 0.1
delete dropdown_arrow.states.default
#Change title text here
Notification_Text = new TextLayer
text: "<NAME>"
fontFamily: "Roboto"
fontWeight: 500
fontSize: 12
x: Align.left 14
y: 34
color: "#1C1C1C"
parent: Notification
#Change Subtext here
Notification_Subtext = new TextLayer
text: "Do you want to go see a movie tonight?"
fontFamily: "Roboto"
fontWeight: 500
fontSize: 12
x: Align.left 14
y: 52
color: "#rgba(0,0,0,0.54)"
parent: Notification
#Change Avatar here
Avatar = new Layer
width: 35
height: 35
borderRadius: 100
x: Align.right -14
y: Align.bottom -10
parent: Notification
#Action Buttons
NotificationButtonArea = new Layer
height: 50
width: Notification.width
y: Align.bottom
backgroundColor: "#EEEEEE"
opacity: 0.0
parent: Notification
Dialog_ActionButton1 = new TextLayer
text: "REPLY"
fontFamily: "Roboto"
fontWeight: 700
fontSize: 12
x: Align.left 13
y: Align.bottom -18
textAlign: "left"
color: "rgba(54,151,241,1)"
parent: NotificationButtonArea
NotificationButtonArea.states.slide =
y: Align.bottom 49
opacity: 1.0
animationOptions:
curve: "spring"
time: 0.1
NotificationButtonArea.states.slideup =
y: Align.bottom
opacity: 0.0
animationOptions:
curve: "spring"
time: 0.1
Dialog_ActionButton2 = new TextLayer
text: "ARCHIVE"
fontFamily: "Roboto"
fontWeight: 700
fontSize: 12
x: Align.left 70
y: Align.bottom -18
textAlign: "left"
color: "rgba(54,151,241,1)"
parent: NotificationButtonArea
NotificationButtonArea.bringToFront()
Notification.bringToFront()
Notification.placeBefore(NotificationButtonArea)
NotificationButtonArea.states.switchInstant "slide"
dropdown_arrow.states.switchInstant "up"
#swipe down on Notification to show actions
Notification.onSwipeDown ->
NotificationButtonArea.sendToBack()
NotificationButtonArea.animate("slide")
Notification.height= 80
dropdown_arrow.rotation= 180
dropdown_arrow.stateSwitch("up1")
#tap on the chevron at the top to show/hide actions
dropdownhotspot.onTap ->
NotificationButtonArea.stateCycle("slide", "slideup")
Notification.height= 80
dropdown_arrow.stateCycle("up", "down")
#hide notification after tapping action buttons
NotificationButtonArea.onTap ->
Notification.animate
y: -180
options:
curve: Bezier.easeInOut
time: .5
# </fold>
"""
| true | plugin.run = (contents, options) ->
"""
#{contents}
# <fold>
#Notification
Notification = new Layer
width: Screen.width
height: 80
y: -180
shadowY: 2
shadowBlur: 2
shadowSpread: 0
shadowColor: "rgba(0,0,0,0.24)"
shadowY: 0
shadowBlur: 2
shadowSpread: 0
shadowColor: "rgba(0,0,0,0.12)"
backgroundColor: "#fff"
#Initial animation
Notification.animate
y: 0
options:
delay: 1
curve: Bezier.easeInOut
time: 1.5
#Change App Icon here
App_Icon = new Layer
html: '<svg id="message" data-name="message" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15 12.85"><title>message</title><path d="M542.71,530.15H529l2.15,3.93v7.71a1.22,1.22,0,0,0,1.28,1.21h10.28a1.23,1.23,0,0,0,1.29-1.21V531.51A1.35,1.35,0,0,0,542.71,530.15Zm-9,9.69h5v-1h-5Zm0-3h7v-1h-7Zm0-3h8v-1h-8Z" transform="translate(-529 -530.15)" style="fill:#147bc1;fill-rule:evenodd"/></svg>'
height: 11
width: 13
x: Align.left 14
y: 15
backgroundColor: ""
parent: Notification
#Change App Title here
App_Title = new TextLayer
text: "Messenger"
fontFamily: "Roboto"
fontWeight: 500
fontSize: 11
letterSpacing: -0.1
x: Align.left 35
y: 13
color: "#007BC3"
parent: Notification
dotdivider = new TextLayer
text: "•"
x: Align.left 50
fontFamily: "Roboto"
fontWeight: 500
fontSize: 8
letterSpacing: -0.1
x: Align.right 6
y: 1
color: "rgba(0,0,0,0.54)"
parent: App_Title
time = new TextLayer
text: "now"
x: Align.left 50
fontFamily: "Roboto"
fontWeight: 500
fontSize: 11
letterSpacing: -0.1
x: Align.left 5
y: -1
color: "rgba(0,0,0,0.54)"
parent: dotdivider
dropdown_arrow = new Layer
html: '<svg id="dropdownarrow" data-name="dropdownarrow" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 7 4.32"><title>dropdownarrow</title><polygon points="0.82 0 3.5 2.67 6.18 0 7 0.82 3.5 4.32 0 0.82 0.82 0" style="fill:#147bc1;fill-rule:evenodd; opacity: 1.0"/></svg>'
height: 4
width: 6
x: Align.right 10
y: 5
opacity: 1
backgroundColor: ""
parent: time
dropdownhotspot = new Layer
width: 50
height: 32
y: Align.center
x: -10
backgroundColor: ""
parent: time
dropdown_arrow.states.up =
rotation: 180
animationOptions:
curve: "spring"
time: 0.1
dropdown_arrow.states.down =
rotation: 0
animationOptions:
curve: "spring"
time: 0.1
delete dropdown_arrow.states.default
#Change title text here
Notification_Text = new TextLayer
text: "PI:NAME:<NAME>END_PI"
fontFamily: "Roboto"
fontWeight: 500
fontSize: 12
x: Align.left 14
y: 34
color: "#1C1C1C"
parent: Notification
#Change Subtext here
Notification_Subtext = new TextLayer
text: "Do you want to go see a movie tonight?"
fontFamily: "Roboto"
fontWeight: 500
fontSize: 12
x: Align.left 14
y: 52
color: "#rgba(0,0,0,0.54)"
parent: Notification
#Change Avatar here
Avatar = new Layer
width: 35
height: 35
borderRadius: 100
x: Align.right -14
y: Align.bottom -10
parent: Notification
#Action Buttons
NotificationButtonArea = new Layer
height: 50
width: Notification.width
y: Align.bottom
backgroundColor: "#EEEEEE"
opacity: 0.0
parent: Notification
Dialog_ActionButton1 = new TextLayer
text: "REPLY"
fontFamily: "Roboto"
fontWeight: 700
fontSize: 12
x: Align.left 13
y: Align.bottom -18
textAlign: "left"
color: "rgba(54,151,241,1)"
parent: NotificationButtonArea
NotificationButtonArea.states.slide =
y: Align.bottom 49
opacity: 1.0
animationOptions:
curve: "spring"
time: 0.1
NotificationButtonArea.states.slideup =
y: Align.bottom
opacity: 0.0
animationOptions:
curve: "spring"
time: 0.1
Dialog_ActionButton2 = new TextLayer
text: "ARCHIVE"
fontFamily: "Roboto"
fontWeight: 700
fontSize: 12
x: Align.left 70
y: Align.bottom -18
textAlign: "left"
color: "rgba(54,151,241,1)"
parent: NotificationButtonArea
NotificationButtonArea.bringToFront()
Notification.bringToFront()
Notification.placeBefore(NotificationButtonArea)
NotificationButtonArea.states.switchInstant "slide"
dropdown_arrow.states.switchInstant "up"
#swipe down on Notification to show actions
Notification.onSwipeDown ->
NotificationButtonArea.sendToBack()
NotificationButtonArea.animate("slide")
Notification.height= 80
dropdown_arrow.rotation= 180
dropdown_arrow.stateSwitch("up1")
#tap on the chevron at the top to show/hide actions
dropdownhotspot.onTap ->
NotificationButtonArea.stateCycle("slide", "slideup")
Notification.height= 80
dropdown_arrow.stateCycle("up", "down")
#hide notification after tapping action buttons
NotificationButtonArea.onTap ->
Notification.animate
y: -180
options:
curve: Bezier.easeInOut
time: .5
# </fold>
"""
|
[
{
"context": "./Helpers/EmailHelper\": EmailHelper\n\t\t@user_id = \"mock-user-id\"\n\t\t@email = \"mock@example.com\"\n\t\t@callback = sino",
"end": 935,
"score": 0.9836840629577637,
"start": 923,
"tag": "USERNAME",
"value": "mock-user-id"
},
{
"context": "ailHelper\n\t\t@user_id = ... | test/unit/coffee/User/UserEmailsConfirmationHandlerTests.coffee | davidmehren/web-sharelatex | 0 | should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
sinon = require('sinon')
modulePath = path.join __dirname, "../../../../app/js/Features/User/UserEmailsConfirmationHandler"
expect = require("chai").expect
Errors = require "../../../../app/js/Features/Errors/Errors"
EmailHelper = require "../../../../app/js/Features/Helpers/EmailHelper"
describe "UserEmailsConfirmationHandler", ->
beforeEach ->
@UserEmailsConfirmationHandler = SandboxedModule.require modulePath, requires:
"settings-sharelatex": @settings =
siteUrl: "emails.example.com"
"logger-sharelatex": @logger = { log: sinon.stub() }
"../Security/OneTimeTokenHandler": @OneTimeTokenHandler = {}
"../Errors/Errors": Errors
"./UserUpdater": @UserUpdater = {}
"../Email/EmailHandler": @EmailHandler = {}
"../Helpers/EmailHelper": EmailHelper
@user_id = "mock-user-id"
@email = "mock@example.com"
@callback = sinon.stub()
describe "sendConfirmationEmail", ->
beforeEach ->
@OneTimeTokenHandler.getNewToken = sinon.stub().yields(null, @token = "new-token")
@EmailHandler.sendEmail = sinon.stub().yields()
describe 'successfully', ->
beforeEach ->
@UserEmailsConfirmationHandler.sendConfirmationEmail @user_id, @email, @callback
it "should generate a token for the user which references their id and email", ->
@OneTimeTokenHandler.getNewToken
.calledWith(
'email_confirmation',
{@user_id, @email},
{ expiresIn: 365 * 24 * 60 * 60 }
)
.should.equal true
it 'should send an email to the user', ->
@EmailHandler.sendEmail
.calledWith('confirmEmail', {
to: @email,
confirmEmailUrl: 'emails.example.com/user/emails/confirm?token=new-token'
})
.should.equal true
it 'should call the callback', ->
@callback.called.should.equal true
describe 'with invalid email', ->
beforeEach ->
@UserEmailsConfirmationHandler.sendConfirmationEmail @user_id, '!"£$%^&*()', @callback
it 'should return an error', ->
@callback.calledWith(sinon.match.instanceOf(Error)).should.equal true
describe 'a custom template', ->
beforeEach ->
@UserEmailsConfirmationHandler.sendConfirmationEmail @user_id, @email, 'myCustomTemplate', @callback
it 'should send an email with the given template', ->
@EmailHandler.sendEmail
.calledWith('myCustomTemplate')
.should.equal true
describe "confirmEmailFromToken", ->
beforeEach ->
@OneTimeTokenHandler.getValueFromTokenAndExpire = sinon.stub().yields(
null,
{@user_id, @email}
)
@UserUpdater.confirmEmail = sinon.stub().yields()
describe "successfully", ->
beforeEach ->
@UserEmailsConfirmationHandler.confirmEmailFromToken @token = 'mock-token', @callback
it "should call getValueFromTokenAndExpire", ->
@OneTimeTokenHandler.getValueFromTokenAndExpire
.calledWith('email_confirmation', @token)
.should.equal true
it "should confirm the email of the user_id", ->
@UserUpdater.confirmEmail
.calledWith(@user_id, @email)
.should.equal true
it "should call the callback", ->
@callback.called.should.equal true
describe 'with an expired token', ->
beforeEach ->
@OneTimeTokenHandler.getValueFromTokenAndExpire = sinon.stub().yields(null, null)
@UserEmailsConfirmationHandler.confirmEmailFromToken @token = 'mock-token', @callback
it "should call the callback with a NotFoundError", ->
@callback.calledWith(sinon.match.instanceOf(Errors.NotFoundError)).should.equal true
describe 'with no user_id in the token', ->
beforeEach ->
@OneTimeTokenHandler.getValueFromTokenAndExpire = sinon.stub().yields(
null,
{@email}
)
@UserEmailsConfirmationHandler.confirmEmailFromToken @token = 'mock-token', @callback
it "should call the callback with a NotFoundError", ->
@callback.calledWith(sinon.match.instanceOf(Errors.NotFoundError)).should.equal true
describe 'with no email in the token', ->
beforeEach ->
@OneTimeTokenHandler.getValueFromTokenAndExpire = sinon.stub().yields(
null,
{@user_id}
)
@UserEmailsConfirmationHandler.confirmEmailFromToken @token = 'mock-token', @callback
it "should call the callback with a NotFoundError", ->
@callback.calledWith(sinon.match.instanceOf(Errors.NotFoundError)).should.equal true
| 74763 | should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
sinon = require('sinon')
modulePath = path.join __dirname, "../../../../app/js/Features/User/UserEmailsConfirmationHandler"
expect = require("chai").expect
Errors = require "../../../../app/js/Features/Errors/Errors"
EmailHelper = require "../../../../app/js/Features/Helpers/EmailHelper"
describe "UserEmailsConfirmationHandler", ->
beforeEach ->
@UserEmailsConfirmationHandler = SandboxedModule.require modulePath, requires:
"settings-sharelatex": @settings =
siteUrl: "emails.example.com"
"logger-sharelatex": @logger = { log: sinon.stub() }
"../Security/OneTimeTokenHandler": @OneTimeTokenHandler = {}
"../Errors/Errors": Errors
"./UserUpdater": @UserUpdater = {}
"../Email/EmailHandler": @EmailHandler = {}
"../Helpers/EmailHelper": EmailHelper
@user_id = "mock-user-id"
@email = "<EMAIL>"
@callback = sinon.stub()
describe "sendConfirmationEmail", ->
beforeEach ->
@OneTimeTokenHandler.getNewToken = sinon.stub().yields(null, @token = "new-token")
@EmailHandler.sendEmail = sinon.stub().yields()
describe 'successfully', ->
beforeEach ->
@UserEmailsConfirmationHandler.sendConfirmationEmail @user_id, @email, @callback
it "should generate a token for the user which references their id and email", ->
@OneTimeTokenHandler.getNewToken
.calledWith(
'email_confirmation',
{@user_id, @email},
{ expiresIn: 365 * 24 * 60 * 60 }
)
.should.equal true
it 'should send an email to the user', ->
@EmailHandler.sendEmail
.calledWith('confirmEmail', {
to: @email,
confirmEmailUrl: 'emails.example.com/user/emails/confirm?token=new-token'
})
.should.equal true
it 'should call the callback', ->
@callback.called.should.equal true
describe 'with invalid email', ->
beforeEach ->
@UserEmailsConfirmationHandler.sendConfirmationEmail @user_id, '!"£$%^&*()', @callback
it 'should return an error', ->
@callback.calledWith(sinon.match.instanceOf(Error)).should.equal true
describe 'a custom template', ->
beforeEach ->
@UserEmailsConfirmationHandler.sendConfirmationEmail @user_id, @email, 'myCustomTemplate', @callback
it 'should send an email with the given template', ->
@EmailHandler.sendEmail
.calledWith('myCustomTemplate')
.should.equal true
describe "confirmEmailFromToken", ->
beforeEach ->
@OneTimeTokenHandler.getValueFromTokenAndExpire = sinon.stub().yields(
null,
{@user_id, @email}
)
@UserUpdater.confirmEmail = sinon.stub().yields()
describe "successfully", ->
beforeEach ->
@UserEmailsConfirmationHandler.confirmEmailFromToken @token = 'mock-token', @callback
it "should call getValueFromTokenAndExpire", ->
@OneTimeTokenHandler.getValueFromTokenAndExpire
.calledWith('email_confirmation', @token)
.should.equal true
it "should confirm the email of the user_id", ->
@UserUpdater.confirmEmail
.calledWith(@user_id, @email)
.should.equal true
it "should call the callback", ->
@callback.called.should.equal true
describe 'with an expired token', ->
beforeEach ->
@OneTimeTokenHandler.getValueFromTokenAndExpire = sinon.stub().yields(null, null)
@UserEmailsConfirmationHandler.confirmEmailFromToken @token = 'mock-token', @callback
it "should call the callback with a NotFoundError", ->
@callback.calledWith(sinon.match.instanceOf(Errors.NotFoundError)).should.equal true
describe 'with no user_id in the token', ->
beforeEach ->
@OneTimeTokenHandler.getValueFromTokenAndExpire = sinon.stub().yields(
null,
{@email}
)
@UserEmailsConfirmationHandler.confirmEmailFromToken @token = '<KEY>-token', @callback
it "should call the callback with a NotFoundError", ->
@callback.calledWith(sinon.match.instanceOf(Errors.NotFoundError)).should.equal true
describe 'with no email in the token', ->
beforeEach ->
@OneTimeTokenHandler.getValueFromTokenAndExpire = sinon.stub().yields(
null,
{@user_id}
)
@UserEmailsConfirmationHandler.confirmEmailFromToken @token = 'mock-token', @callback
it "should call the callback with a NotFoundError", ->
@callback.calledWith(sinon.match.instanceOf(Errors.NotFoundError)).should.equal true
| true | should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
sinon = require('sinon')
modulePath = path.join __dirname, "../../../../app/js/Features/User/UserEmailsConfirmationHandler"
expect = require("chai").expect
Errors = require "../../../../app/js/Features/Errors/Errors"
EmailHelper = require "../../../../app/js/Features/Helpers/EmailHelper"
describe "UserEmailsConfirmationHandler", ->
beforeEach ->
@UserEmailsConfirmationHandler = SandboxedModule.require modulePath, requires:
"settings-sharelatex": @settings =
siteUrl: "emails.example.com"
"logger-sharelatex": @logger = { log: sinon.stub() }
"../Security/OneTimeTokenHandler": @OneTimeTokenHandler = {}
"../Errors/Errors": Errors
"./UserUpdater": @UserUpdater = {}
"../Email/EmailHandler": @EmailHandler = {}
"../Helpers/EmailHelper": EmailHelper
@user_id = "mock-user-id"
@email = "PI:EMAIL:<EMAIL>END_PI"
@callback = sinon.stub()
describe "sendConfirmationEmail", ->
beforeEach ->
@OneTimeTokenHandler.getNewToken = sinon.stub().yields(null, @token = "new-token")
@EmailHandler.sendEmail = sinon.stub().yields()
describe 'successfully', ->
beforeEach ->
@UserEmailsConfirmationHandler.sendConfirmationEmail @user_id, @email, @callback
it "should generate a token for the user which references their id and email", ->
@OneTimeTokenHandler.getNewToken
.calledWith(
'email_confirmation',
{@user_id, @email},
{ expiresIn: 365 * 24 * 60 * 60 }
)
.should.equal true
it 'should send an email to the user', ->
@EmailHandler.sendEmail
.calledWith('confirmEmail', {
to: @email,
confirmEmailUrl: 'emails.example.com/user/emails/confirm?token=new-token'
})
.should.equal true
it 'should call the callback', ->
@callback.called.should.equal true
describe 'with invalid email', ->
beforeEach ->
@UserEmailsConfirmationHandler.sendConfirmationEmail @user_id, '!"£$%^&*()', @callback
it 'should return an error', ->
@callback.calledWith(sinon.match.instanceOf(Error)).should.equal true
describe 'a custom template', ->
beforeEach ->
@UserEmailsConfirmationHandler.sendConfirmationEmail @user_id, @email, 'myCustomTemplate', @callback
it 'should send an email with the given template', ->
@EmailHandler.sendEmail
.calledWith('myCustomTemplate')
.should.equal true
describe "confirmEmailFromToken", ->
beforeEach ->
@OneTimeTokenHandler.getValueFromTokenAndExpire = sinon.stub().yields(
null,
{@user_id, @email}
)
@UserUpdater.confirmEmail = sinon.stub().yields()
describe "successfully", ->
beforeEach ->
@UserEmailsConfirmationHandler.confirmEmailFromToken @token = 'mock-token', @callback
it "should call getValueFromTokenAndExpire", ->
@OneTimeTokenHandler.getValueFromTokenAndExpire
.calledWith('email_confirmation', @token)
.should.equal true
it "should confirm the email of the user_id", ->
@UserUpdater.confirmEmail
.calledWith(@user_id, @email)
.should.equal true
it "should call the callback", ->
@callback.called.should.equal true
describe 'with an expired token', ->
beforeEach ->
@OneTimeTokenHandler.getValueFromTokenAndExpire = sinon.stub().yields(null, null)
@UserEmailsConfirmationHandler.confirmEmailFromToken @token = 'mock-token', @callback
it "should call the callback with a NotFoundError", ->
@callback.calledWith(sinon.match.instanceOf(Errors.NotFoundError)).should.equal true
describe 'with no user_id in the token', ->
beforeEach ->
@OneTimeTokenHandler.getValueFromTokenAndExpire = sinon.stub().yields(
null,
{@email}
)
@UserEmailsConfirmationHandler.confirmEmailFromToken @token = 'PI:KEY:<KEY>END_PI-token', @callback
it "should call the callback with a NotFoundError", ->
@callback.calledWith(sinon.match.instanceOf(Errors.NotFoundError)).should.equal true
describe 'with no email in the token', ->
beforeEach ->
@OneTimeTokenHandler.getValueFromTokenAndExpire = sinon.stub().yields(
null,
{@user_id}
)
@UserEmailsConfirmationHandler.confirmEmailFromToken @token = 'mock-token', @callback
it "should call the callback with a NotFoundError", ->
@callback.calledWith(sinon.match.instanceOf(Errors.NotFoundError)).should.equal true
|
[
{
"context": "AABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTNui8sowA",
"end": 613,
"score": 0.5365869998931885,
"start": 611,
"tag": "KEY",
"value": "AB"
},
{
"context": "EgAACxIB0t1+/AAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTNui8s... | bokehjs/src/coffee/tool/box_zoom_tool.coffee | csaid/bokeh | 1 |
define [
"underscore",
"backbone",
"./tool",
"./event_generators",
], (_, Backbone, Tool, EventGenerators) ->
TwoPointEventGenerator = EventGenerators.TwoPointEventGenerator
class BoxZoomToolView extends Tool.View
initialize: (options) ->
super(options)
bind_bokeh_events: () ->
super()
eventGeneratorClass: TwoPointEventGenerator
toolType: "BoxZoomTool"
evgen_options:
keyName: "ctrlKey"
buttonText: "Box Zoom"
buttonIcon: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAYAAAByDd+UAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTNui8sowAAAFKSURBVEiJ7ZZhecMgEIZhzwRUAhIigTmYhEiJg0mIhElAQiWkDlIH737saCnlgLTNr+37UyjHvbl8XBILGGut2VPAZfy2K6mgPwbkV0HGkzL/zPY4YAZWrlqAL+BgjLk9I6mhQMgT1gSM1LUCQ+QAt8AtAnyWeJL/vFSXrrkiUDa5TmDIq8jWhwQ6a0AA3wFzSbKxEhcrXTVgKF1tIdHldvbGReB7GmCt/WjBnlXeFr0enpI9tVPt5fecQtJxl4cSu0j8gvRbtj5w7U310HR5KLHxQRChoxwmJ2sRprdFr2g3fNQa75hWYdPDDLbK/LsAm9NcGhAqHhZgQ7buNUs2e9iCtbTJw2dhKlDzEDgK7NjyuHChvgYseggc5BDc9VsDGICpBlQ9fETNCvdUBD76LO2FjHcWFTxsfdO05sg8vpqmtELL/4fwi/UDzP86Q6mEI4kAAAAASUVORK5CYII="
cursor: "crosshair"
auto_deactivate: true
restrict_to_innercanvas: true
tool_events:
SetBasepoint: "_start_selecting"
UpdatingMouseMove: "_selecting"
DragEnd: "_dragend"
pause:()->
return null
view_coords: (sx, sy) ->
[vx, vy] = [
@plot_view.view_state.sx_to_vx(sx),
@plot_view.view_state.sy_to_vy(sy)
]
return [vx, vy]
_start_selecting: (e) ->
@plot_view.pause()
@trigger('startselect')
[vx, vy] = @view_coords(e.bokehX, e.bokehY)
@mset({'start_vx': vx, 'start_vy': vy, 'current_vx': null, 'current_vy': null})
@basepoint_set = true
_get_selection_range: ->
if @mget('select_x')
xrange = [@mget('start_vx'), @mget('current_vx')]
xrange = [_.min(xrange), _.max(xrange)]
else
xrange = null
if @mget('select_y')
yrange = [@mget('start_vy'), @mget('current_vy')]
yrange = [_.min(yrange), _.max(yrange)]
else
yrange = null
return [xrange, yrange]
_selecting: (e, x_, y_) ->
[vx, vy] = @view_coords(e.bokehX, e.bokehY)
@mset({'current_vx': vx, 'current_vy': vy})
[@xrange, @yrange] = @_get_selection_range()
@trigger('boxselect', @xrange, @yrange)
@plot_view.render_overlays(true)
return null
_dragend : () ->
@_select_data()
@basepoint_set = false
@plot_view.unpause()
@trigger('stopselect')
_select_data: () ->
if not @basepoint_set
return
[xstart, xend] = @plot_view.xmapper.v_map_from_target([@xrange[0], @xrange[1]])
[ystart, yend] = @plot_view.ymapper.v_map_from_target([@yrange[0], @yrange[1]])
zoom_info = {
xr: {start: xstart, end: xend}
yr: {start: ystart, end: yend}
}
@plot_view.update_range(zoom_info)
class BoxZoomTool extends Tool.Model
default_view: BoxZoomToolView
type: "BoxZoomTool"
defaults: () ->
return _.extend(super(), {
renderers: []
select_x: true
select_y: true
select_every_mousemove: false
data_source_options: {} # backbone options for save on datasource
})
display_defaults: () ->
super()
class BoxZoomTools extends Backbone.Collection
model: BoxZoomTool
return {
"Model": BoxZoomTool,
"Collection": new BoxZoomTools(),
"View": BoxZoomToolView,
}
| 191611 |
define [
"underscore",
"backbone",
"./tool",
"./event_generators",
], (_, Backbone, Tool, EventGenerators) ->
TwoPointEventGenerator = EventGenerators.TwoPointEventGenerator
class BoxZoomToolView extends Tool.View
initialize: (options) ->
super(options)
bind_bokeh_events: () ->
super()
eventGeneratorClass: TwoPointEventGenerator
toolType: "BoxZoomTool"
evgen_options:
keyName: "ctrlKey"
buttonText: "Box Zoom"
buttonIcon: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAYAAAByDd+UAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAA<KEY>x0RVh0U29mdHdhcmUAQWRvYmUgRmlyZX<KEY>vcmtzIENT<KEY>ui8<KEY>ow<KEY>UR<KEY>i<KEY>cMg<KEY>IZhzw<KEY>igTmYhEiJg0<KEY>Ih<KEY>iWkDlIH<KEY>CnlgLTNr+<KEY>j<KEY>8<KEY>2<KEY>2<KEY>mg<KEY>wb<KEY>z<KEY>jLk<KEY>Mg<KEY>g<KEY>AnyWe<KEY>w<KEY>Fz<KEY>GmCt<KEY>/Wj<KEY>0enpI9t<KEY>QtJxl4c<KEY>0j8gv<KEY>btj5w7<KEY>310HR5KLHxQRChoxwmJ2s<KEY>prdFr2g3fNQa75hWYdPDDLbK/LsAm9NcGhAqHhZgQ7buNUs2e9iCtbTJw2dhKlDzEDgK7NjyuHChvgYseggc5BDc9VsDGICpBlQ9fETNCvdUBD76LO2FjHcWFTxsfdO05sg8vpqmtELL/4fwi/UD<KEY>
cursor: "crosshair"
auto_deactivate: true
restrict_to_innercanvas: true
tool_events:
SetBasepoint: "_start_selecting"
UpdatingMouseMove: "_selecting"
DragEnd: "_dragend"
pause:()->
return null
view_coords: (sx, sy) ->
[vx, vy] = [
@plot_view.view_state.sx_to_vx(sx),
@plot_view.view_state.sy_to_vy(sy)
]
return [vx, vy]
_start_selecting: (e) ->
@plot_view.pause()
@trigger('startselect')
[vx, vy] = @view_coords(e.bokehX, e.bokehY)
@mset({'start_vx': vx, 'start_vy': vy, 'current_vx': null, 'current_vy': null})
@basepoint_set = true
_get_selection_range: ->
if @mget('select_x')
xrange = [@mget('start_vx'), @mget('current_vx')]
xrange = [_.min(xrange), _.max(xrange)]
else
xrange = null
if @mget('select_y')
yrange = [@mget('start_vy'), @mget('current_vy')]
yrange = [_.min(yrange), _.max(yrange)]
else
yrange = null
return [xrange, yrange]
_selecting: (e, x_, y_) ->
[vx, vy] = @view_coords(e.bokehX, e.bokehY)
@mset({'current_vx': vx, 'current_vy': vy})
[@xrange, @yrange] = @_get_selection_range()
@trigger('boxselect', @xrange, @yrange)
@plot_view.render_overlays(true)
return null
_dragend : () ->
@_select_data()
@basepoint_set = false
@plot_view.unpause()
@trigger('stopselect')
_select_data: () ->
if not @basepoint_set
return
[xstart, xend] = @plot_view.xmapper.v_map_from_target([@xrange[0], @xrange[1]])
[ystart, yend] = @plot_view.ymapper.v_map_from_target([@yrange[0], @yrange[1]])
zoom_info = {
xr: {start: xstart, end: xend}
yr: {start: ystart, end: yend}
}
@plot_view.update_range(zoom_info)
class BoxZoomTool extends Tool.Model
default_view: BoxZoomToolView
type: "BoxZoomTool"
defaults: () ->
return _.extend(super(), {
renderers: []
select_x: true
select_y: true
select_every_mousemove: false
data_source_options: {} # backbone options for save on datasource
})
display_defaults: () ->
super()
class BoxZoomTools extends Backbone.Collection
model: BoxZoomTool
return {
"Model": BoxZoomTool,
"Collection": new BoxZoomTools(),
"View": BoxZoomToolView,
}
| true |
define [
"underscore",
"backbone",
"./tool",
"./event_generators",
], (_, Backbone, Tool, EventGenerators) ->
TwoPointEventGenerator = EventGenerators.TwoPointEventGenerator
class BoxZoomToolView extends Tool.View
initialize: (options) ->
super(options)
bind_bokeh_events: () ->
super()
eventGeneratorClass: TwoPointEventGenerator
toolType: "BoxZoomTool"
evgen_options:
keyName: "ctrlKey"
buttonText: "Box Zoom"
buttonIcon: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAYAAAByDd+UAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAPI:KEY:<KEY>END_PIx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXPI:KEY:<KEY>END_PIvcmtzIENTPI:KEY:<KEY>END_PIui8PI:KEY:<KEY>END_PIowPI:KEY:<KEY>END_PIURPI:KEY:<KEY>END_PIiPI:KEY:<KEY>END_PIcMgPI:KEY:<KEY>END_PIIZhzwPI:KEY:<KEY>END_PIigTmYhEiJg0PI:KEY:<KEY>END_PIIhPI:KEY:<KEY>END_PIiWkDlIHPI:KEY:<KEY>END_PICnlgLTNr+PI:KEY:<KEY>END_PIjPI:KEY:<KEY>END_PI8PI:KEY:<KEY>END_PI2PI:KEY:<KEY>END_PI2PI:KEY:<KEY>END_PImgPI:KEY:<KEY>END_PIwbPI:KEY:<KEY>END_PIzPI:KEY:<KEY>END_PIjLkPI:KEY:<KEY>END_PIMgPI:KEY:<KEY>END_PIgPI:KEY:<KEY>END_PIAnyWePI:KEY:<KEY>END_PIwPI:KEY:<KEY>END_PIFzPI:KEY:<KEY>END_PIGmCtPI:KEY:<KEY>END_PI/WjPI:KEY:<KEY>END_PI0enpI9tPI:KEY:<KEY>END_PIQtJxl4cPI:KEY:<KEY>END_PI0j8gvPI:KEY:<KEY>END_PIbtj5w7PI:KEY:<KEY>END_PI310HR5KLHxQRChoxwmJ2sPI:KEY:<KEY>END_PIprdFr2g3fNQa75hWYdPDDLbK/LsAm9NcGhAqHhZgQ7buNUs2e9iCtbTJw2dhKlDzEDgK7NjyuHChvgYseggc5BDc9VsDGICpBlQ9fETNCvdUBD76LO2FjHcWFTxsfdO05sg8vpqmtELL/4fwi/UDPI:KEY:<KEY>END_PI
cursor: "crosshair"
auto_deactivate: true
restrict_to_innercanvas: true
tool_events:
SetBasepoint: "_start_selecting"
UpdatingMouseMove: "_selecting"
DragEnd: "_dragend"
pause:()->
return null
view_coords: (sx, sy) ->
[vx, vy] = [
@plot_view.view_state.sx_to_vx(sx),
@plot_view.view_state.sy_to_vy(sy)
]
return [vx, vy]
_start_selecting: (e) ->
@plot_view.pause()
@trigger('startselect')
[vx, vy] = @view_coords(e.bokehX, e.bokehY)
@mset({'start_vx': vx, 'start_vy': vy, 'current_vx': null, 'current_vy': null})
@basepoint_set = true
_get_selection_range: ->
if @mget('select_x')
xrange = [@mget('start_vx'), @mget('current_vx')]
xrange = [_.min(xrange), _.max(xrange)]
else
xrange = null
if @mget('select_y')
yrange = [@mget('start_vy'), @mget('current_vy')]
yrange = [_.min(yrange), _.max(yrange)]
else
yrange = null
return [xrange, yrange]
_selecting: (e, x_, y_) ->
[vx, vy] = @view_coords(e.bokehX, e.bokehY)
@mset({'current_vx': vx, 'current_vy': vy})
[@xrange, @yrange] = @_get_selection_range()
@trigger('boxselect', @xrange, @yrange)
@plot_view.render_overlays(true)
return null
_dragend : () ->
@_select_data()
@basepoint_set = false
@plot_view.unpause()
@trigger('stopselect')
_select_data: () ->
if not @basepoint_set
return
[xstart, xend] = @plot_view.xmapper.v_map_from_target([@xrange[0], @xrange[1]])
[ystart, yend] = @plot_view.ymapper.v_map_from_target([@yrange[0], @yrange[1]])
zoom_info = {
xr: {start: xstart, end: xend}
yr: {start: ystart, end: yend}
}
@plot_view.update_range(zoom_info)
class BoxZoomTool extends Tool.Model
default_view: BoxZoomToolView
type: "BoxZoomTool"
defaults: () ->
return _.extend(super(), {
renderers: []
select_x: true
select_y: true
select_every_mousemove: false
data_source_options: {} # backbone options for save on datasource
})
display_defaults: () ->
super()
class BoxZoomTools extends Backbone.Collection
model: BoxZoomTool
return {
"Model": BoxZoomTool,
"Collection": new BoxZoomTools(),
"View": BoxZoomToolView,
}
|
[
{
"context": " array for list of trigger phrases\n#\n# Author:\n# Morgan Wigmanich <okize123@gmail.com> (https://github.com/okize)\n\n",
"end": 276,
"score": 0.999884307384491,
"start": 260,
"tag": "NAME",
"value": "Morgan Wigmanich"
},
{
"context": "trigger phrases\n#\n# Author:\n... | src/businesscat.coffee | adrianpike/hubot-business-cat | 0 | # Description:
# Business cat is summoned when business jargon is used
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# business jargon - summons business cat
#
# Notes
# See jargon array for list of trigger phrases
#
# Author:
# Morgan Wigmanich <okize123@gmail.com> (https://github.com/okize)
images = require './data/images.json'
jargon = require './data/triggers.json'
regex = new RegExp jargon.join('|'), 'gi'
module.exports = (robot) ->
robot.hear regex, (msg) ->
msg.send msg.random images
| 196920 | # Description:
# Business cat is summoned when business jargon is used
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# business jargon - summons business cat
#
# Notes
# See jargon array for list of trigger phrases
#
# Author:
# <NAME> <<EMAIL>> (https://github.com/okize)
images = require './data/images.json'
jargon = require './data/triggers.json'
regex = new RegExp jargon.join('|'), 'gi'
module.exports = (robot) ->
robot.hear regex, (msg) ->
msg.send msg.random images
| true | # Description:
# Business cat is summoned when business jargon is used
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# business jargon - summons business cat
#
# Notes
# See jargon array for list of trigger phrases
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (https://github.com/okize)
images = require './data/images.json'
jargon = require './data/triggers.json'
regex = new RegExp jargon.join('|'), 'gi'
module.exports = (robot) ->
robot.hear regex, (msg) ->
msg.send msg.random images
|
[
{
"context": "Assay = Backbone.Model.extend\n\n entityName: 'Assay'\n entityNamePlural: 'Assays'\n idAttribute: 'a",
"end": 49,
"score": 0.9404688477516174,
"start": 46,
"tag": "NAME",
"value": "Ass"
},
{
"context": "xtend\n\n entityName: 'Assay'\n entityNamePlural: 'Assays'\n ... | src/glados/static/coffee/models/Assay.coffee | BNext-IQT/glados-frontend-chembl-main-interface | 33 | Assay = Backbone.Model.extend
entityName: 'Assay'
entityNamePlural: 'Assays'
idAttribute: 'assay_chembl_id'
defaults:
fetch_from_elastic: true
indexName: 'chembl_assay'
initialize: ->
id = @get('id')
id ?= @get('assay_chembl_id')
@set('id', id)
@set('assay_chembl_id', id)
if @get('fetch_from_elastic')
@url = "#{glados.Settings.ES_PROXY_API_BASE_URL}/es_data/get_es_document/#{Assay.ES_INDEX}/#{id}"
else
@url = glados.Settings.WS_BASE_URL + 'assay/' + id + '.json'
parse: (response) ->
# get data when it comes from elastic
if response._source?
objData = response._source
else
objData = response
objData.target = response.assay_chembl_id
objData.report_card_url = Assay.get_report_card_url(objData.assay_chembl_id )
objData.document_link = Document.get_report_card_url(objData.document_chembl_id)
objData.tissue_link = glados.models.Tissue.get_report_card_url(objData.tissue_chembl_id)
filterForCompounds = '_metadata.related_assays.all_chembl_ids:' + objData.assay_chembl_id
objData.compounds_url = Compound.getCompoundsListURL(filterForCompounds)
filterForActivities = 'assay_chembl_id:' + objData.assay_chembl_id
objData.activities_url = Activity.getActivitiesListURL(filterForActivities)
objData.target_link = Target.get_report_card_url(objData.target_chembl_id)
objData.cell_link = CellLine.get_report_card_url(objData.cell_chembl_id)
#check if it is bindingdb and add corresponding link
isFromBindingDB = objData.src_id == 37
if isFromBindingDB
assayIDParts = objData.src_assay_id.split('_')
byAssayID = assayIDParts[1]
entryID = assayIDParts[0]
bindingDBLink = "https://www.bindingdb.org/jsp/dbsearch/assay.jsp?assayid=#{byAssayID}&entryid=#{entryID}"
objData.binding_db_link = bindingDBLink
objData.binding_db_link_text = entryID
if objData._metadata.document_data.doi?
objData.reference_link = 'http://dx.doi.org/' + encodeURIComponent(objData._metadata.document_data.doi)
if objData._metadata.document_data.pubmed_id?
objData.pubmed_link = 'https://www.ncbi.nlm.nih.gov/pubmed/' + \
encodeURIComponent(objData._metadata.document_data.pubmed_id)
return objData;
# Constant definition for ReportCardEntity model functionalities
_.extend(Assay, glados.models.base.ReportCardEntity)
Assay.color = 'amber'
Assay.reportCardPath = 'assay_report_card/'
Assay.getAssaysListURL = (filter, isFullState=false, fragmentOnly=false) ->
if isFullState
filter = btoa(JSON.stringify(filter))
return glados.Settings.ENTITY_BROWSERS_URL_GENERATOR
fragment_only: fragmentOnly
entity: 'assays'
filter: encodeURIComponent(filter) unless not filter?
is_full_state: isFullState
Assay.ES_INDEX = 'chembl_assay'
Assay.INDEX_NAME = Assay.ES_INDEX
Assay.PROPERTIES_VISUAL_CONFIG = {
'assay_chembl_id': {
link_base: 'report_card_url'
}
'_metadata.related_compounds.count': {
link_base: 'compounds_url'
on_click: AssayReportCardApp.initMiniHistogramFromFunctionLink
function_constant_parameters: ['compounds']
function_parameters: ['assay_chembl_id']
function_key: 'assay_num_compounds'
function_link: true
execute_on_render: true
format_class: 'number-cell-center'
}
'_metadata.related_activities.count': {
link_base: 'activities_url'
on_click: AssayReportCardApp.initMiniHistogramFromFunctionLink
function_parameters: ['assay_chembl_id']
function_constant_parameters: ['activities']
function_key: 'assay_bioactivities'
function_link: true
execute_on_render: true
format_class: 'number-cell-center'
}
'document_chembl_id': {
link_base: 'document_link'
}
'tissue_chembl_id': {
link_base: 'tissue_link'
}
'_metadata.document_data.pubmed_id': {
link_base: 'pubmed_link'
}
'_metadata.document_data.doi': {
link_base: 'reference_link'
}
'assay_parameters': {
parse_function: (raw_parameters) ->
param_groups = []
for param in raw_parameters
useful_params = []
for key in ['standard_type', 'standard_relation', 'standard_value', 'standard_units', 'comments']
useful_params.push("#{key}:#{param[key]}")
param_groups.push(useful_params.join(' '))
return param_groups.join(' | ')
}
'assay_parameters_report_card_rows': {
parse_function: (raw_parameters) ->
console.log('raw_parameters: ', raw_parameters)
rows = []
for paramsObj in raw_parameters
if paramsObj.standard_value?
textValue = "#{paramsObj.standard_relation} #{paramsObj.standard_value} #{paramsObj.standard_units}"
else
textValue = paramsObj.standard_text_value
currentRow = {
standard_type: paramsObj.standard_type
text_value: textValue
}
rows.push(currentRow)
console.log('parsed rows: ', rows)
return rows
},
'assay_classifications_level1': {
parse_function: (raw_classifications) ->
if raw_classifications == glados.Settings.DEFAULT_NULL_VALUE_LABEL
return glados.Settings.DEFAULT_NULL_VALUE_LABEL
else
return (data['l1'] for data in raw_classifications).join(', ')
},
'assay_classifications_level2': {
parse_function: (raw_classifications) ->
if raw_classifications == glados.Settings.DEFAULT_NULL_VALUE_LABEL
return glados.Settings.DEFAULT_NULL_VALUE_LABEL
else
return (data['l2'] for data in raw_classifications).join(', ')
},
'assay_classifications_level3': {
parse_function: (raw_classifications) ->
if raw_classifications == glados.Settings.DEFAULT_NULL_VALUE_LABEL
return glados.Settings.DEFAULT_NULL_VALUE_LABEL
else
return (data['l3'] for data in raw_classifications).join(', ')
}
}
Assay.COLUMNS = {
CHEMBL_ID:
aggregatable: true
comparator: "assay_chembl_id"
hide_label: true
id: "assay_chembl_id"
is_sorting: 0
link_base: "report_card_url"
name_to_show: "ChEMBL ID"
name_to_show_short: "ChEMBL ID"
show: true
sort_class: "fa-sort"
sort_disabled: false
}
Assay.ID_COLUMN = Assay.COLUMNS.CHEMBL_ID
Assay.MINI_REPORT_CARD =
LOADING_TEMPLATE: 'Handlebars-Common-MiniRepCardPreloader'
TEMPLATE: 'Handlebars-Common-MiniReportCard' | 22427 | Assay = Backbone.Model.extend
entityName: '<NAME>ay'
entityNamePlural: '<NAME>ays'
idAttribute: 'assay_chembl_id'
defaults:
fetch_from_elastic: true
indexName: 'chembl_assay'
initialize: ->
id = @get('id')
id ?= @get('assay_chembl_id')
@set('id', id)
@set('assay_chembl_id', id)
if @get('fetch_from_elastic')
@url = "#{glados.Settings.ES_PROXY_API_BASE_URL}/es_data/get_es_document/#{Assay.ES_INDEX}/#{id}"
else
@url = glados.Settings.WS_BASE_URL + 'assay/' + id + '.json'
parse: (response) ->
# get data when it comes from elastic
if response._source?
objData = response._source
else
objData = response
objData.target = response.assay_chembl_id
objData.report_card_url = Assay.get_report_card_url(objData.assay_chembl_id )
objData.document_link = Document.get_report_card_url(objData.document_chembl_id)
objData.tissue_link = glados.models.Tissue.get_report_card_url(objData.tissue_chembl_id)
filterForCompounds = '_metadata.related_assays.all_chembl_ids:' + objData.assay_chembl_id
objData.compounds_url = Compound.getCompoundsListURL(filterForCompounds)
filterForActivities = 'assay_chembl_id:' + objData.assay_chembl_id
objData.activities_url = Activity.getActivitiesListURL(filterForActivities)
objData.target_link = Target.get_report_card_url(objData.target_chembl_id)
objData.cell_link = CellLine.get_report_card_url(objData.cell_chembl_id)
#check if it is bindingdb and add corresponding link
isFromBindingDB = objData.src_id == 37
if isFromBindingDB
assayIDParts = objData.src_assay_id.split('_')
byAssayID = assayIDParts[1]
entryID = assayIDParts[0]
bindingDBLink = "https://www.bindingdb.org/jsp/dbsearch/assay.jsp?assayid=#{byAssayID}&entryid=#{entryID}"
objData.binding_db_link = bindingDBLink
objData.binding_db_link_text = entryID
if objData._metadata.document_data.doi?
objData.reference_link = 'http://dx.doi.org/' + encodeURIComponent(objData._metadata.document_data.doi)
if objData._metadata.document_data.pubmed_id?
objData.pubmed_link = 'https://www.ncbi.nlm.nih.gov/pubmed/' + \
encodeURIComponent(objData._metadata.document_data.pubmed_id)
return objData;
# Constant definition for ReportCardEntity model functionalities
_.extend(Assay, glados.models.base.ReportCardEntity)
Assay.color = 'amber'
Assay.reportCardPath = 'assay_report_card/'
Assay.getAssaysListURL = (filter, isFullState=false, fragmentOnly=false) ->
if isFullState
filter = btoa(JSON.stringify(filter))
return glados.Settings.ENTITY_BROWSERS_URL_GENERATOR
fragment_only: fragmentOnly
entity: 'assays'
filter: encodeURIComponent(filter) unless not filter?
is_full_state: isFullState
Assay.ES_INDEX = 'chembl_assay'
Assay.INDEX_NAME = Assay.ES_INDEX
Assay.PROPERTIES_VISUAL_CONFIG = {
'assay_chembl_id': {
link_base: 'report_card_url'
}
'_metadata.related_compounds.count': {
link_base: 'compounds_url'
on_click: AssayReportCardApp.initMiniHistogramFromFunctionLink
function_constant_parameters: ['compounds']
function_parameters: ['assay_chembl_id']
function_key: '<KEY>'
function_link: true
execute_on_render: true
format_class: 'number-cell-center'
}
'_metadata.related_activities.count': {
link_base: 'activities_url'
on_click: AssayReportCardApp.initMiniHistogramFromFunctionLink
function_parameters: ['assay_chembl_id']
function_constant_parameters: ['activities']
function_key: '<KEY>'
function_link: true
execute_on_render: true
format_class: 'number-cell-center'
}
'document_chembl_id': {
link_base: 'document_link'
}
'tissue_chembl_id': {
link_base: 'tissue_link'
}
'_metadata.document_data.pubmed_id': {
link_base: 'pubmed_link'
}
'_metadata.document_data.doi': {
link_base: 'reference_link'
}
'assay_parameters': {
parse_function: (raw_parameters) ->
param_groups = []
for param in raw_parameters
useful_params = []
for key in ['standard_type', 'standard_relation', 'standard_value', 'standard_units', 'comments']
useful_params.push("#{key}:#{param[key]}")
param_groups.push(useful_params.join(' '))
return param_groups.join(' | ')
}
'assay_parameters_report_card_rows': {
parse_function: (raw_parameters) ->
console.log('raw_parameters: ', raw_parameters)
rows = []
for paramsObj in raw_parameters
if paramsObj.standard_value?
textValue = "#{paramsObj.standard_relation} #{paramsObj.standard_value} #{paramsObj.standard_units}"
else
textValue = paramsObj.standard_text_value
currentRow = {
standard_type: paramsObj.standard_type
text_value: textValue
}
rows.push(currentRow)
console.log('parsed rows: ', rows)
return rows
},
'assay_classifications_level1': {
parse_function: (raw_classifications) ->
if raw_classifications == glados.Settings.DEFAULT_NULL_VALUE_LABEL
return glados.Settings.DEFAULT_NULL_VALUE_LABEL
else
return (data['l1'] for data in raw_classifications).join(', ')
},
'assay_classifications_level2': {
parse_function: (raw_classifications) ->
if raw_classifications == glados.Settings.DEFAULT_NULL_VALUE_LABEL
return glados.Settings.DEFAULT_NULL_VALUE_LABEL
else
return (data['l2'] for data in raw_classifications).join(', ')
},
'assay_classifications_level3': {
parse_function: (raw_classifications) ->
if raw_classifications == glados.Settings.DEFAULT_NULL_VALUE_LABEL
return glados.Settings.DEFAULT_NULL_VALUE_LABEL
else
return (data['l3'] for data in raw_classifications).join(', ')
}
}
Assay.COLUMNS = {
CHEMBL_ID:
aggregatable: true
comparator: "assay_chembl_id"
hide_label: true
id: "assay_chembl_id"
is_sorting: 0
link_base: "report_card_url"
name_to_show: "ChEMBL ID"
name_to_show_short: "ChEMBL ID"
show: true
sort_class: "fa-sort"
sort_disabled: false
}
Assay.ID_COLUMN = Assay.COLUMNS.CHEMBL_ID
Assay.MINI_REPORT_CARD =
LOADING_TEMPLATE: 'Handlebars-Common-MiniRepCardPreloader'
TEMPLATE: 'Handlebars-Common-MiniReportCard' | true | Assay = Backbone.Model.extend
entityName: 'PI:NAME:<NAME>END_PIay'
entityNamePlural: 'PI:NAME:<NAME>END_PIays'
idAttribute: 'assay_chembl_id'
defaults:
fetch_from_elastic: true
indexName: 'chembl_assay'
initialize: ->
id = @get('id')
id ?= @get('assay_chembl_id')
@set('id', id)
@set('assay_chembl_id', id)
if @get('fetch_from_elastic')
@url = "#{glados.Settings.ES_PROXY_API_BASE_URL}/es_data/get_es_document/#{Assay.ES_INDEX}/#{id}"
else
@url = glados.Settings.WS_BASE_URL + 'assay/' + id + '.json'
parse: (response) ->
# get data when it comes from elastic
if response._source?
objData = response._source
else
objData = response
objData.target = response.assay_chembl_id
objData.report_card_url = Assay.get_report_card_url(objData.assay_chembl_id )
objData.document_link = Document.get_report_card_url(objData.document_chembl_id)
objData.tissue_link = glados.models.Tissue.get_report_card_url(objData.tissue_chembl_id)
filterForCompounds = '_metadata.related_assays.all_chembl_ids:' + objData.assay_chembl_id
objData.compounds_url = Compound.getCompoundsListURL(filterForCompounds)
filterForActivities = 'assay_chembl_id:' + objData.assay_chembl_id
objData.activities_url = Activity.getActivitiesListURL(filterForActivities)
objData.target_link = Target.get_report_card_url(objData.target_chembl_id)
objData.cell_link = CellLine.get_report_card_url(objData.cell_chembl_id)
#check if it is bindingdb and add corresponding link
isFromBindingDB = objData.src_id == 37
if isFromBindingDB
assayIDParts = objData.src_assay_id.split('_')
byAssayID = assayIDParts[1]
entryID = assayIDParts[0]
bindingDBLink = "https://www.bindingdb.org/jsp/dbsearch/assay.jsp?assayid=#{byAssayID}&entryid=#{entryID}"
objData.binding_db_link = bindingDBLink
objData.binding_db_link_text = entryID
if objData._metadata.document_data.doi?
objData.reference_link = 'http://dx.doi.org/' + encodeURIComponent(objData._metadata.document_data.doi)
if objData._metadata.document_data.pubmed_id?
objData.pubmed_link = 'https://www.ncbi.nlm.nih.gov/pubmed/' + \
encodeURIComponent(objData._metadata.document_data.pubmed_id)
return objData;
# Constant definition for ReportCardEntity model functionalities
_.extend(Assay, glados.models.base.ReportCardEntity)
Assay.color = 'amber'
Assay.reportCardPath = 'assay_report_card/'
Assay.getAssaysListURL = (filter, isFullState=false, fragmentOnly=false) ->
if isFullState
filter = btoa(JSON.stringify(filter))
return glados.Settings.ENTITY_BROWSERS_URL_GENERATOR
fragment_only: fragmentOnly
entity: 'assays'
filter: encodeURIComponent(filter) unless not filter?
is_full_state: isFullState
Assay.ES_INDEX = 'chembl_assay'
Assay.INDEX_NAME = Assay.ES_INDEX
Assay.PROPERTIES_VISUAL_CONFIG = {
'assay_chembl_id': {
link_base: 'report_card_url'
}
'_metadata.related_compounds.count': {
link_base: 'compounds_url'
on_click: AssayReportCardApp.initMiniHistogramFromFunctionLink
function_constant_parameters: ['compounds']
function_parameters: ['assay_chembl_id']
function_key: 'PI:KEY:<KEY>END_PI'
function_link: true
execute_on_render: true
format_class: 'number-cell-center'
}
'_metadata.related_activities.count': {
link_base: 'activities_url'
on_click: AssayReportCardApp.initMiniHistogramFromFunctionLink
function_parameters: ['assay_chembl_id']
function_constant_parameters: ['activities']
function_key: 'PI:KEY:<KEY>END_PI'
function_link: true
execute_on_render: true
format_class: 'number-cell-center'
}
'document_chembl_id': {
link_base: 'document_link'
}
'tissue_chembl_id': {
link_base: 'tissue_link'
}
'_metadata.document_data.pubmed_id': {
link_base: 'pubmed_link'
}
'_metadata.document_data.doi': {
link_base: 'reference_link'
}
'assay_parameters': {
parse_function: (raw_parameters) ->
param_groups = []
for param in raw_parameters
useful_params = []
for key in ['standard_type', 'standard_relation', 'standard_value', 'standard_units', 'comments']
useful_params.push("#{key}:#{param[key]}")
param_groups.push(useful_params.join(' '))
return param_groups.join(' | ')
}
'assay_parameters_report_card_rows': {
parse_function: (raw_parameters) ->
console.log('raw_parameters: ', raw_parameters)
rows = []
for paramsObj in raw_parameters
if paramsObj.standard_value?
textValue = "#{paramsObj.standard_relation} #{paramsObj.standard_value} #{paramsObj.standard_units}"
else
textValue = paramsObj.standard_text_value
currentRow = {
standard_type: paramsObj.standard_type
text_value: textValue
}
rows.push(currentRow)
console.log('parsed rows: ', rows)
return rows
},
'assay_classifications_level1': {
parse_function: (raw_classifications) ->
if raw_classifications == glados.Settings.DEFAULT_NULL_VALUE_LABEL
return glados.Settings.DEFAULT_NULL_VALUE_LABEL
else
return (data['l1'] for data in raw_classifications).join(', ')
},
'assay_classifications_level2': {
parse_function: (raw_classifications) ->
if raw_classifications == glados.Settings.DEFAULT_NULL_VALUE_LABEL
return glados.Settings.DEFAULT_NULL_VALUE_LABEL
else
return (data['l2'] for data in raw_classifications).join(', ')
},
'assay_classifications_level3': {
parse_function: (raw_classifications) ->
if raw_classifications == glados.Settings.DEFAULT_NULL_VALUE_LABEL
return glados.Settings.DEFAULT_NULL_VALUE_LABEL
else
return (data['l3'] for data in raw_classifications).join(', ')
}
}
Assay.COLUMNS = {
CHEMBL_ID:
aggregatable: true
comparator: "assay_chembl_id"
hide_label: true
id: "assay_chembl_id"
is_sorting: 0
link_base: "report_card_url"
name_to_show: "ChEMBL ID"
name_to_show_short: "ChEMBL ID"
show: true
sort_class: "fa-sort"
sort_disabled: false
}
Assay.ID_COLUMN = Assay.COLUMNS.CHEMBL_ID
Assay.MINI_REPORT_CARD =
LOADING_TEMPLATE: 'Handlebars-Common-MiniRepCardPreloader'
TEMPLATE: 'Handlebars-Common-MiniReportCard' |
[
{
"context": " beforeEach ->\n @sut.resetToken 'river-song'\n\n it 'should call resetToken on meshbluHttp",
"end": 2474,
"score": 0.6472532153129578,
"start": 2470,
"tag": "PASSWORD",
"value": "song"
},
{
"context": "oken.yield null, uuid: 'river-uuid', token: 'river... | test/flow-deploy-model-spec.coffee | octoblu/deprecated-flow-deploy-service | 1 | FlowDeployModel = require '../src/flow-deploy-model'
describe 'FlowDeployModel', ->
beforeEach ->
@flowId = '1234'
@meshbluHttp =
mydevices: sinon.stub()
message: sinon.stub()
device: sinon.stub()
update: sinon.stub()
updateDangerously: sinon.stub()
resetToken: sinon.stub()
MeshbluHttp = =>
@meshbluHttp
@dependencies = MeshbluHttp: MeshbluHttp, TIMEOUT: 1000, WAIT: 100
options =
flowId: @flowId
userMeshbluConfig: {}
serviceMeshbluConfig: {}
@sut = new FlowDeployModel options, @dependencies
describe '->constructor', ->
it 'should exist', ->
expect(@sut).to.exist
describe '->clearState', ->
describe 'when called with a uuid', ->
beforeEach ->
@sut.clearState 'whatevs'
it 'should call meshbluHttp.update', ->
expect(@meshbluHttp.update).to.have.been.calledWith 'whatevs', states: null
describe 'when called with a different uuid', ->
beforeEach ->
@sut.clearState 'evswhat'
it 'should call meshbluHttp.update', ->
expect(@meshbluHttp.update).to.have.been.calledWith 'evswhat', states: null
describe 'when meshbluHttp.update yields an error', ->
beforeEach (done) ->
@meshbluHttp.update.yields new Error('big badda boom')
@sut.clearState 'smoething', (@error) => done()
it 'should call the callback with an error', ->
expect(@error).to.be.an.instanceOf Error
expect(@error.message).to.deep.equal 'big badda boom'
describe 'when meshbluHttp.update does not yield an error', ->
beforeEach (done) ->
@meshbluHttp.update.yields undefined
@sut.clearState 'smoething', (@error) => done()
it 'should call the callback without an error', ->
expect(@error).to.not.exist
describe '->find', ->
beforeEach (done) ->
@meshbluHttp.device.yields null, uuid: 'honey-bunny'
@sut.find 21352135, (@error, @device) => done()
it 'should find the flow', ->
expect(@device).to.deep.equal uuid: 'honey-bunny'
describe '->resetToken', ->
describe 'when called with a uuid', ->
beforeEach ->
@sut.resetToken 'river-flow'
it 'should call resetToken on meshbluHttp with river-flow', ->
expect(@meshbluHttp.resetToken).to.have.been.calledWith 'river-flow'
describe 'when called with a different uuid', ->
beforeEach ->
@sut.resetToken 'river-song'
it 'should call resetToken on meshbluHttp with river-song', ->
expect(@meshbluHttp.resetToken).to.have.been.calledWith 'river-song'
describe 'when meshbluHttp.resetToken yields an error', ->
beforeEach (done) ->
@sut.resetToken 'something-witty', (@error, @result) => done()
@meshbluHttp.resetToken.yield new Error('oh no!')
it 'should call the callback with the error', ->
expect(@error).to.deep.equal new Error('oh no!')
it 'should call the callback with no result', ->
expect(@result).not.to.exist
describe 'when meshbluHttp.resetToken yields a uuid and token', ->
beforeEach (done) ->
@sut.resetToken 'something-witty', (@error, @result) => done()
@meshbluHttp.resetToken.yield null, uuid: 'river-uuid', token: 'river-token'
it 'should call the callback with the token', ->
expect(@result).to.deep.equal 'river-token'
it 'should call the callback with an empty error', ->
expect(@error).to.not.exist
describe '->sendFlowMessage', ->
beforeEach ->
@flow = uuid: 'big-daddy', token: 'tolking'
@meshbluHttp.mydevices.yields null, devices: [uuid: 'honey-bear']
@meshbluHttp.message.yields null
@sut.sendFlowMessage @flow, 'test', {pay: 'load'}
it 'should call message', ->
expect(@meshbluHttp.message).to.have.been.calledWith
devices: ['big-daddy']
topic: "test"
payload:
pay: 'load'
describe '->start', ->
describe 'when find returns an error', ->
beforeEach (done) ->
@sut = new FlowDeployModel flowId: '1234', userMeshbluConfig: {}, @dependencies
@sut.find = sinon.stub().yields new Error
@sut.sendFlowMessage = sinon.spy()
@sut.start (@error) => done()
it 'should yield an error', ->
expect(@error).to.exist
describe 'when find, resetToken, clearState, and useContainer succeed', ->
beforeEach (done) ->
@sut = new FlowDeployModel flowId: '1234', userMeshbluConfig: {}, @dependencies
@sut.find = sinon.stub().yields null, {}
@sut.resetToken = sinon.stub().yields null, 'token'
@sut.clearState = sinon.stub().yields null
@sut.useContainer = sinon.stub().yields null
@sut.sendFlowMessage = sinon.spy()
@sut.start (@error) => done()
it 'should call find', ->
expect(@sut.find).to.have.been.calledWith '1234'
it 'should call resetToken with the uuid', ->
expect(@sut.resetToken).to.have.been.calledWith '1234'
it 'should call clearState with the uuid', ->
expect(@sut.clearState).to.have.been.calledWith '1234'
it 'should call useContainer', ->
expect(@sut.useContainer).to.have.been.calledWith {token: 'token'}
it 'should not have an error', ->
expect(@error).not.to.exist
describe 'when clearState yields an error', ->
beforeEach (done) ->
@sut = new FlowDeployModel flowId: '1234', userMeshbluConfig: {}, @dependencies
@sut.find = sinon.stub().yields null, {}
@sut.resetToken = sinon.stub().yields null, 'token'
@sut.clearState = sinon.stub().yields new Error('state is still opaque')
@sut.useContainer = sinon.stub().yields new Error('should not be called')
@sut.sendFlowMessage = sinon.spy()
@sut.start (@error) => done()
it 'should call the callback with the error', ->
expect(@error).to.be.an.instanceOf Error
expect(@error.message).to.deep.equal 'state is still opaque'
describe '->stop', ->
describe 'when find returns an error', ->
beforeEach (done) ->
@sut = new FlowDeployModel userMeshbluConfig: {}, @dependencies
@sut.find = sinon.stub().yields new Error
@sut.sendFlowMessage = sinon.spy()
@sut.stop (@error) => done()
it 'should yield an error', ->
expect(@error).to.exist
describe 'when find succeeds', ->
beforeEach (done) ->
@sut = new FlowDeployModel flowId: '1234', userMeshbluConfig: {}, @dependencies
@sut.find = sinon.stub().yields null, {}
@sut.useContainer = sinon.stub().yields null
@sut.sendFlowMessage = sinon.spy()
@sut.stop (@error) => done()
it 'should have called find', ->
expect(@sut.find).to.have.been.calledWith '1234'
it 'should have called useContainer', ->
expect(@sut.useContainer).to.have.been.calledWith {}
it 'should not have an error', ->
expect(@error).not.to.exist
describe '->pause', ->
describe 'when find returns an error', ->
beforeEach (done) ->
@sut = new FlowDeployModel
@sut.find = sinon.stub().yields new Error
@sut.pause (@error) => done()
it 'should yield an error', ->
expect(@error).to.exist
describe 'when find succeeds', ->
beforeEach (done) ->
@sut = new FlowDeployModel flowId: '1234'
@sut.find = sinon.stub().yields null, {}
@sut.sendFlowMessage = sinon.stub().yields null
@sut.pause (@error) => done()
it 'should have called find', ->
expect(@sut.find).to.have.been.calledWith '1234'
it 'should have called sendFlowMessage', ->
expect(@sut.sendFlowMessage).to.have.been.calledWith {}, 'flow:pause', {}
it 'should not have an error', ->
expect(@error).not.to.exist
describe '->resume', ->
describe 'when find returns an error', ->
beforeEach (done) ->
@sut = new FlowDeployModel
@sut.find = sinon.stub().yields new Error
@sut.resume (@error) => done()
it 'should yield an error', ->
expect(@error).to.exist
describe 'when find succeeds', ->
beforeEach (done) ->
@sut = new FlowDeployModel flowId: '1234'
@sut.find = sinon.stub().yields null, {}
@sut.sendFlowMessage = sinon.stub().yields null
@sut.resume (@error) => done()
it 'should have called find', ->
expect(@sut.find).to.have.been.calledWith '1234'
it 'should have called sendFlowMessage', ->
expect(@sut.sendFlowMessage).to.have.been.calledWith {}, 'flow:resume', {}
it 'should not have an error', ->
expect(@error).not.to.exist
describe '->didSave', ->
describe 'when the state has changed', ->
beforeEach (done) ->
@meshbluHttp.device = sinon.stub()
@meshbluHttp.device.onCall(0).yields null, {}
@meshbluHttp.device.onCall(1).yields null, stateId:'4321'
@sut.didSave '4321', (@error) => done()
it 'should not have an error', ->
expect(@error).to.not.exist
it 'should call device', ->
expect(@meshbluHttp.device).to.have.been.calledWith '1234'
describe 'when the state is something else and has changed', ->
beforeEach (done) ->
@meshbluHttp.device = sinon.stub()
@meshbluHttp.device.onCall(0).yields null, {}
@meshbluHttp.device.onCall(1).yields null, stateId: '5678'
@sut.didSave '5678', (@error) => done()
it 'should not have an error', ->
expect(@error).to.not.exist
it 'should call device', ->
expect(@meshbluHttp.device).to.have.been.calledWith '1234'
describe 'when the state does not change', ->
beforeEach (done) ->
@meshbluHttp.device = sinon.stub().yields null, {}
@sut.didSave '5678', (@error) => done()
it 'should have an error', ->
expect(@error).to.exist
it 'should call device', ->
expect(@meshbluHttp.device).to.have.been.calledWith '1234'
describe '->save', ->
describe 'when find returns an error', ->
beforeEach (done) ->
@sut = new FlowDeployModel
@sut.find = sinon.stub().yields new Error
@sut.didSave = sinon.stub().yields null
@sut.save 1555, (@error) => done()
it 'should yield an error', ->
expect(@error).to.exist
describe 'when find succeeds', ->
beforeEach (done) ->
@sut = new FlowDeployModel flowId: '1234'
@sut.find = sinon.stub().yields null, {}
@sut.sendFlowMessage = sinon.stub().yields null
@sut.didSave = sinon.stub().yields null
@sut.save 1235, (@error) => done()
it 'should have called find', ->
expect(@sut.find).to.have.been.calledWith '1234'
it 'should have called sendFlowMessage', ->
expect(@sut.sendFlowMessage).to.have.been.calledWith {}, 'flow:save', stateId: 1235
it 'should not have an error', ->
expect(@error).not.to.exist
describe '->savePause', ->
describe 'when find returns an error', ->
beforeEach (done) ->
@sut = new FlowDeployModel
@sut.find = sinon.stub().yields new Error
@sut.didSave = sinon.stub().yields null
@sut.savePause 1555, (@error) => done()
it 'should yield an error', ->
expect(@error).to.exist
describe 'when find succeeds', ->
beforeEach (done) ->
@sut = new FlowDeployModel flowId: '1234'
@sut.find = sinon.stub().yields null, {}
@sut.sendFlowMessage = sinon.stub().yields null
@sut.didSave = sinon.stub().yields null
@sut.savePause 1235, (@error) => done()
it 'should have called find', ->
expect(@sut.find).to.have.been.calledWith '1234'
it 'should have called sendFlowMessage', ->
expect(@sut.sendFlowMessage).to.have.been.calledWith {}, 'flow:save-pause', stateId: 1235
it 'should not have an error', ->
expect(@error).not.to.exist
| 5349 | FlowDeployModel = require '../src/flow-deploy-model'
describe 'FlowDeployModel', ->
beforeEach ->
@flowId = '1234'
@meshbluHttp =
mydevices: sinon.stub()
message: sinon.stub()
device: sinon.stub()
update: sinon.stub()
updateDangerously: sinon.stub()
resetToken: sinon.stub()
MeshbluHttp = =>
@meshbluHttp
@dependencies = MeshbluHttp: MeshbluHttp, TIMEOUT: 1000, WAIT: 100
options =
flowId: @flowId
userMeshbluConfig: {}
serviceMeshbluConfig: {}
@sut = new FlowDeployModel options, @dependencies
describe '->constructor', ->
it 'should exist', ->
expect(@sut).to.exist
describe '->clearState', ->
describe 'when called with a uuid', ->
beforeEach ->
@sut.clearState 'whatevs'
it 'should call meshbluHttp.update', ->
expect(@meshbluHttp.update).to.have.been.calledWith 'whatevs', states: null
describe 'when called with a different uuid', ->
beforeEach ->
@sut.clearState 'evswhat'
it 'should call meshbluHttp.update', ->
expect(@meshbluHttp.update).to.have.been.calledWith 'evswhat', states: null
describe 'when meshbluHttp.update yields an error', ->
beforeEach (done) ->
@meshbluHttp.update.yields new Error('big badda boom')
@sut.clearState 'smoething', (@error) => done()
it 'should call the callback with an error', ->
expect(@error).to.be.an.instanceOf Error
expect(@error.message).to.deep.equal 'big badda boom'
describe 'when meshbluHttp.update does not yield an error', ->
beforeEach (done) ->
@meshbluHttp.update.yields undefined
@sut.clearState 'smoething', (@error) => done()
it 'should call the callback without an error', ->
expect(@error).to.not.exist
describe '->find', ->
beforeEach (done) ->
@meshbluHttp.device.yields null, uuid: 'honey-bunny'
@sut.find 21352135, (@error, @device) => done()
it 'should find the flow', ->
expect(@device).to.deep.equal uuid: 'honey-bunny'
describe '->resetToken', ->
describe 'when called with a uuid', ->
beforeEach ->
@sut.resetToken 'river-flow'
it 'should call resetToken on meshbluHttp with river-flow', ->
expect(@meshbluHttp.resetToken).to.have.been.calledWith 'river-flow'
describe 'when called with a different uuid', ->
beforeEach ->
@sut.resetToken 'river-<PASSWORD>'
it 'should call resetToken on meshbluHttp with river-song', ->
expect(@meshbluHttp.resetToken).to.have.been.calledWith 'river-song'
describe 'when meshbluHttp.resetToken yields an error', ->
beforeEach (done) ->
@sut.resetToken 'something-witty', (@error, @result) => done()
@meshbluHttp.resetToken.yield new Error('oh no!')
it 'should call the callback with the error', ->
expect(@error).to.deep.equal new Error('oh no!')
it 'should call the callback with no result', ->
expect(@result).not.to.exist
describe 'when meshbluHttp.resetToken yields a uuid and token', ->
beforeEach (done) ->
@sut.resetToken 'something-witty', (@error, @result) => done()
@meshbluHttp.resetToken.yield null, uuid: 'river-uuid', token: 'river-<PASSWORD>'
it 'should call the callback with the token', ->
expect(@result).to.deep.equal 'river-token'
it 'should call the callback with an empty error', ->
expect(@error).to.not.exist
describe '->sendFlowMessage', ->
beforeEach ->
@flow = uuid: 'big-daddy', token: '<PASSWORD>'
@meshbluHttp.mydevices.yields null, devices: [uuid: 'honey-bear']
@meshbluHttp.message.yields null
@sut.sendFlowMessage @flow, 'test', {pay: 'load'}
it 'should call message', ->
expect(@meshbluHttp.message).to.have.been.calledWith
devices: ['big-daddy']
topic: "test"
payload:
pay: 'load'
describe '->start', ->
describe 'when find returns an error', ->
beforeEach (done) ->
@sut = new FlowDeployModel flowId: '1234', userMeshbluConfig: {}, @dependencies
@sut.find = sinon.stub().yields new Error
@sut.sendFlowMessage = sinon.spy()
@sut.start (@error) => done()
it 'should yield an error', ->
expect(@error).to.exist
describe 'when find, resetToken, clearState, and useContainer succeed', ->
beforeEach (done) ->
@sut = new FlowDeployModel flowId: '1234', userMeshbluConfig: {}, @dependencies
@sut.find = sinon.stub().yields null, {}
@sut.resetToken = sinon.stub().yields null, 'token'
@sut.clearState = sinon.stub().yields null
@sut.useContainer = sinon.stub().yields null
@sut.sendFlowMessage = sinon.spy()
@sut.start (@error) => done()
it 'should call find', ->
expect(@sut.find).to.have.been.calledWith '1234'
it 'should call resetToken with the uuid', ->
expect(@sut.resetToken).to.have.been.calledWith '1234'
it 'should call clearState with the uuid', ->
expect(@sut.clearState).to.have.been.calledWith '1234'
it 'should call useContainer', ->
expect(@sut.useContainer).to.have.been.calledWith {token: 'token'}
it 'should not have an error', ->
expect(@error).not.to.exist
describe 'when clearState yields an error', ->
beforeEach (done) ->
@sut = new FlowDeployModel flowId: '1234', userMeshbluConfig: {}, @dependencies
@sut.find = sinon.stub().yields null, {}
@sut.resetToken = sinon.stub().yields null, 'token'
@sut.clearState = sinon.stub().yields new Error('state is still opaque')
@sut.useContainer = sinon.stub().yields new Error('should not be called')
@sut.sendFlowMessage = sinon.spy()
@sut.start (@error) => done()
it 'should call the callback with the error', ->
expect(@error).to.be.an.instanceOf Error
expect(@error.message).to.deep.equal 'state is still opaque'
describe '->stop', ->
describe 'when find returns an error', ->
beforeEach (done) ->
@sut = new FlowDeployModel userMeshbluConfig: {}, @dependencies
@sut.find = sinon.stub().yields new Error
@sut.sendFlowMessage = sinon.spy()
@sut.stop (@error) => done()
it 'should yield an error', ->
expect(@error).to.exist
describe 'when find succeeds', ->
beforeEach (done) ->
@sut = new FlowDeployModel flowId: '1234', userMeshbluConfig: {}, @dependencies
@sut.find = sinon.stub().yields null, {}
@sut.useContainer = sinon.stub().yields null
@sut.sendFlowMessage = sinon.spy()
@sut.stop (@error) => done()
it 'should have called find', ->
expect(@sut.find).to.have.been.calledWith '1234'
it 'should have called useContainer', ->
expect(@sut.useContainer).to.have.been.calledWith {}
it 'should not have an error', ->
expect(@error).not.to.exist
describe '->pause', ->
describe 'when find returns an error', ->
beforeEach (done) ->
@sut = new FlowDeployModel
@sut.find = sinon.stub().yields new Error
@sut.pause (@error) => done()
it 'should yield an error', ->
expect(@error).to.exist
describe 'when find succeeds', ->
beforeEach (done) ->
@sut = new FlowDeployModel flowId: '1234'
@sut.find = sinon.stub().yields null, {}
@sut.sendFlowMessage = sinon.stub().yields null
@sut.pause (@error) => done()
it 'should have called find', ->
expect(@sut.find).to.have.been.calledWith '1234'
it 'should have called sendFlowMessage', ->
expect(@sut.sendFlowMessage).to.have.been.calledWith {}, 'flow:pause', {}
it 'should not have an error', ->
expect(@error).not.to.exist
describe '->resume', ->
describe 'when find returns an error', ->
beforeEach (done) ->
@sut = new FlowDeployModel
@sut.find = sinon.stub().yields new Error
@sut.resume (@error) => done()
it 'should yield an error', ->
expect(@error).to.exist
describe 'when find succeeds', ->
beforeEach (done) ->
@sut = new FlowDeployModel flowId: '1234'
@sut.find = sinon.stub().yields null, {}
@sut.sendFlowMessage = sinon.stub().yields null
@sut.resume (@error) => done()
it 'should have called find', ->
expect(@sut.find).to.have.been.calledWith '1234'
it 'should have called sendFlowMessage', ->
expect(@sut.sendFlowMessage).to.have.been.calledWith {}, 'flow:resume', {}
it 'should not have an error', ->
expect(@error).not.to.exist
describe '->didSave', ->
describe 'when the state has changed', ->
beforeEach (done) ->
@meshbluHttp.device = sinon.stub()
@meshbluHttp.device.onCall(0).yields null, {}
@meshbluHttp.device.onCall(1).yields null, stateId:'4321'
@sut.didSave '4321', (@error) => done()
it 'should not have an error', ->
expect(@error).to.not.exist
it 'should call device', ->
expect(@meshbluHttp.device).to.have.been.calledWith '1234'
describe 'when the state is something else and has changed', ->
beforeEach (done) ->
@meshbluHttp.device = sinon.stub()
@meshbluHttp.device.onCall(0).yields null, {}
@meshbluHttp.device.onCall(1).yields null, stateId: '5678'
@sut.didSave '5678', (@error) => done()
it 'should not have an error', ->
expect(@error).to.not.exist
it 'should call device', ->
expect(@meshbluHttp.device).to.have.been.calledWith '1234'
describe 'when the state does not change', ->
beforeEach (done) ->
@meshbluHttp.device = sinon.stub().yields null, {}
@sut.didSave '5678', (@error) => done()
it 'should have an error', ->
expect(@error).to.exist
it 'should call device', ->
expect(@meshbluHttp.device).to.have.been.calledWith '1234'
describe '->save', ->
describe 'when find returns an error', ->
beforeEach (done) ->
@sut = new FlowDeployModel
@sut.find = sinon.stub().yields new Error
@sut.didSave = sinon.stub().yields null
@sut.save 1555, (@error) => done()
it 'should yield an error', ->
expect(@error).to.exist
describe 'when find succeeds', ->
beforeEach (done) ->
@sut = new FlowDeployModel flowId: '1234'
@sut.find = sinon.stub().yields null, {}
@sut.sendFlowMessage = sinon.stub().yields null
@sut.didSave = sinon.stub().yields null
@sut.save 1235, (@error) => done()
it 'should have called find', ->
expect(@sut.find).to.have.been.calledWith '1234'
it 'should have called sendFlowMessage', ->
expect(@sut.sendFlowMessage).to.have.been.calledWith {}, 'flow:save', stateId: 1235
it 'should not have an error', ->
expect(@error).not.to.exist
describe '->savePause', ->
describe 'when find returns an error', ->
beforeEach (done) ->
@sut = new FlowDeployModel
@sut.find = sinon.stub().yields new Error
@sut.didSave = sinon.stub().yields null
@sut.savePause 1555, (@error) => done()
it 'should yield an error', ->
expect(@error).to.exist
describe 'when find succeeds', ->
beforeEach (done) ->
@sut = new FlowDeployModel flowId: '1234'
@sut.find = sinon.stub().yields null, {}
@sut.sendFlowMessage = sinon.stub().yields null
@sut.didSave = sinon.stub().yields null
@sut.savePause 1235, (@error) => done()
it 'should have called find', ->
expect(@sut.find).to.have.been.calledWith '1234'
it 'should have called sendFlowMessage', ->
expect(@sut.sendFlowMessage).to.have.been.calledWith {}, 'flow:save-pause', stateId: 1235
it 'should not have an error', ->
expect(@error).not.to.exist
| true | FlowDeployModel = require '../src/flow-deploy-model'
describe 'FlowDeployModel', ->
beforeEach ->
@flowId = '1234'
@meshbluHttp =
mydevices: sinon.stub()
message: sinon.stub()
device: sinon.stub()
update: sinon.stub()
updateDangerously: sinon.stub()
resetToken: sinon.stub()
MeshbluHttp = =>
@meshbluHttp
@dependencies = MeshbluHttp: MeshbluHttp, TIMEOUT: 1000, WAIT: 100
options =
flowId: @flowId
userMeshbluConfig: {}
serviceMeshbluConfig: {}
@sut = new FlowDeployModel options, @dependencies
describe '->constructor', ->
it 'should exist', ->
expect(@sut).to.exist
describe '->clearState', ->
describe 'when called with a uuid', ->
beforeEach ->
@sut.clearState 'whatevs'
it 'should call meshbluHttp.update', ->
expect(@meshbluHttp.update).to.have.been.calledWith 'whatevs', states: null
describe 'when called with a different uuid', ->
beforeEach ->
@sut.clearState 'evswhat'
it 'should call meshbluHttp.update', ->
expect(@meshbluHttp.update).to.have.been.calledWith 'evswhat', states: null
describe 'when meshbluHttp.update yields an error', ->
beforeEach (done) ->
@meshbluHttp.update.yields new Error('big badda boom')
@sut.clearState 'smoething', (@error) => done()
it 'should call the callback with an error', ->
expect(@error).to.be.an.instanceOf Error
expect(@error.message).to.deep.equal 'big badda boom'
describe 'when meshbluHttp.update does not yield an error', ->
beforeEach (done) ->
@meshbluHttp.update.yields undefined
@sut.clearState 'smoething', (@error) => done()
it 'should call the callback without an error', ->
expect(@error).to.not.exist
describe '->find', ->
beforeEach (done) ->
@meshbluHttp.device.yields null, uuid: 'honey-bunny'
@sut.find 21352135, (@error, @device) => done()
it 'should find the flow', ->
expect(@device).to.deep.equal uuid: 'honey-bunny'
describe '->resetToken', ->
describe 'when called with a uuid', ->
beforeEach ->
@sut.resetToken 'river-flow'
it 'should call resetToken on meshbluHttp with river-flow', ->
expect(@meshbluHttp.resetToken).to.have.been.calledWith 'river-flow'
describe 'when called with a different uuid', ->
beforeEach ->
@sut.resetToken 'river-PI:PASSWORD:<PASSWORD>END_PI'
it 'should call resetToken on meshbluHttp with river-song', ->
expect(@meshbluHttp.resetToken).to.have.been.calledWith 'river-song'
describe 'when meshbluHttp.resetToken yields an error', ->
beforeEach (done) ->
@sut.resetToken 'something-witty', (@error, @result) => done()
@meshbluHttp.resetToken.yield new Error('oh no!')
it 'should call the callback with the error', ->
expect(@error).to.deep.equal new Error('oh no!')
it 'should call the callback with no result', ->
expect(@result).not.to.exist
describe 'when meshbluHttp.resetToken yields a uuid and token', ->
beforeEach (done) ->
@sut.resetToken 'something-witty', (@error, @result) => done()
@meshbluHttp.resetToken.yield null, uuid: 'river-uuid', token: 'river-PI:PASSWORD:<PASSWORD>END_PI'
it 'should call the callback with the token', ->
expect(@result).to.deep.equal 'river-token'
it 'should call the callback with an empty error', ->
expect(@error).to.not.exist
describe '->sendFlowMessage', ->
beforeEach ->
@flow = uuid: 'big-daddy', token: 'PI:PASSWORD:<PASSWORD>END_PI'
@meshbluHttp.mydevices.yields null, devices: [uuid: 'honey-bear']
@meshbluHttp.message.yields null
@sut.sendFlowMessage @flow, 'test', {pay: 'load'}
it 'should call message', ->
expect(@meshbluHttp.message).to.have.been.calledWith
devices: ['big-daddy']
topic: "test"
payload:
pay: 'load'
describe '->start', ->
describe 'when find returns an error', ->
beforeEach (done) ->
@sut = new FlowDeployModel flowId: '1234', userMeshbluConfig: {}, @dependencies
@sut.find = sinon.stub().yields new Error
@sut.sendFlowMessage = sinon.spy()
@sut.start (@error) => done()
it 'should yield an error', ->
expect(@error).to.exist
describe 'when find, resetToken, clearState, and useContainer succeed', ->
beforeEach (done) ->
@sut = new FlowDeployModel flowId: '1234', userMeshbluConfig: {}, @dependencies
@sut.find = sinon.stub().yields null, {}
@sut.resetToken = sinon.stub().yields null, 'token'
@sut.clearState = sinon.stub().yields null
@sut.useContainer = sinon.stub().yields null
@sut.sendFlowMessage = sinon.spy()
@sut.start (@error) => done()
it 'should call find', ->
expect(@sut.find).to.have.been.calledWith '1234'
it 'should call resetToken with the uuid', ->
expect(@sut.resetToken).to.have.been.calledWith '1234'
it 'should call clearState with the uuid', ->
expect(@sut.clearState).to.have.been.calledWith '1234'
it 'should call useContainer', ->
expect(@sut.useContainer).to.have.been.calledWith {token: 'token'}
it 'should not have an error', ->
expect(@error).not.to.exist
describe 'when clearState yields an error', ->
beforeEach (done) ->
@sut = new FlowDeployModel flowId: '1234', userMeshbluConfig: {}, @dependencies
@sut.find = sinon.stub().yields null, {}
@sut.resetToken = sinon.stub().yields null, 'token'
@sut.clearState = sinon.stub().yields new Error('state is still opaque')
@sut.useContainer = sinon.stub().yields new Error('should not be called')
@sut.sendFlowMessage = sinon.spy()
@sut.start (@error) => done()
it 'should call the callback with the error', ->
expect(@error).to.be.an.instanceOf Error
expect(@error.message).to.deep.equal 'state is still opaque'
describe '->stop', ->
describe 'when find returns an error', ->
beforeEach (done) ->
@sut = new FlowDeployModel userMeshbluConfig: {}, @dependencies
@sut.find = sinon.stub().yields new Error
@sut.sendFlowMessage = sinon.spy()
@sut.stop (@error) => done()
it 'should yield an error', ->
expect(@error).to.exist
describe 'when find succeeds', ->
beforeEach (done) ->
@sut = new FlowDeployModel flowId: '1234', userMeshbluConfig: {}, @dependencies
@sut.find = sinon.stub().yields null, {}
@sut.useContainer = sinon.stub().yields null
@sut.sendFlowMessage = sinon.spy()
@sut.stop (@error) => done()
it 'should have called find', ->
expect(@sut.find).to.have.been.calledWith '1234'
it 'should have called useContainer', ->
expect(@sut.useContainer).to.have.been.calledWith {}
it 'should not have an error', ->
expect(@error).not.to.exist
describe '->pause', ->
describe 'when find returns an error', ->
beforeEach (done) ->
@sut = new FlowDeployModel
@sut.find = sinon.stub().yields new Error
@sut.pause (@error) => done()
it 'should yield an error', ->
expect(@error).to.exist
describe 'when find succeeds', ->
beforeEach (done) ->
@sut = new FlowDeployModel flowId: '1234'
@sut.find = sinon.stub().yields null, {}
@sut.sendFlowMessage = sinon.stub().yields null
@sut.pause (@error) => done()
it 'should have called find', ->
expect(@sut.find).to.have.been.calledWith '1234'
it 'should have called sendFlowMessage', ->
expect(@sut.sendFlowMessage).to.have.been.calledWith {}, 'flow:pause', {}
it 'should not have an error', ->
expect(@error).not.to.exist
describe '->resume', ->
describe 'when find returns an error', ->
beforeEach (done) ->
@sut = new FlowDeployModel
@sut.find = sinon.stub().yields new Error
@sut.resume (@error) => done()
it 'should yield an error', ->
expect(@error).to.exist
describe 'when find succeeds', ->
beforeEach (done) ->
@sut = new FlowDeployModel flowId: '1234'
@sut.find = sinon.stub().yields null, {}
@sut.sendFlowMessage = sinon.stub().yields null
@sut.resume (@error) => done()
it 'should have called find', ->
expect(@sut.find).to.have.been.calledWith '1234'
it 'should have called sendFlowMessage', ->
expect(@sut.sendFlowMessage).to.have.been.calledWith {}, 'flow:resume', {}
it 'should not have an error', ->
expect(@error).not.to.exist
describe '->didSave', ->
describe 'when the state has changed', ->
beforeEach (done) ->
@meshbluHttp.device = sinon.stub()
@meshbluHttp.device.onCall(0).yields null, {}
@meshbluHttp.device.onCall(1).yields null, stateId:'4321'
@sut.didSave '4321', (@error) => done()
it 'should not have an error', ->
expect(@error).to.not.exist
it 'should call device', ->
expect(@meshbluHttp.device).to.have.been.calledWith '1234'
describe 'when the state is something else and has changed', ->
beforeEach (done) ->
@meshbluHttp.device = sinon.stub()
@meshbluHttp.device.onCall(0).yields null, {}
@meshbluHttp.device.onCall(1).yields null, stateId: '5678'
@sut.didSave '5678', (@error) => done()
it 'should not have an error', ->
expect(@error).to.not.exist
it 'should call device', ->
expect(@meshbluHttp.device).to.have.been.calledWith '1234'
describe 'when the state does not change', ->
beforeEach (done) ->
@meshbluHttp.device = sinon.stub().yields null, {}
@sut.didSave '5678', (@error) => done()
it 'should have an error', ->
expect(@error).to.exist
it 'should call device', ->
expect(@meshbluHttp.device).to.have.been.calledWith '1234'
describe '->save', ->
describe 'when find returns an error', ->
beforeEach (done) ->
@sut = new FlowDeployModel
@sut.find = sinon.stub().yields new Error
@sut.didSave = sinon.stub().yields null
@sut.save 1555, (@error) => done()
it 'should yield an error', ->
expect(@error).to.exist
describe 'when find succeeds', ->
beforeEach (done) ->
@sut = new FlowDeployModel flowId: '1234'
@sut.find = sinon.stub().yields null, {}
@sut.sendFlowMessage = sinon.stub().yields null
@sut.didSave = sinon.stub().yields null
@sut.save 1235, (@error) => done()
it 'should have called find', ->
expect(@sut.find).to.have.been.calledWith '1234'
it 'should have called sendFlowMessage', ->
expect(@sut.sendFlowMessage).to.have.been.calledWith {}, 'flow:save', stateId: 1235
it 'should not have an error', ->
expect(@error).not.to.exist
describe '->savePause', ->
describe 'when find returns an error', ->
beforeEach (done) ->
@sut = new FlowDeployModel
@sut.find = sinon.stub().yields new Error
@sut.didSave = sinon.stub().yields null
@sut.savePause 1555, (@error) => done()
it 'should yield an error', ->
expect(@error).to.exist
describe 'when find succeeds', ->
beforeEach (done) ->
@sut = new FlowDeployModel flowId: '1234'
@sut.find = sinon.stub().yields null, {}
@sut.sendFlowMessage = sinon.stub().yields null
@sut.didSave = sinon.stub().yields null
@sut.savePause 1235, (@error) => done()
it 'should have called find', ->
expect(@sut.find).to.have.been.calledWith '1234'
it 'should have called sendFlowMessage', ->
expect(@sut.sendFlowMessage).to.have.been.calledWith {}, 'flow:save-pause', stateId: 1235
it 'should not have an error', ->
expect(@error).not.to.exist
|
[
{
"context": ">\n expect(\n _B.isEqualArraySet [1, 2, 3, 'John', 'Doe'], ['John', 3, 'Doe', 2, 1]\n ).to.be.tr",
"end": 210,
"score": 0.9997692704200745,
"start": 206,
"tag": "NAME",
"value": "John"
},
{
"context": "pect(\n _B.isEqualArraySet [1, 2, 3, 'John', 'Doe'],... | source/spec/collections/array/isEqualArraySet-spec.coffee | anodynos/uBerscore | 1 | # clone to check mutability
{ obj, arrInt, arrInt2, arrStr } = _.clone data, true
describe 'isEqualArraySet :', ->
it "simple arrays with primitives", ->
expect(
_B.isEqualArraySet [1, 2, 3, 'John', 'Doe'], ['John', 3, 'Doe', 2, 1]
).to.be.true
it "arrays with primitives & references", ->
expect(
_B.isEqualArraySet [ obj, arrInt, arrStr, 2, 3, 'John', 'Doe'],
[ obj, 'John', arrInt, 3, arrStr, 'Doe', 2]
).to.be.true
| 152778 | # clone to check mutability
{ obj, arrInt, arrInt2, arrStr } = _.clone data, true
describe 'isEqualArraySet :', ->
it "simple arrays with primitives", ->
expect(
_B.isEqualArraySet [1, 2, 3, '<NAME>', '<NAME>'], ['<NAME>', 3, '<NAME>', 2, 1]
).to.be.true
it "arrays with primitives & references", ->
expect(
_B.isEqualArraySet [ obj, arrInt, arrStr, 2, 3, '<NAME>', '<NAME>'],
[ obj, '<NAME>', arrInt, 3, arrStr, '<NAME>', 2]
).to.be.true
| true | # clone to check mutability
{ obj, arrInt, arrInt2, arrStr } = _.clone data, true
describe 'isEqualArraySet :', ->
it "simple arrays with primitives", ->
expect(
_B.isEqualArraySet [1, 2, 3, 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'], ['PI:NAME:<NAME>END_PI', 3, 'PI:NAME:<NAME>END_PI', 2, 1]
).to.be.true
it "arrays with primitives & references", ->
expect(
_B.isEqualArraySet [ obj, arrInt, arrStr, 2, 3, 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'],
[ obj, 'PI:NAME:<NAME>END_PI', arrInt, 3, arrStr, 'PI:NAME:<NAME>END_PI', 2]
).to.be.true
|
[
{
"context": "name: \"Louk\"\nscopeName: \"text.html.vue.louk\"\nfileTypes: [\n\t\"l",
"end": 11,
"score": 0.9976301193237305,
"start": 7,
"tag": "NAME",
"value": "Louk"
}
] | grammars/louk.cson | louk-lang/louk-editor-atom | 0 | name: "Louk"
scopeName: "text.html.vue.louk"
fileTypes: [
"louk"
]
uuid: "444bb94d-ce8b-415d-8683-534f8524ee5a"
patterns: [
{
comment: "Script section marker"
name: "meta.section.vue.louk"
begin: "^(script)(,)"
end: "(?=^([^\\s]*)(,))"
beginCaptures:
"1":
name: "entity.name.tag.html.louk"
"2":
name: "punctuation.definition.tag.static.louk"
patterns: [
{
name: "source.js.embedded.html"
begin: "^\\s+"
end: "(?=^([^\\s]*)(,))"
patterns: [
{
include: "source.js"
}
]
}
]
}
{
comment: "Style section marker"
name: "meta.section.vue.louk"
begin: "^(style)(,)"
end: "(?=^([^\\s]*)(,))"
beginCaptures:
"1":
name: "entity.name.tag.html.louk"
"2":
name: "punctuation.definition.tag.static.louk"
patterns: [
{
name: "source.css.embedded.html"
begin: "^\\s+"
end: "(?=^([^\\s]*)(,))"
patterns: [
{
include: "source.css"
}
]
}
]
}
{
comment: "Template section marker"
name: "meta.section.vue.louk"
begin: "^(template)(,)"
end: "(?=^([^\\s]*)(,))"
beginCaptures:
"1":
name: "entity.name.tag.html.louk"
"2":
name: "punctuation.definition.tag.static.louk"
patterns: [
{
comment: "A comment"
name: "comment.line.louk"
begin: "^\\s*(//)(.*)"
end: "$"
captures:
"1":
name: "punctuation.comment.begin.louk"
"2":
name: "comment.content.louk"
}
{
comment: "A static shorthand attribute"
name: "meta.attribute-with-value.louk"
begin: "^\\s*([>\\.#])(\\S*)"
beginCaptures:
"1":
name: "entity.other.attribute-name.louk"
"2":
name: "string.louk"
end: "\\s"
}
{
comment: "A static attribute"
name: "meta.attribute-with-value.louk"
begin: "^\\s*(['])(\\S*)"
beginCaptures:
"1":
name: "punctuation.definition.attribute.static.louk"
"2":
name: "entity.other.attribute-name.louk"
end: "$"
patterns: [
{
name: "string.louk"
match: ".*"
}
]
}
{
comment: "A directive attribute"
name: "meta.directive.vue.louk"
begin: "^\\s*([:@-])(\\S+)\\s+"
end: "$"
beginCaptures:
"1":
name: "punctuation.separator.key-value.html.louk"
"2":
name: "entity.other.attribute-name.directive.louk"
}
{
comment: "An HTML line"
name: "text.html"
begin: "(?=^\\s*<)"
end: "$"
patterns: [
{
include: "text.html.vue"
}
]
}
{
comment: "An element with static content"
name: "meta.tag.any.html.louk"
begin: "^\\s*([^\\s\"]*)(\")"
end: "$"
beginCaptures:
"1":
name: "entity.name.tag.html.louk"
"2":
name: "punctuation.definition.tag.static.louk"
patterns: [
{
name: "string.louk"
match: ".*"
}
]
}
{
comment: "An element with dynamic content"
name: "meta.tag.any.html.louk"
match: "^\\s*([^\\s]*)"
captures:
"1":
name: "entity.name.tag.html.louk"
}
]
}
] | 60876 | name: "<NAME>"
scopeName: "text.html.vue.louk"
fileTypes: [
"louk"
]
uuid: "444bb94d-ce8b-415d-8683-534f8524ee5a"
patterns: [
{
comment: "Script section marker"
name: "meta.section.vue.louk"
begin: "^(script)(,)"
end: "(?=^([^\\s]*)(,))"
beginCaptures:
"1":
name: "entity.name.tag.html.louk"
"2":
name: "punctuation.definition.tag.static.louk"
patterns: [
{
name: "source.js.embedded.html"
begin: "^\\s+"
end: "(?=^([^\\s]*)(,))"
patterns: [
{
include: "source.js"
}
]
}
]
}
{
comment: "Style section marker"
name: "meta.section.vue.louk"
begin: "^(style)(,)"
end: "(?=^([^\\s]*)(,))"
beginCaptures:
"1":
name: "entity.name.tag.html.louk"
"2":
name: "punctuation.definition.tag.static.louk"
patterns: [
{
name: "source.css.embedded.html"
begin: "^\\s+"
end: "(?=^([^\\s]*)(,))"
patterns: [
{
include: "source.css"
}
]
}
]
}
{
comment: "Template section marker"
name: "meta.section.vue.louk"
begin: "^(template)(,)"
end: "(?=^([^\\s]*)(,))"
beginCaptures:
"1":
name: "entity.name.tag.html.louk"
"2":
name: "punctuation.definition.tag.static.louk"
patterns: [
{
comment: "A comment"
name: "comment.line.louk"
begin: "^\\s*(//)(.*)"
end: "$"
captures:
"1":
name: "punctuation.comment.begin.louk"
"2":
name: "comment.content.louk"
}
{
comment: "A static shorthand attribute"
name: "meta.attribute-with-value.louk"
begin: "^\\s*([>\\.#])(\\S*)"
beginCaptures:
"1":
name: "entity.other.attribute-name.louk"
"2":
name: "string.louk"
end: "\\s"
}
{
comment: "A static attribute"
name: "meta.attribute-with-value.louk"
begin: "^\\s*(['])(\\S*)"
beginCaptures:
"1":
name: "punctuation.definition.attribute.static.louk"
"2":
name: "entity.other.attribute-name.louk"
end: "$"
patterns: [
{
name: "string.louk"
match: ".*"
}
]
}
{
comment: "A directive attribute"
name: "meta.directive.vue.louk"
begin: "^\\s*([:@-])(\\S+)\\s+"
end: "$"
beginCaptures:
"1":
name: "punctuation.separator.key-value.html.louk"
"2":
name: "entity.other.attribute-name.directive.louk"
}
{
comment: "An HTML line"
name: "text.html"
begin: "(?=^\\s*<)"
end: "$"
patterns: [
{
include: "text.html.vue"
}
]
}
{
comment: "An element with static content"
name: "meta.tag.any.html.louk"
begin: "^\\s*([^\\s\"]*)(\")"
end: "$"
beginCaptures:
"1":
name: "entity.name.tag.html.louk"
"2":
name: "punctuation.definition.tag.static.louk"
patterns: [
{
name: "string.louk"
match: ".*"
}
]
}
{
comment: "An element with dynamic content"
name: "meta.tag.any.html.louk"
match: "^\\s*([^\\s]*)"
captures:
"1":
name: "entity.name.tag.html.louk"
}
]
}
] | true | name: "PI:NAME:<NAME>END_PI"
scopeName: "text.html.vue.louk"
fileTypes: [
"louk"
]
uuid: "444bb94d-ce8b-415d-8683-534f8524ee5a"
patterns: [
{
comment: "Script section marker"
name: "meta.section.vue.louk"
begin: "^(script)(,)"
end: "(?=^([^\\s]*)(,))"
beginCaptures:
"1":
name: "entity.name.tag.html.louk"
"2":
name: "punctuation.definition.tag.static.louk"
patterns: [
{
name: "source.js.embedded.html"
begin: "^\\s+"
end: "(?=^([^\\s]*)(,))"
patterns: [
{
include: "source.js"
}
]
}
]
}
{
comment: "Style section marker"
name: "meta.section.vue.louk"
begin: "^(style)(,)"
end: "(?=^([^\\s]*)(,))"
beginCaptures:
"1":
name: "entity.name.tag.html.louk"
"2":
name: "punctuation.definition.tag.static.louk"
patterns: [
{
name: "source.css.embedded.html"
begin: "^\\s+"
end: "(?=^([^\\s]*)(,))"
patterns: [
{
include: "source.css"
}
]
}
]
}
{
comment: "Template section marker"
name: "meta.section.vue.louk"
begin: "^(template)(,)"
end: "(?=^([^\\s]*)(,))"
beginCaptures:
"1":
name: "entity.name.tag.html.louk"
"2":
name: "punctuation.definition.tag.static.louk"
patterns: [
{
comment: "A comment"
name: "comment.line.louk"
begin: "^\\s*(//)(.*)"
end: "$"
captures:
"1":
name: "punctuation.comment.begin.louk"
"2":
name: "comment.content.louk"
}
{
comment: "A static shorthand attribute"
name: "meta.attribute-with-value.louk"
begin: "^\\s*([>\\.#])(\\S*)"
beginCaptures:
"1":
name: "entity.other.attribute-name.louk"
"2":
name: "string.louk"
end: "\\s"
}
{
comment: "A static attribute"
name: "meta.attribute-with-value.louk"
begin: "^\\s*(['])(\\S*)"
beginCaptures:
"1":
name: "punctuation.definition.attribute.static.louk"
"2":
name: "entity.other.attribute-name.louk"
end: "$"
patterns: [
{
name: "string.louk"
match: ".*"
}
]
}
{
comment: "A directive attribute"
name: "meta.directive.vue.louk"
begin: "^\\s*([:@-])(\\S+)\\s+"
end: "$"
beginCaptures:
"1":
name: "punctuation.separator.key-value.html.louk"
"2":
name: "entity.other.attribute-name.directive.louk"
}
{
comment: "An HTML line"
name: "text.html"
begin: "(?=^\\s*<)"
end: "$"
patterns: [
{
include: "text.html.vue"
}
]
}
{
comment: "An element with static content"
name: "meta.tag.any.html.louk"
begin: "^\\s*([^\\s\"]*)(\")"
end: "$"
beginCaptures:
"1":
name: "entity.name.tag.html.louk"
"2":
name: "punctuation.definition.tag.static.louk"
patterns: [
{
name: "string.louk"
match: ".*"
}
]
}
{
comment: "An element with dynamic content"
name: "meta.tag.any.html.louk"
match: "^\\s*([^\\s]*)"
captures:
"1":
name: "entity.name.tag.html.louk"
}
]
}
] |
[
{
"context": "loginInfo =\n username: 'username'\n password: 'password'\n\nwindow.loginInfo = log",
"end": 35,
"score": 0.9987185001373291,
"start": 27,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ginInfo =\n username: 'username'\n password: 'password'\n\nwind... | halite/test/mock/loginConf.coffee | CARFAX/halite | 212 | loginInfo =
username: 'username'
password: 'password'
window.loginInfo = loginInfo
| 137476 | loginInfo =
username: 'username'
password: '<PASSWORD>'
window.loginInfo = loginInfo
| true | loginInfo =
username: 'username'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
window.loginInfo = loginInfo
|
[
{
"context": " person: '=person'\n askPost: '@askPost'\n hideSpecialitySelector: '@hideSpeciali",
"end": 277,
"score": 0.793716549873352,
"start": 270,
"tag": "USERNAME",
"value": "askPost"
},
{
"context": "endingRequests.length > 0\n\n for key in... | app/assets/javascripts/manage/spa/app/directives/people_input.coffee | openteam-tusur/aspirant-site | 0 | angular.module('dashboard')
.directive('peopleInput', ['$http', 'localization', 'science',
($http, localization, science) ->
return {
scope:
context: '=context'
people: '=people'
person: '=person'
askPost: '@askPost'
hideSpecialitySelector: '@hideSpecialitySelector'
kind: '@kind'
specialities: '=specialities'
blockNameValue: '=blockNameValue'
editForm: '=editForm'
transclude: true
restrict: 'E'
templateUrl: 'people_input.html'
controller: ($scope, localization) ->
$scope.l = localization.l
$scope.science_dictionaries = science
$scope.isLoading = () ->
return $http.pendingRequests.length > 0
for key in ['new_person', 'science']
$scope[key] = {}
$scope.setPerson = (obj) ->
unless obj.originalObject.id
$scope.personNotFound = true
$scope.peopleInput.$setPristine()
else
$scope.new_person = obj.originalObject
$scope.compareDictionariesValues = (normalize_string, dictionary_object) ->
current_object = dictionary_object.find (obj) ->
obj.value == normalize_string
return current_object
$scope.normalizeDictionariesValue = (string, dictionary_objects) ->
normalize_result = string.charAt(0).toUpperCase() + string.slice(1) if string
return normalize_result
$scope.fillPerson = (person) ->
u = $scope.new_person
for key in ['patronymic', 'surname', 'name']
u[key] = person[key]
u.url = "https://directory.tusur.ru/people/#{person.id}"
# Result object of scence degree
science_degree_object = $scope.compareDictionariesValues($scope.normalizeDictionariesValue(person.academic_degree),
$scope.science_dictionaries.science_degrees)
# Result object of scence title
science_title_object = $scope.compareDictionariesValues($scope.normalizeDictionariesValue(person.academic_rank),
$scope.science_dictionaries.science_titles)
if science_degree_object
u.science_degree = science_degree_object.value
u.science_degree_abbr = science_degree_object.abbr
if science_title_object
u.science_title = science_title_object.value
u.science_title_abbr = science_title_object.abbr
if person.main_post
u.work_post = person.main_post.short_title || ''
u.work_place = person.main_post.subdivision.title + ' ТУСУР'
u.post ||= {}
u.post.title ||= {}
$scope.updateDirectorySearch()
$scope.cleanPerson = () ->
$scope.new_person_post_speciality = null
$scope.$broadcast 'cleanPerson'
$scope.peopleInput.$setPristine() if $scope.peopleInput
$scope.submitPerson = () ->
if $scope.peopleInput && $scope.peopleInput.$invalid
$scope.peopleInput.$setSubmitted()
for _, input of $scope.peopleInput
if input && input.$name
input.$setDirty()
else
params = {}
angular.copy $scope.context, params
params['person'] = $scope.new_person
$http
.post '/manage/people', params
.success (data) ->
if $scope.people
$scope.people.push data
$scope.directory_search = null
else
$scope.person = data
$scope.cleanPerson()
$scope.hideForm()
$scope.directorySearchTrigger = () ->
$scope.directorySearch = !$scope.directorySearch
$scope.updateDirectorySearch = () ->
query = []
for key in ['name', 'surname', 'patronymic']
query.push $scope.new_person[key]
query = query.join(' ')
$scope.directorySearchTrigger()
$http
.get '/manage/people/directory_search', params: { term: query }
.success (data) ->
$scope.directorySearchTrigger()
$scope.directory_search = data
$scope.postsOf = (result) ->
result.split(';')
$scope.hideForm = () ->
$scope.personNotFound = false
$scope.directory_search = null
$scope.hideNamedBlock = () ->
$scope.blockNameValue = null
$scope.requestFormatter = (str) ->
q: str, ids: ($scope.people || []).map((p) -> p.id ) # ||[] decision is for one person case
$scope.searchResponseFormatter = (data) ->
results = []
for result in data.people
results.push result
empty_object = {
fullname: $scope.l('person.create_new')
id: false
}
results.push empty_object
return results
$scope.setSpeciality = (speciality, callback) ->
unless speciality.id #create new speciality from form
params = { speciality }
$http
.post 'manage/council_specialities', params
.success (data) -> $scope.reallySetSpeciality(data, callback)
else #set speciality id to person post
$scope.reallySetSpeciality(speciality, callback)
$scope.reallySetSpeciality = (speciality, callback) ->
$scope.new_person.post ||= {}
$scope.new_person.post.council_speciality_id = speciality.id
$scope.new_person_post_speciality = speciality
callback()
$scope.destroySpeciality = () ->
$scope.new_person.post.council_speciality_id = null
$scope.new_person_post_speciality = null
}
])
| 36272 | angular.module('dashboard')
.directive('peopleInput', ['$http', 'localization', 'science',
($http, localization, science) ->
return {
scope:
context: '=context'
people: '=people'
person: '=person'
askPost: '@askPost'
hideSpecialitySelector: '@hideSpecialitySelector'
kind: '@kind'
specialities: '=specialities'
blockNameValue: '=blockNameValue'
editForm: '=editForm'
transclude: true
restrict: 'E'
templateUrl: 'people_input.html'
controller: ($scope, localization) ->
$scope.l = localization.l
$scope.science_dictionaries = science
$scope.isLoading = () ->
return $http.pendingRequests.length > 0
for key in ['<KEY>', 'science']
$scope[key] = {}
$scope.setPerson = (obj) ->
unless obj.originalObject.id
$scope.personNotFound = true
$scope.peopleInput.$setPristine()
else
$scope.new_person = obj.originalObject
$scope.compareDictionariesValues = (normalize_string, dictionary_object) ->
current_object = dictionary_object.find (obj) ->
obj.value == normalize_string
return current_object
$scope.normalizeDictionariesValue = (string, dictionary_objects) ->
normalize_result = string.charAt(0).toUpperCase() + string.slice(1) if string
return normalize_result
$scope.fillPerson = (person) ->
u = $scope.new_person
for key in ['patronymic', 'surname', 'name']
u[key] = person[key]
u.url = "https://directory.tusur.ru/people/#{person.id}"
# Result object of scence degree
science_degree_object = $scope.compareDictionariesValues($scope.normalizeDictionariesValue(person.academic_degree),
$scope.science_dictionaries.science_degrees)
# Result object of scence title
science_title_object = $scope.compareDictionariesValues($scope.normalizeDictionariesValue(person.academic_rank),
$scope.science_dictionaries.science_titles)
if science_degree_object
u.science_degree = science_degree_object.value
u.science_degree_abbr = science_degree_object.abbr
if science_title_object
u.science_title = science_title_object.value
u.science_title_abbr = science_title_object.abbr
if person.main_post
u.work_post = person.main_post.short_title || ''
u.work_place = person.main_post.subdivision.title + ' ТУСУР'
u.post ||= {}
u.post.title ||= {}
$scope.updateDirectorySearch()
$scope.cleanPerson = () ->
$scope.new_person_post_speciality = null
$scope.$broadcast 'cleanPerson'
$scope.peopleInput.$setPristine() if $scope.peopleInput
$scope.submitPerson = () ->
if $scope.peopleInput && $scope.peopleInput.$invalid
$scope.peopleInput.$setSubmitted()
for _, input of $scope.peopleInput
if input && input.$name
input.$setDirty()
else
params = {}
angular.copy $scope.context, params
params['person'] = $scope.new_person
$http
.post '/manage/people', params
.success (data) ->
if $scope.people
$scope.people.push data
$scope.directory_search = null
else
$scope.person = data
$scope.cleanPerson()
$scope.hideForm()
$scope.directorySearchTrigger = () ->
$scope.directorySearch = !$scope.directorySearch
$scope.updateDirectorySearch = () ->
query = []
for key in ['name', 'surname', 'patronymic']
query.push $scope.new_person[key]
query = query.join(' ')
$scope.directorySearchTrigger()
$http
.get '/manage/people/directory_search', params: { term: query }
.success (data) ->
$scope.directorySearchTrigger()
$scope.directory_search = data
$scope.postsOf = (result) ->
result.split(';')
$scope.hideForm = () ->
$scope.personNotFound = false
$scope.directory_search = null
$scope.hideNamedBlock = () ->
$scope.blockNameValue = null
$scope.requestFormatter = (str) ->
q: str, ids: ($scope.people || []).map((p) -> p.id ) # ||[] decision is for one person case
$scope.searchResponseFormatter = (data) ->
results = []
for result in data.people
results.push result
empty_object = {
fullname: $scope.l('person.create_new')
id: false
}
results.push empty_object
return results
$scope.setSpeciality = (speciality, callback) ->
unless speciality.id #create new speciality from form
params = { speciality }
$http
.post 'manage/council_specialities', params
.success (data) -> $scope.reallySetSpeciality(data, callback)
else #set speciality id to person post
$scope.reallySetSpeciality(speciality, callback)
$scope.reallySetSpeciality = (speciality, callback) ->
$scope.new_person.post ||= {}
$scope.new_person.post.council_speciality_id = speciality.id
$scope.new_person_post_speciality = speciality
callback()
$scope.destroySpeciality = () ->
$scope.new_person.post.council_speciality_id = null
$scope.new_person_post_speciality = null
}
])
| true | angular.module('dashboard')
.directive('peopleInput', ['$http', 'localization', 'science',
($http, localization, science) ->
return {
scope:
context: '=context'
people: '=people'
person: '=person'
askPost: '@askPost'
hideSpecialitySelector: '@hideSpecialitySelector'
kind: '@kind'
specialities: '=specialities'
blockNameValue: '=blockNameValue'
editForm: '=editForm'
transclude: true
restrict: 'E'
templateUrl: 'people_input.html'
controller: ($scope, localization) ->
$scope.l = localization.l
$scope.science_dictionaries = science
$scope.isLoading = () ->
return $http.pendingRequests.length > 0
for key in ['PI:KEY:<KEY>END_PI', 'science']
$scope[key] = {}
$scope.setPerson = (obj) ->
unless obj.originalObject.id
$scope.personNotFound = true
$scope.peopleInput.$setPristine()
else
$scope.new_person = obj.originalObject
$scope.compareDictionariesValues = (normalize_string, dictionary_object) ->
current_object = dictionary_object.find (obj) ->
obj.value == normalize_string
return current_object
$scope.normalizeDictionariesValue = (string, dictionary_objects) ->
normalize_result = string.charAt(0).toUpperCase() + string.slice(1) if string
return normalize_result
$scope.fillPerson = (person) ->
u = $scope.new_person
for key in ['patronymic', 'surname', 'name']
u[key] = person[key]
u.url = "https://directory.tusur.ru/people/#{person.id}"
# Result object of scence degree
science_degree_object = $scope.compareDictionariesValues($scope.normalizeDictionariesValue(person.academic_degree),
$scope.science_dictionaries.science_degrees)
# Result object of scence title
science_title_object = $scope.compareDictionariesValues($scope.normalizeDictionariesValue(person.academic_rank),
$scope.science_dictionaries.science_titles)
if science_degree_object
u.science_degree = science_degree_object.value
u.science_degree_abbr = science_degree_object.abbr
if science_title_object
u.science_title = science_title_object.value
u.science_title_abbr = science_title_object.abbr
if person.main_post
u.work_post = person.main_post.short_title || ''
u.work_place = person.main_post.subdivision.title + ' ТУСУР'
u.post ||= {}
u.post.title ||= {}
$scope.updateDirectorySearch()
$scope.cleanPerson = () ->
$scope.new_person_post_speciality = null
$scope.$broadcast 'cleanPerson'
$scope.peopleInput.$setPristine() if $scope.peopleInput
$scope.submitPerson = () ->
if $scope.peopleInput && $scope.peopleInput.$invalid
$scope.peopleInput.$setSubmitted()
for _, input of $scope.peopleInput
if input && input.$name
input.$setDirty()
else
params = {}
angular.copy $scope.context, params
params['person'] = $scope.new_person
$http
.post '/manage/people', params
.success (data) ->
if $scope.people
$scope.people.push data
$scope.directory_search = null
else
$scope.person = data
$scope.cleanPerson()
$scope.hideForm()
$scope.directorySearchTrigger = () ->
$scope.directorySearch = !$scope.directorySearch
$scope.updateDirectorySearch = () ->
query = []
for key in ['name', 'surname', 'patronymic']
query.push $scope.new_person[key]
query = query.join(' ')
$scope.directorySearchTrigger()
$http
.get '/manage/people/directory_search', params: { term: query }
.success (data) ->
$scope.directorySearchTrigger()
$scope.directory_search = data
$scope.postsOf = (result) ->
result.split(';')
$scope.hideForm = () ->
$scope.personNotFound = false
$scope.directory_search = null
$scope.hideNamedBlock = () ->
$scope.blockNameValue = null
$scope.requestFormatter = (str) ->
q: str, ids: ($scope.people || []).map((p) -> p.id ) # ||[] decision is for one person case
$scope.searchResponseFormatter = (data) ->
results = []
for result in data.people
results.push result
empty_object = {
fullname: $scope.l('person.create_new')
id: false
}
results.push empty_object
return results
$scope.setSpeciality = (speciality, callback) ->
unless speciality.id #create new speciality from form
params = { speciality }
$http
.post 'manage/council_specialities', params
.success (data) -> $scope.reallySetSpeciality(data, callback)
else #set speciality id to person post
$scope.reallySetSpeciality(speciality, callback)
$scope.reallySetSpeciality = (speciality, callback) ->
$scope.new_person.post ||= {}
$scope.new_person.post.council_speciality_id = speciality.id
$scope.new_person_post_speciality = speciality
callback()
$scope.destroySpeciality = () ->
$scope.new_person.post.council_speciality_id = null
$scope.new_person_post_speciality = null
}
])
|
[
{
"context": "r ID of user who created request\",\n username: \"username of user who created request\",\n email: \"email of user who c",
"end": 780,
"score": 0.9815064668655396,
"start": 760,
"tag": "USERNAME",
"value": "username of user who"
},
{
"context": "nd\n service:... | noddy/service/oabutton/request.coffee | jibe-b/website | 0 |
import { Random } from 'meteor/random'
###
to create a request the url and type are required, What about story?
{
url: "url of item request is about",
type: "article OR data (OR code eventually and possibly other things)",
story: "the story of why this request / support, if supplied",
email: "email address of person to contact to request",
count: "the count of how many people support this request",
createdAt: "date request was created",
status: "help OR moderate OR progress OR hold OR refused OR received OR closed",
receiver: "unique ID that the receive endpoint will use to accept one-time submission of content",
title: "article title",
doi: "article doi",
user: {
id: "user ID of user who created request",
username: "username of user who created request",
email: "email of user who created request"
},
followup: [
{
date: "date of followup",
email:"email of this request at time of followup"
}
],
hold: {
from: "date it was put on hold",
until: "date until it is on hold to",
by: "email of who put it on hold"
},
holds: [
{"history": "of hold items, as above"}
],
refused: [
{
email: "email address of author who refused to provide content (adding themselves to dnr is implicit refusal too)",
date: "date the author refused"
}
],
received: {
date: "date the item was received",
from: "email of who it was received from",
description: "description of provided content, if available".
url: "url to where it is (remote if provided, or on our system if uploaded)"
}
}
###
API.service.oab.request = (req,uacc,fast) ->
dom
if req.dom
dom = req.dom
delete req.dom
return false if JSON.stringify(req).indexOf('<script') isnt -1
req.type ?= 'article'
req.doi = req.url if not req.doi? and req.url? and req.url.indexOf('10.') isnt -1 and req.url.split('10.')[1].indexOf('/') isnt -1
req.doi = '10.' + req.doi.split('10.')[1] if req.doi? and req.doi.indexOf('10.') isnt 0
if req.url? and req.url.indexOf('eu.alma.exlibrisgroup.com') isnt -1
req.url += (if req.url.indexOf('?') is -1 then '?' else '&') + 'oabLibris=' + Random.id()
if req.title? and typeof req.title is 'string' and req.title.length > 0 and texist = oab_request.find {title:req.title,type:req.type}
texist.cache = true
return texist
else if exists = oab_request.find {url:req.url,type:req.type}
exists.cache = true
return exists
return false if not req.test and API.service.oab.blacklist req.url
req.doi = decodeURIComponent(req.doi) if req.doi
rid = if req._id and oab_request.get(req._id) then req._id else oab_request.insert {url:req.url,type:req.type,_id:req._id}
user = if uacc then (if typeof uacc is 'string' then API.accounts.retrieve(uacc) else uacc) else undefined
if not req.user? and user and req.story
un = user.profile?.firstname ? user.username ? user.emails[0].address
req.user =
id: user._id
username: un
email: user.emails[0].address
firstname: user.profile?.firstname
lastname: user.profile?.lastname
affiliation: user.service?.openaccessbutton?.profile?.affiliation
profession: user.service?.openaccessbutton?.profile?.profession
req.count = if req.story then 1 else 0
if not fast and (not req.title or not req.email)
meta = API.service.oab.scrape req.url, dom, req.doi
if meta?.email?
for e in meta.email
isauthor = false
if meta?.author?
for a in meta.author
isauthor = a.family and e.toLowerCase().indexOf(a.family.toLowerCase()) isnt -1
if isauthor and not API.service.oab.dnr(e) and API.mail.validate(e, API.settings.service?.openaccessbutton?.mail?.pubkey).is_valid
req.email = e
if req.author
for author in req.author
try
if req.email.toLowerCase().indexOf(author.family) isnt -1
req.author_affiliation = author.affiliation[0].name
break
break
else if req.author and not req.author_affiliation
try
req.author_affiliation = req.author[0].affiliation[0].name # first on the crossref list is the first author so we assume that is the author to contact
req.keywords ?= meta?.keywords ? []
req.title ?= meta?.title ? ''
req.doi ?= meta?.doi ? ''
req.author = meta?.author ? []
req.journal = meta?.journal ? ''
req.issn = meta?.issn ? ''
req.publisher = meta?.publisher ? ''
req.year = meta?.year
if not req.email and req.author_affiliation
try
for author in req.author
if author.affiliation[0].name is req.author_affiliation
# it would be possible to lookup ORCID here if the author has one in the crossref data, but that would only get us an email for people who make it public
# previous analysis showed that this is rare. So not doing it yet
email = API.use.hunter.email {company: req.author_affiliation, first_name: author.family, last_name: author.given}, API.settings.service.openaccessbutton.hunter.api_key
if email?.email?
req.email = email.email
break
if fast and req.doi and (not req.journal or not req.year or not req.title)
try
cr = API.use.crossref.works.doi req.doi
req.title = cr.title[0]
req.author ?= cr.author
req.journal ?= cr['container-title'][0] if cr['container-title']?
req.issn ?= cr.ISSN[0] if cr.ISSN?
req.subject ?= cr.subject
req.publisher ?= cr.publisher
req.year = cr['published-print']['date-parts'][0][0] if cr['published-print']?['date-parts']? and cr['published-print']['date-parts'].length > 0 and cr['published-print']['date-parts'][0].length > 0
req.crossref_type = cr.type
req.year ?= cr.created['date-time'].split('-')[0] if cr.created?['date-time']?
if req.journal and not req.sherpa? # doing this even on fast cos we may be able to close immediately. If users say too slow now, disable this on fast again
try
sherpa = API.use.sherpa.romeo.search {jtitle:req.journal}
try req.sherpa = {color: sherpa.publishers[0].publisher[0].romeocolour[0]}
# a problem with sherpa postrestrictions data caused saves to fail, which caused further problems. Disabling this for now. Need to wrangle sherpa data into a better shape
#try
# req.sherpa.journal = sherpa.journals[0].journal[0]
# for k of req.sherpa.journal
# try
# if _.isArray(req.sherpa.journal[k]) and req.sherpa.journal[k].length is 1
# req.sherpa.journal[k] = req.sherpa.journal[k][0]
#try
# req.sherpa.publisher = sherpa.publishers[0].publisher[0]
# for k of req.sherpa.publisher
# try
# if _.isArray(req.sherpa.publisher[k]) and req.sherpa.publisher[k].length is 1
# req.sherpa.publisher[k] = req.sherpa.publisher[k][0]
if req.story
res = oab_request.search 'rating:1 AND story.exact:"' + req.story + '"'
if res.hits.total
nres = oab_request.search 'rating:0 AND story.exact:"' + req.story + '"'
req.rating = 1 if nres.hits.total is 0
req.status ?= if not req.story or not req.title or not req.email or not req.user? then "help" else "moderate"
if req.year
try
req.year = parseInt(req.year) if typeof req.year is 'string'
if req.year < 2000
req.status = 'closed'
req.closed_on_create = true
req.closed_on_create_reason = 'pre2000'
try
if fast and (new Date()).getFullYear() - req.year > 5 # only doing these on fast means only doing them via UI for now
req.status = 'closed'
req.closed_on_create = true
req.closed_on_create_reason = 'gt5'
if fast and not req.doi?
req.status = 'closed'
req.closed_on_create = true
req.closed_on_create_reason = 'nodoi'
if fast and req.crossref_type? and ['journal-article', 'proceedings-article'].indexOf(req.crossref_type) is -1
req.status = 'closed'
req.closed_on_create = true
req.closed_on_create_reason = 'notarticle'
if req.sherpa?.color? and typeof req.sherpa.color is 'string' and req.sherpa.color.toLowerCase() is 'white'
req.status = 'closed'
req.closed_on_create = true
req.closed_on_create_reason = 'sherpawhite'
if req.location?.geo
req.location.geo.lat = Math.round(req.location.geo.lat*1000)/1000 if req.location.geo.lat
req.location.geo.lon = Math.round(req.location.geo.lon*1000)/1000 if req.location.geo.lon
req.receiver = Random.id()
req._id = rid
if req.title? and typeof req.title is 'string'
try req.title = req.title.charAt(0).toUpperCase() + req.title.slice(1)
if req.journal? and typeof req.journal is 'string'
try req.journal = req.journal.charAt(0).toUpperCase() + req.journal.slice(1)
oab_request.update rid, req
if fast and req.user?.email?
try
tmpl = API.mail.template 'initiator_confirmation.html'
sub = API.service.oab.substitute tmpl.content, {_id: req._id, url: req.url, title:(req.title ? req.url) }
API.mail.send
service: 'openaccessbutton',
from: sub.from ? API.settings.service.openaccessbutton.mail.from
to: req.user.email
subject: sub.subject ? 'New request created ' + req._id
html: sub.content
if req.story
API.mail.send
service: 'openaccessbutton'
from: 'requests@openaccessbutton.org'
to: API.settings.service.openaccessbutton.notify.request
subject: 'New request created ' + req._id
text: (if API.settings.dev then 'https://dev.openaccessbutton.org/request/' else 'https://openaccessbutton.org/request/') + req._id
return req
API.service.oab.support = (rid,story,uacc) ->
return false if story and story.indexOf('<script') isnt -1
r = oab_request.get rid
if not uacc?
anons = {url:r.url,rid:r._id,type:r.type,username:'anonymous',story:story}
anons._id = oab_support.insert anons
return anons
else if ((typeof uacc is 'string' and r.user?.id isnt uacc) or r.user?.id isnt uacc?._id ) and not API.service.oab.supports(rid,uacc)?
oab_request.update rid, {count:r.count + 1}
uacc = API.accounts.retrieve(uacc) if typeof uacc is 'string'
s = {url:r.url,rid:r._id,type:r.type,uid:uacc._id,username:uacc.username,email:uacc.emails[0].address,story:story}
s.firstname = uacc.profile?.firstname
s.lastname = uacc.profile?.lastname
s._id = oab_support.insert s
return s
API.service.oab.supports = (rid,uacc,url) ->
uacc = uacc._id if typeof uacc is 'object'
matcher = {}
if rid and uacc
matcher = {uid:uacc,rid:rid}
else if rid
matcher.rid = rid
else if uacc and url
matcher = {uid:uacc,url:url}
else if uacc
matcher.uid = uacc
return oab_support.find matcher
API.service.oab.hold = (rid,days) ->
today = new Date().getTime()
date = (Math.floor(today/1000) + (days*86400)) * 1000
r = oab_request.get rid
r.holds ?= []
r.holds.push(r.hold) if r.hold
r.hold = {from:today,until:date}
r.status = 'hold'
oab_request.update rid,{hold:r.hold, holds:r.holds, status:r.status}
#API.mail.send(); # inform requestee that their request is on hold
return r
API.service.oab.refuse = (rid,reason) ->
today = new Date().getTime()
r = oab_request.get rid
r.holds ?= []
r.holds.push(r.hold) if r.hold
delete r.hold
r.refused ?= []
r.refused.push({date:today,email:r.email,reason:reason})
r.status = 'refused'
delete r.email
oab_request.update rid, {hold:'$DELETE',email:'$DELETE',holds:r.holds,refused:r.refused,status:r.status}
#API.mail.send(); # inform requestee that their request has been refused
return r
# so far automatic follow up has never been used - it should probably connect to admin rather than emailing directly
# keep this here for now though
API.service.oab.followup = (rid) ->
MAXEMAILFOLLOWUP = 5 # how many followups to one email address will we do before giving up, and can the followup count be reset or overrided somehow?
r = oab_request.get rid
r.followup ?= []
thisfollows = 0
for i in r.followup
thisfollows += 1 if i.email is r.email
today = new Date().getTime()
dnr = oab_dnr.find {email:r.email}
if dnr
return {status:'error', data:'The email address for this request has been placed on the do-not-request list, and can no longer be contacted'}
else if r.hold?.until > today
return {status:'error', data:'This request is currently on hold, so cannot be followed up yet.'}
else if thisfollows >= MAXEMAILFOLLOWUP
return {status:'error', data:'This request has already been followed up the maximum number of times.'}
else
#API.mail.send() #email the request email contact with the followup request
r.followup.push {date:today,email:r.email}
oab_request.update r._id, {followup:r.followup,status:'progress'}
return r
| 44852 |
import { Random } from 'meteor/random'
###
to create a request the url and type are required, What about story?
{
url: "url of item request is about",
type: "article OR data (OR code eventually and possibly other things)",
story: "the story of why this request / support, if supplied",
email: "email address of person to contact to request",
count: "the count of how many people support this request",
createdAt: "date request was created",
status: "help OR moderate OR progress OR hold OR refused OR received OR closed",
receiver: "unique ID that the receive endpoint will use to accept one-time submission of content",
title: "article title",
doi: "article doi",
user: {
id: "user ID of user who created request",
username: "username of user who created request",
email: "email of user who created request"
},
followup: [
{
date: "date of followup",
email:"email of this request at time of followup"
}
],
hold: {
from: "date it was put on hold",
until: "date until it is on hold to",
by: "email of who put it on hold"
},
holds: [
{"history": "of hold items, as above"}
],
refused: [
{
email: "email address of author who refused to provide content (adding themselves to dnr is implicit refusal too)",
date: "date the author refused"
}
],
received: {
date: "date the item was received",
from: "email of who it was received from",
description: "description of provided content, if available".
url: "url to where it is (remote if provided, or on our system if uploaded)"
}
}
###
API.service.oab.request = (req,uacc,fast) ->
dom
if req.dom
dom = req.dom
delete req.dom
return false if JSON.stringify(req).indexOf('<script') isnt -1
req.type ?= 'article'
req.doi = req.url if not req.doi? and req.url? and req.url.indexOf('10.') isnt -1 and req.url.split('10.')[1].indexOf('/') isnt -1
req.doi = '10.' + req.doi.split('10.')[1] if req.doi? and req.doi.indexOf('10.') isnt 0
if req.url? and req.url.indexOf('eu.alma.exlibrisgroup.com') isnt -1
req.url += (if req.url.indexOf('?') is -1 then '?' else '&') + 'oabLibris=' + Random.id()
if req.title? and typeof req.title is 'string' and req.title.length > 0 and texist = oab_request.find {title:req.title,type:req.type}
texist.cache = true
return texist
else if exists = oab_request.find {url:req.url,type:req.type}
exists.cache = true
return exists
return false if not req.test and API.service.oab.blacklist req.url
req.doi = decodeURIComponent(req.doi) if req.doi
rid = if req._id and oab_request.get(req._id) then req._id else oab_request.insert {url:req.url,type:req.type,_id:req._id}
user = if uacc then (if typeof uacc is 'string' then API.accounts.retrieve(uacc) else uacc) else undefined
if not req.user? and user and req.story
un = user.profile?.firstname ? user.username ? user.emails[0].address
req.user =
id: user._id
username: un
email: user.emails[0].address
firstname: user.profile?.firstname
lastname: user.profile?.lastname
affiliation: user.service?.openaccessbutton?.profile?.affiliation
profession: user.service?.openaccessbutton?.profile?.profession
req.count = if req.story then 1 else 0
if not fast and (not req.title or not req.email)
meta = API.service.oab.scrape req.url, dom, req.doi
if meta?.email?
for e in meta.email
isauthor = false
if meta?.author?
for a in meta.author
isauthor = a.family and e.toLowerCase().indexOf(a.family.toLowerCase()) isnt -1
if isauthor and not API.service.oab.dnr(e) and API.mail.validate(e, API.settings.service?.openaccessbutton?.mail?.pubkey).is_valid
req.email = e
if req.author
for author in req.author
try
if req.email.toLowerCase().indexOf(author.family) isnt -1
req.author_affiliation = author.affiliation[0].name
break
break
else if req.author and not req.author_affiliation
try
req.author_affiliation = req.author[0].affiliation[0].name # first on the crossref list is the first author so we assume that is the author to contact
req.keywords ?= meta?.keywords ? []
req.title ?= meta?.title ? ''
req.doi ?= meta?.doi ? ''
req.author = meta?.author ? []
req.journal = meta?.journal ? ''
req.issn = meta?.issn ? ''
req.publisher = meta?.publisher ? ''
req.year = meta?.year
if not req.email and req.author_affiliation
try
for author in req.author
if author.affiliation[0].name is req.author_affiliation
# it would be possible to lookup ORCID here if the author has one in the crossref data, but that would only get us an email for people who make it public
# previous analysis showed that this is rare. So not doing it yet
email = API.use.hunter.email {company: req.author_affiliation, first_name: author.family, last_name: author.given}, API.settings.service.openaccessbutton.hunter.api_key
if email?.email?
req.email = email.email
break
if fast and req.doi and (not req.journal or not req.year or not req.title)
try
cr = API.use.crossref.works.doi req.doi
req.title = cr.title[0]
req.author ?= cr.author
req.journal ?= cr['container-title'][0] if cr['container-title']?
req.issn ?= cr.ISSN[0] if cr.ISSN?
req.subject ?= cr.subject
req.publisher ?= cr.publisher
req.year = cr['published-print']['date-parts'][0][0] if cr['published-print']?['date-parts']? and cr['published-print']['date-parts'].length > 0 and cr['published-print']['date-parts'][0].length > 0
req.crossref_type = cr.type
req.year ?= cr.created['date-time'].split('-')[0] if cr.created?['date-time']?
if req.journal and not req.sherpa? # doing this even on fast cos we may be able to close immediately. If users say too slow now, disable this on fast again
try
sherpa = API.use.sherpa.romeo.search {jtitle:req.journal}
try req.sherpa = {color: sherpa.publishers[0].publisher[0].romeocolour[0]}
# a problem with sherpa postrestrictions data caused saves to fail, which caused further problems. Disabling this for now. Need to wrangle sherpa data into a better shape
#try
# req.sherpa.journal = sherpa.journals[0].journal[0]
# for k of req.sherpa.journal
# try
# if _.isArray(req.sherpa.journal[k]) and req.sherpa.journal[k].length is 1
# req.sherpa.journal[k] = req.sherpa.journal[k][0]
#try
# req.sherpa.publisher = sherpa.publishers[0].publisher[0]
# for k of req.sherpa.publisher
# try
# if _.isArray(req.sherpa.publisher[k]) and req.sherpa.publisher[k].length is 1
# req.sherpa.publisher[k] = req.sherpa.publisher[k][0]
if req.story
res = oab_request.search 'rating:1 AND story.exact:"' + req.story + '"'
if res.hits.total
nres = oab_request.search 'rating:0 AND story.exact:"' + req.story + '"'
req.rating = 1 if nres.hits.total is 0
req.status ?= if not req.story or not req.title or not req.email or not req.user? then "help" else "moderate"
if req.year
try
req.year = parseInt(req.year) if typeof req.year is 'string'
if req.year < 2000
req.status = 'closed'
req.closed_on_create = true
req.closed_on_create_reason = 'pre2000'
try
if fast and (new Date()).getFullYear() - req.year > 5 # only doing these on fast means only doing them via UI for now
req.status = 'closed'
req.closed_on_create = true
req.closed_on_create_reason = 'gt5'
if fast and not req.doi?
req.status = 'closed'
req.closed_on_create = true
req.closed_on_create_reason = 'nodoi'
if fast and req.crossref_type? and ['journal-article', 'proceedings-article'].indexOf(req.crossref_type) is -1
req.status = 'closed'
req.closed_on_create = true
req.closed_on_create_reason = 'notarticle'
if req.sherpa?.color? and typeof req.sherpa.color is 'string' and req.sherpa.color.toLowerCase() is 'white'
req.status = 'closed'
req.closed_on_create = true
req.closed_on_create_reason = 'sherpawhite'
if req.location?.geo
req.location.geo.lat = Math.round(req.location.geo.lat*1000)/1000 if req.location.geo.lat
req.location.geo.lon = Math.round(req.location.geo.lon*1000)/1000 if req.location.geo.lon
req.receiver = Random.id()
req._id = rid
if req.title? and typeof req.title is 'string'
try req.title = req.title.charAt(0).toUpperCase() + req.title.slice(1)
if req.journal? and typeof req.journal is 'string'
try req.journal = req.journal.charAt(0).toUpperCase() + req.journal.slice(1)
oab_request.update rid, req
if fast and req.user?.email?
try
tmpl = API.mail.template 'initiator_confirmation.html'
sub = API.service.oab.substitute tmpl.content, {_id: req._id, url: req.url, title:(req.title ? req.url) }
API.mail.send
service: 'openaccessbutton',
from: sub.from ? API.settings.service.openaccessbutton.mail.from
to: req.user.email
subject: sub.subject ? 'New request created ' + req._id
html: sub.content
if req.story
API.mail.send
service: 'openaccessbutton'
from: '<EMAIL>'
to: API.settings.service.openaccessbutton.notify.request
subject: 'New request created ' + req._id
text: (if API.settings.dev then 'https://dev.openaccessbutton.org/request/' else 'https://openaccessbutton.org/request/') + req._id
return req
API.service.oab.support = (rid,story,uacc) ->
return false if story and story.indexOf('<script') isnt -1
r = oab_request.get rid
if not uacc?
anons = {url:r.url,rid:r._id,type:r.type,username:'anonymous',story:story}
anons._id = oab_support.insert anons
return anons
else if ((typeof uacc is 'string' and r.user?.id isnt uacc) or r.user?.id isnt uacc?._id ) and not API.service.oab.supports(rid,uacc)?
oab_request.update rid, {count:r.count + 1}
uacc = API.accounts.retrieve(uacc) if typeof uacc is 'string'
s = {url:r.url,rid:r._id,type:r.type,uid:uacc._id,username:uacc.username,email:uacc.emails[0].address,story:story}
s.firstname = uacc.profile?.firstname
s.lastname = uacc.profile?.lastname
s._id = oab_support.insert s
return s
API.service.oab.supports = (rid,uacc,url) ->
uacc = uacc._id if typeof uacc is 'object'
matcher = {}
if rid and uacc
matcher = {uid:uacc,rid:rid}
else if rid
matcher.rid = rid
else if uacc and url
matcher = {uid:uacc,url:url}
else if uacc
matcher.uid = uacc
return oab_support.find matcher
API.service.oab.hold = (rid,days) ->
today = new Date().getTime()
date = (Math.floor(today/1000) + (days*86400)) * 1000
r = oab_request.get rid
r.holds ?= []
r.holds.push(r.hold) if r.hold
r.hold = {from:today,until:date}
r.status = 'hold'
oab_request.update rid,{hold:r.hold, holds:r.holds, status:r.status}
#API.mail.send(); # inform requestee that their request is on hold
return r
API.service.oab.refuse = (rid,reason) ->
today = new Date().getTime()
r = oab_request.get rid
r.holds ?= []
r.holds.push(r.hold) if r.hold
delete r.hold
r.refused ?= []
r.refused.push({date:today,email:r.email,reason:reason})
r.status = 'refused'
delete r.email
oab_request.update rid, {hold:'$DELETE',email:'$DELETE',holds:r.holds,refused:r.refused,status:r.status}
#API.mail.send(); # inform requestee that their request has been refused
return r
# so far automatic follow up has never been used - it should probably connect to admin rather than emailing directly
# keep this here for now though
API.service.oab.followup = (rid) ->
MAXEMAILFOLLOWUP = 5 # how many followups to one email address will we do before giving up, and can the followup count be reset or overrided somehow?
r = oab_request.get rid
r.followup ?= []
thisfollows = 0
for i in r.followup
thisfollows += 1 if i.email is r.email
today = new Date().getTime()
dnr = oab_dnr.find {email:r.email}
if dnr
return {status:'error', data:'The email address for this request has been placed on the do-not-request list, and can no longer be contacted'}
else if r.hold?.until > today
return {status:'error', data:'This request is currently on hold, so cannot be followed up yet.'}
else if thisfollows >= MAXEMAILFOLLOWUP
return {status:'error', data:'This request has already been followed up the maximum number of times.'}
else
#API.mail.send() #email the request email contact with the followup request
r.followup.push {date:today,email:r.email}
oab_request.update r._id, {followup:r.followup,status:'progress'}
return r
| true |
import { Random } from 'meteor/random'
###
to create a request the url and type are required, What about story?
{
url: "url of item request is about",
type: "article OR data (OR code eventually and possibly other things)",
story: "the story of why this request / support, if supplied",
email: "email address of person to contact to request",
count: "the count of how many people support this request",
createdAt: "date request was created",
status: "help OR moderate OR progress OR hold OR refused OR received OR closed",
receiver: "unique ID that the receive endpoint will use to accept one-time submission of content",
title: "article title",
doi: "article doi",
user: {
id: "user ID of user who created request",
username: "username of user who created request",
email: "email of user who created request"
},
followup: [
{
date: "date of followup",
email:"email of this request at time of followup"
}
],
hold: {
from: "date it was put on hold",
until: "date until it is on hold to",
by: "email of who put it on hold"
},
holds: [
{"history": "of hold items, as above"}
],
refused: [
{
email: "email address of author who refused to provide content (adding themselves to dnr is implicit refusal too)",
date: "date the author refused"
}
],
received: {
date: "date the item was received",
from: "email of who it was received from",
description: "description of provided content, if available".
url: "url to where it is (remote if provided, or on our system if uploaded)"
}
}
###
API.service.oab.request = (req,uacc,fast) ->
dom
if req.dom
dom = req.dom
delete req.dom
return false if JSON.stringify(req).indexOf('<script') isnt -1
req.type ?= 'article'
req.doi = req.url if not req.doi? and req.url? and req.url.indexOf('10.') isnt -1 and req.url.split('10.')[1].indexOf('/') isnt -1
req.doi = '10.' + req.doi.split('10.')[1] if req.doi? and req.doi.indexOf('10.') isnt 0
if req.url? and req.url.indexOf('eu.alma.exlibrisgroup.com') isnt -1
req.url += (if req.url.indexOf('?') is -1 then '?' else '&') + 'oabLibris=' + Random.id()
if req.title? and typeof req.title is 'string' and req.title.length > 0 and texist = oab_request.find {title:req.title,type:req.type}
texist.cache = true
return texist
else if exists = oab_request.find {url:req.url,type:req.type}
exists.cache = true
return exists
return false if not req.test and API.service.oab.blacklist req.url
req.doi = decodeURIComponent(req.doi) if req.doi
rid = if req._id and oab_request.get(req._id) then req._id else oab_request.insert {url:req.url,type:req.type,_id:req._id}
user = if uacc then (if typeof uacc is 'string' then API.accounts.retrieve(uacc) else uacc) else undefined
if not req.user? and user and req.story
un = user.profile?.firstname ? user.username ? user.emails[0].address
req.user =
id: user._id
username: un
email: user.emails[0].address
firstname: user.profile?.firstname
lastname: user.profile?.lastname
affiliation: user.service?.openaccessbutton?.profile?.affiliation
profession: user.service?.openaccessbutton?.profile?.profession
req.count = if req.story then 1 else 0
if not fast and (not req.title or not req.email)
meta = API.service.oab.scrape req.url, dom, req.doi
if meta?.email?
for e in meta.email
isauthor = false
if meta?.author?
for a in meta.author
isauthor = a.family and e.toLowerCase().indexOf(a.family.toLowerCase()) isnt -1
if isauthor and not API.service.oab.dnr(e) and API.mail.validate(e, API.settings.service?.openaccessbutton?.mail?.pubkey).is_valid
req.email = e
if req.author
for author in req.author
try
if req.email.toLowerCase().indexOf(author.family) isnt -1
req.author_affiliation = author.affiliation[0].name
break
break
else if req.author and not req.author_affiliation
try
req.author_affiliation = req.author[0].affiliation[0].name # first on the crossref list is the first author so we assume that is the author to contact
req.keywords ?= meta?.keywords ? []
req.title ?= meta?.title ? ''
req.doi ?= meta?.doi ? ''
req.author = meta?.author ? []
req.journal = meta?.journal ? ''
req.issn = meta?.issn ? ''
req.publisher = meta?.publisher ? ''
req.year = meta?.year
if not req.email and req.author_affiliation
try
for author in req.author
if author.affiliation[0].name is req.author_affiliation
# it would be possible to lookup ORCID here if the author has one in the crossref data, but that would only get us an email for people who make it public
# previous analysis showed that this is rare. So not doing it yet
email = API.use.hunter.email {company: req.author_affiliation, first_name: author.family, last_name: author.given}, API.settings.service.openaccessbutton.hunter.api_key
if email?.email?
req.email = email.email
break
if fast and req.doi and (not req.journal or not req.year or not req.title)
try
cr = API.use.crossref.works.doi req.doi
req.title = cr.title[0]
req.author ?= cr.author
req.journal ?= cr['container-title'][0] if cr['container-title']?
req.issn ?= cr.ISSN[0] if cr.ISSN?
req.subject ?= cr.subject
req.publisher ?= cr.publisher
req.year = cr['published-print']['date-parts'][0][0] if cr['published-print']?['date-parts']? and cr['published-print']['date-parts'].length > 0 and cr['published-print']['date-parts'][0].length > 0
req.crossref_type = cr.type
req.year ?= cr.created['date-time'].split('-')[0] if cr.created?['date-time']?
if req.journal and not req.sherpa? # doing this even on fast cos we may be able to close immediately. If users say too slow now, disable this on fast again
try
sherpa = API.use.sherpa.romeo.search {jtitle:req.journal}
try req.sherpa = {color: sherpa.publishers[0].publisher[0].romeocolour[0]}
# a problem with sherpa postrestrictions data caused saves to fail, which caused further problems. Disabling this for now. Need to wrangle sherpa data into a better shape
#try
# req.sherpa.journal = sherpa.journals[0].journal[0]
# for k of req.sherpa.journal
# try
# if _.isArray(req.sherpa.journal[k]) and req.sherpa.journal[k].length is 1
# req.sherpa.journal[k] = req.sherpa.journal[k][0]
#try
# req.sherpa.publisher = sherpa.publishers[0].publisher[0]
# for k of req.sherpa.publisher
# try
# if _.isArray(req.sherpa.publisher[k]) and req.sherpa.publisher[k].length is 1
# req.sherpa.publisher[k] = req.sherpa.publisher[k][0]
if req.story
res = oab_request.search 'rating:1 AND story.exact:"' + req.story + '"'
if res.hits.total
nres = oab_request.search 'rating:0 AND story.exact:"' + req.story + '"'
req.rating = 1 if nres.hits.total is 0
req.status ?= if not req.story or not req.title or not req.email or not req.user? then "help" else "moderate"
if req.year
try
req.year = parseInt(req.year) if typeof req.year is 'string'
if req.year < 2000
req.status = 'closed'
req.closed_on_create = true
req.closed_on_create_reason = 'pre2000'
try
if fast and (new Date()).getFullYear() - req.year > 5 # only doing these on fast means only doing them via UI for now
req.status = 'closed'
req.closed_on_create = true
req.closed_on_create_reason = 'gt5'
if fast and not req.doi?
req.status = 'closed'
req.closed_on_create = true
req.closed_on_create_reason = 'nodoi'
if fast and req.crossref_type? and ['journal-article', 'proceedings-article'].indexOf(req.crossref_type) is -1
req.status = 'closed'
req.closed_on_create = true
req.closed_on_create_reason = 'notarticle'
if req.sherpa?.color? and typeof req.sherpa.color is 'string' and req.sherpa.color.toLowerCase() is 'white'
req.status = 'closed'
req.closed_on_create = true
req.closed_on_create_reason = 'sherpawhite'
if req.location?.geo
req.location.geo.lat = Math.round(req.location.geo.lat*1000)/1000 if req.location.geo.lat
req.location.geo.lon = Math.round(req.location.geo.lon*1000)/1000 if req.location.geo.lon
req.receiver = Random.id()
req._id = rid
if req.title? and typeof req.title is 'string'
try req.title = req.title.charAt(0).toUpperCase() + req.title.slice(1)
if req.journal? and typeof req.journal is 'string'
try req.journal = req.journal.charAt(0).toUpperCase() + req.journal.slice(1)
oab_request.update rid, req
if fast and req.user?.email?
try
tmpl = API.mail.template 'initiator_confirmation.html'
sub = API.service.oab.substitute tmpl.content, {_id: req._id, url: req.url, title:(req.title ? req.url) }
API.mail.send
service: 'openaccessbutton',
from: sub.from ? API.settings.service.openaccessbutton.mail.from
to: req.user.email
subject: sub.subject ? 'New request created ' + req._id
html: sub.content
if req.story
API.mail.send
service: 'openaccessbutton'
from: 'PI:EMAIL:<EMAIL>END_PI'
to: API.settings.service.openaccessbutton.notify.request
subject: 'New request created ' + req._id
text: (if API.settings.dev then 'https://dev.openaccessbutton.org/request/' else 'https://openaccessbutton.org/request/') + req._id
return req
API.service.oab.support = (rid,story,uacc) ->
return false if story and story.indexOf('<script') isnt -1
r = oab_request.get rid
if not uacc?
anons = {url:r.url,rid:r._id,type:r.type,username:'anonymous',story:story}
anons._id = oab_support.insert anons
return anons
else if ((typeof uacc is 'string' and r.user?.id isnt uacc) or r.user?.id isnt uacc?._id ) and not API.service.oab.supports(rid,uacc)?
oab_request.update rid, {count:r.count + 1}
uacc = API.accounts.retrieve(uacc) if typeof uacc is 'string'
s = {url:r.url,rid:r._id,type:r.type,uid:uacc._id,username:uacc.username,email:uacc.emails[0].address,story:story}
s.firstname = uacc.profile?.firstname
s.lastname = uacc.profile?.lastname
s._id = oab_support.insert s
return s
API.service.oab.supports = (rid,uacc,url) ->
uacc = uacc._id if typeof uacc is 'object'
matcher = {}
if rid and uacc
matcher = {uid:uacc,rid:rid}
else if rid
matcher.rid = rid
else if uacc and url
matcher = {uid:uacc,url:url}
else if uacc
matcher.uid = uacc
return oab_support.find matcher
API.service.oab.hold = (rid,days) ->
today = new Date().getTime()
date = (Math.floor(today/1000) + (days*86400)) * 1000
r = oab_request.get rid
r.holds ?= []
r.holds.push(r.hold) if r.hold
r.hold = {from:today,until:date}
r.status = 'hold'
oab_request.update rid,{hold:r.hold, holds:r.holds, status:r.status}
#API.mail.send(); # inform requestee that their request is on hold
return r
API.service.oab.refuse = (rid,reason) ->
today = new Date().getTime()
r = oab_request.get rid
r.holds ?= []
r.holds.push(r.hold) if r.hold
delete r.hold
r.refused ?= []
r.refused.push({date:today,email:r.email,reason:reason})
r.status = 'refused'
delete r.email
oab_request.update rid, {hold:'$DELETE',email:'$DELETE',holds:r.holds,refused:r.refused,status:r.status}
#API.mail.send(); # inform requestee that their request has been refused
return r
# so far automatic follow up has never been used - it should probably connect to admin rather than emailing directly
# keep this here for now though
API.service.oab.followup = (rid) ->
MAXEMAILFOLLOWUP = 5 # how many followups to one email address will we do before giving up, and can the followup count be reset or overrided somehow?
r = oab_request.get rid
r.followup ?= []
thisfollows = 0
for i in r.followup
thisfollows += 1 if i.email is r.email
today = new Date().getTime()
dnr = oab_dnr.find {email:r.email}
if dnr
return {status:'error', data:'The email address for this request has been placed on the do-not-request list, and can no longer be contacted'}
else if r.hold?.until > today
return {status:'error', data:'This request is currently on hold, so cannot be followed up yet.'}
else if thisfollows >= MAXEMAILFOLLOWUP
return {status:'error', data:'This request has already been followed up the maximum number of times.'}
else
#API.mail.send() #email the request email contact with the followup request
r.followup.push {date:today,email:r.email}
oab_request.update r._id, {followup:r.followup,status:'progress'}
return r
|
[
{
"context": "\":\n _lastBackupHash: \"ba46f32e916ddcbae202ed91f85ef9999eb18ec3\"\n gistId: \"be0c571e97df1e57f60ae9abd7e75573\"\n ",
"end": 1620,
"score": 0.9253738522529602,
"start": 1605,
"tag": "PASSWORD",
"value": "85ef9999eb18ec3"
},
{
"context": "df1e57f60ae9abd7e75573\"... | config/config.cson | concon121/atom-quickstart | 0 | "*":
"atom-beautify":
bash:
beautify_on_save: true
general:
_analyticsUserId: "d22e841b-58b7-4104-9647-1129661e82c2"
java: {}
js:
beautify_on_save: true
end_with_newline: true
indent_size: 2
jslint_happy: true
space_after_anon_function: true
json:
beautify_on_save: true
end_with_newline: true
indent_size: 2
jslint_happy: true
space_after_anon_function: true
markdown:
default_beautifier: "Remark"
puppet:
beautify_on_save: true
ruby:
beautify_on_save: true
"atom-maven":
classpathFileName: ".atom-classpath"
"autocomplete-java":
classpathFilePath: ".atom-classpath"
refreshClassOnSave: false
core:
closeDeletedFileTabs: true
followSymlinks: false
openEmptyEditorOnStart: false
telemetryConsent: "no"
"exception-reporting":
userId: "110bb6f9-b221-46bb-894e-cc3b978a51b6"
"file-types":
template: "source.yaml.cf"
"java-generator":
toggles:
appendThisToGetters: true
generateGettersThenSetters: true
"linter-eslint":
fixOnSave: true
lintHtmlFiles: true
"linter-javac":
classpathFilename: ".atom-classpath"
"linter-js-standard":
checkStyleDevDependencies: true
honorStyleSettings: false
lintHtmlFiles: true
lintMarkdownFiles: true
showEslintRules: true
style: "happiness"
"linter-jshint":
lintInlineJavaScript: true
"linter-json-lint":
allowComments: true
"linter-ui-default":
showPanel: true
"sync-settings":
_lastBackupHash: "ba46f32e916ddcbae202ed91f85ef9999eb18ec3"
gistId: "be0c571e97df1e57f60ae9abd7e75573"
personalAccessToken: "8cac091ae422876fa62b8a8cb9a370fb2d78376b"
quietUpdateCheck: true
"tool-bar":
iconSize: "16px"
position: "Right"
"vim-mode-plus-ex-mode":
notifiedUseExMode: true
welcome:
showOnStartup: false
| 6752 | "*":
"atom-beautify":
bash:
beautify_on_save: true
general:
_analyticsUserId: "d22e841b-58b7-4104-9647-1129661e82c2"
java: {}
js:
beautify_on_save: true
end_with_newline: true
indent_size: 2
jslint_happy: true
space_after_anon_function: true
json:
beautify_on_save: true
end_with_newline: true
indent_size: 2
jslint_happy: true
space_after_anon_function: true
markdown:
default_beautifier: "Remark"
puppet:
beautify_on_save: true
ruby:
beautify_on_save: true
"atom-maven":
classpathFileName: ".atom-classpath"
"autocomplete-java":
classpathFilePath: ".atom-classpath"
refreshClassOnSave: false
core:
closeDeletedFileTabs: true
followSymlinks: false
openEmptyEditorOnStart: false
telemetryConsent: "no"
"exception-reporting":
userId: "110bb6f9-b221-46bb-894e-cc3b978a51b6"
"file-types":
template: "source.yaml.cf"
"java-generator":
toggles:
appendThisToGetters: true
generateGettersThenSetters: true
"linter-eslint":
fixOnSave: true
lintHtmlFiles: true
"linter-javac":
classpathFilename: ".atom-classpath"
"linter-js-standard":
checkStyleDevDependencies: true
honorStyleSettings: false
lintHtmlFiles: true
lintMarkdownFiles: true
showEslintRules: true
style: "happiness"
"linter-jshint":
lintInlineJavaScript: true
"linter-json-lint":
allowComments: true
"linter-ui-default":
showPanel: true
"sync-settings":
_lastBackupHash: "ba46f32e916ddcbae202ed91f<PASSWORD>"
gistId: "be0c571e97df1e57f60ae9abd7e75573"
personalAccessToken: "<KEY>"
quietUpdateCheck: true
"tool-bar":
iconSize: "16px"
position: "Right"
"vim-mode-plus-ex-mode":
notifiedUseExMode: true
welcome:
showOnStartup: false
| true | "*":
"atom-beautify":
bash:
beautify_on_save: true
general:
_analyticsUserId: "d22e841b-58b7-4104-9647-1129661e82c2"
java: {}
js:
beautify_on_save: true
end_with_newline: true
indent_size: 2
jslint_happy: true
space_after_anon_function: true
json:
beautify_on_save: true
end_with_newline: true
indent_size: 2
jslint_happy: true
space_after_anon_function: true
markdown:
default_beautifier: "Remark"
puppet:
beautify_on_save: true
ruby:
beautify_on_save: true
"atom-maven":
classpathFileName: ".atom-classpath"
"autocomplete-java":
classpathFilePath: ".atom-classpath"
refreshClassOnSave: false
core:
closeDeletedFileTabs: true
followSymlinks: false
openEmptyEditorOnStart: false
telemetryConsent: "no"
"exception-reporting":
userId: "110bb6f9-b221-46bb-894e-cc3b978a51b6"
"file-types":
template: "source.yaml.cf"
"java-generator":
toggles:
appendThisToGetters: true
generateGettersThenSetters: true
"linter-eslint":
fixOnSave: true
lintHtmlFiles: true
"linter-javac":
classpathFilename: ".atom-classpath"
"linter-js-standard":
checkStyleDevDependencies: true
honorStyleSettings: false
lintHtmlFiles: true
lintMarkdownFiles: true
showEslintRules: true
style: "happiness"
"linter-jshint":
lintInlineJavaScript: true
"linter-json-lint":
allowComments: true
"linter-ui-default":
showPanel: true
"sync-settings":
_lastBackupHash: "ba46f32e916ddcbae202ed91fPI:PASSWORD:<PASSWORD>END_PI"
gistId: "be0c571e97df1e57f60ae9abd7e75573"
personalAccessToken: "PI:KEY:<KEY>END_PI"
quietUpdateCheck: true
"tool-bar":
iconSize: "16px"
position: "Right"
"vim-mode-plus-ex-mode":
notifiedUseExMode: true
welcome:
showOnStartup: false
|
[
{
"context": " other_keys = _.without([\"enable_auto_attendant\",\"enable_custom_greeting\",\"enable_g",
"end": 1718,
"score": 0.5921764373779297,
"start": 1718,
"tag": "KEY",
"value": ""
},
{
"context": " other_keys = _.without([\"enable_auto_attendant... | pages/group_settings/call_settings/call_settings_page.coffee | signonsridhar/sridhar_hbs | 0 | define([
'bases/page'
'models/group/group',
'modules/set_vm/set_vm',
'modules/file_uploader/file_uploader',
'modules/settings/change_voicemail_pin/change_voicemail_pin',
'modules/set_group_ring/set_group_ring',
'modules/auto_attendant_settings/auto_attendant_settings',
'models/auth/auth',
'models/settings/settings',
'modules/tab/tab',
'_'
], (BasePage,Group,SetVM,EnableCustomGreeting,ChangeVMPin,EnableGroupRing,EnableAutoAttendant,Auth,Settings,Tab)->
BasePage.extend({
init:($elem, options)->
this.setup_viewmodel({
})
if(options.models.group.value('group_name'))
this.viewmodel.attr('group_name',options.models.group.attr('group_name'))
this.render('group_settings/call_settings/call_settings_page')
this.on()
if(options.models.group.value('group_name') == 'Main')
this.viewmodel.attr("is_main_group",true)
this.options.group_options = new Tab(this.find('.main_group_tabs_container_js'), {
type:'call_settings_horizontal',
tabs:{
group: options.models.group
map:{
enable_auto_attendant:['Use Auto-Attendant Greeting',EnableAutoAttendant]
enable_custom_greeting: ['Use Custom Greeting',EnableCustomGreeting]
enable_group_ring: ['Ring Call Group Members',EnableGroupRing]
}
change:(key, item)=>
other_keys = _.without(["enable_auto_attendant","enable_custom_greeting","enable_group_ring"],key)
#hide other tabs
_.each other_keys, (key_map, map_item)=>
this.element.find('.'+key_map+ '_container_js').hide()
#show selected tab
this.element.find('.'+key+ '_container_js').show()
this.key = new item[1](this.element.find('.'+key+ '_container_js'),{group:options.models.group})
#if no greetings, no api call
if(!options.models.group.attr('has_custom_greeting') && key == "enable_custom_greeting")
return;
_.each other_keys, (key_map, map_item)=>
options.models.group.attr(key_map,false)
#setting selected option to true
options.models.group.attr(key,true)
req = {
groupid: options.models.group.attr('groupid')
enable_auto_attendant: options.models.group.attr('enable_auto_attendant')
enable_custom_greeting: options.models.group.attr('enable_custom_greeting')
enable_group_ring: options.models.group.attr('enable_group_ring')
}
#updating settings
options.models.group.update_group_settings(req).done(()=>
).fail((resp)=>
console.log("setgroupsettings api failed")
)
renderer:(key, value)=>
"<span>#{value[0]}</span>"
}
})
if(options.models.group.attr('enable_auto_attendant'))
this.options.group_options.set_active('enable_auto_attendant')
this.key = new EnableAutoAttendant(this.element.find('.enable_auto_attendant_container_js'),{group:options.models.group})
else if(options.models.group.attr('enable_custom_greeting'))
this.options.group_options.set_active('enable_custom_greeting')
this.key = new EnableCustomGreeting(this.element.find('.enable_custom_greeting_container_js'),{group:options.models.group})
else if(options.models.group.attr('enable_group_ring'))
this.options.group_options.set_active('enable_group_ring')
this.key = new EnableGroupRing(this.element.find('.enable_group_ring_container_js'),{group:options.models.group})
else
this.auto_attendant_option = new EnableAutoAttendant(this.find('.enable_auto_attendant_container_js'),{group:options.models.group})
this.upload_greetings = new EnableCustomGreeting(this.find('.enable_custom_greeting_container_js'),{group:options.models.group})
this.set_group_ring = new EnableGroupRing(this.find('.enable_group_ring_container_js'),{group:options.models.group})
this.set_vm = new SetVM(this.find('.enable_vm_forward_email_container_js'),{group:options.models.group})
#this part is for reusing module change_voicemail_pin
window.settings = this.settings = this.options.settings = new Settings(Auth.get_auth().get_user().serialize())
if(this.options.models.group.attr('extensions'))
BaseModel = can.Model.extend({},{})
this.options.model = new BaseModel({extension_number: this.options.models.group.attr('extensions.0.extension_number')})
this.change_vm_pin = new ChangeVMPin(this.find('.vmpin_container_js'),this.options)
})
) | 139742 | define([
'bases/page'
'models/group/group',
'modules/set_vm/set_vm',
'modules/file_uploader/file_uploader',
'modules/settings/change_voicemail_pin/change_voicemail_pin',
'modules/set_group_ring/set_group_ring',
'modules/auto_attendant_settings/auto_attendant_settings',
'models/auth/auth',
'models/settings/settings',
'modules/tab/tab',
'_'
], (BasePage,Group,SetVM,EnableCustomGreeting,ChangeVMPin,EnableGroupRing,EnableAutoAttendant,Auth,Settings,Tab)->
BasePage.extend({
init:($elem, options)->
this.setup_viewmodel({
})
if(options.models.group.value('group_name'))
this.viewmodel.attr('group_name',options.models.group.attr('group_name'))
this.render('group_settings/call_settings/call_settings_page')
this.on()
if(options.models.group.value('group_name') == 'Main')
this.viewmodel.attr("is_main_group",true)
this.options.group_options = new Tab(this.find('.main_group_tabs_container_js'), {
type:'call_settings_horizontal',
tabs:{
group: options.models.group
map:{
enable_auto_attendant:['Use Auto-Attendant Greeting',EnableAutoAttendant]
enable_custom_greeting: ['Use Custom Greeting',EnableCustomGreeting]
enable_group_ring: ['Ring Call Group Members',EnableGroupRing]
}
change:(key, item)=>
other_keys = _.without(["enable<KEY>_auto<KEY>_attendant","enable_<KEY>greeting","enable<KEY>_group<KEY>_ring"],key)
#hide other tabs
_.each other_keys, (key_map, map_item)=>
this.element.find('.'+key_map+ '_container_js').hide()
#show selected tab
this.element.find('.'+key+ '_container_js').show()
this.key = new item[1](this.element.find('.'+key+ '_container_js'),{group:options.models.group})
#if no greetings, no api call
if(!options.models.group.attr('has_custom_greeting') && key == "<KEY>custom_<KEY>")
return;
_.each other_keys, (key_map, map_item)=>
options.models.group.attr(key_map,false)
#setting selected option to true
options.models.group.attr(key,true)
req = {
groupid: options.models.group.attr('groupid')
enable_auto_attendant: options.models.group.attr('enable_auto_attendant')
enable_custom_greeting: options.models.group.attr('enable_custom_greeting')
enable_group_ring: options.models.group.attr('enable_group_ring')
}
#updating settings
options.models.group.update_group_settings(req).done(()=>
).fail((resp)=>
console.log("setgroupsettings api failed")
)
renderer:(key, value)=>
"<span>#{value[0]}</span>"
}
})
if(options.models.group.attr('enable_auto_attendant'))
this.options.group_options.set_active('enable_auto_attendant')
this.key = new EnableAutoAttendant(this.element.find('.enable_auto_attendant_container_js'),{group:options.models.group})
else if(options.models.group.attr('enable_custom_greeting'))
this.options.group_options.set_active('enable_custom_greeting')
this.key = new EnableCustomGreeting(this.element.find('.enable_custom_greeting_container_js'),{group:options.models.group})
else if(options.models.group.attr('enable_group_ring'))
this.options.group_options.set_active('enable_group_ring')
this.key = new EnableGroupRing(this.element.find('.enable_group_ring_container_js'),{group:options.models.group})
else
this.auto_attendant_option = new EnableAutoAttendant(this.find('.enable_auto_attendant_container_js'),{group:options.models.group})
this.upload_greetings = new EnableCustomGreeting(this.find('.enable_custom_greeting_container_js'),{group:options.models.group})
this.set_group_ring = new EnableGroupRing(this.find('.enable_group_ring_container_js'),{group:options.models.group})
this.set_vm = new SetVM(this.find('.enable_vm_forward_email_container_js'),{group:options.models.group})
#this part is for reusing module change_voicemail_pin
window.settings = this.settings = this.options.settings = new Settings(Auth.get_auth().get_user().serialize())
if(this.options.models.group.attr('extensions'))
BaseModel = can.Model.extend({},{})
this.options.model = new BaseModel({extension_number: this.options.models.group.attr('extensions.0.extension_number')})
this.change_vm_pin = new ChangeVMPin(this.find('.vmpin_container_js'),this.options)
})
) | true | define([
'bases/page'
'models/group/group',
'modules/set_vm/set_vm',
'modules/file_uploader/file_uploader',
'modules/settings/change_voicemail_pin/change_voicemail_pin',
'modules/set_group_ring/set_group_ring',
'modules/auto_attendant_settings/auto_attendant_settings',
'models/auth/auth',
'models/settings/settings',
'modules/tab/tab',
'_'
], (BasePage,Group,SetVM,EnableCustomGreeting,ChangeVMPin,EnableGroupRing,EnableAutoAttendant,Auth,Settings,Tab)->
BasePage.extend({
init:($elem, options)->
this.setup_viewmodel({
})
if(options.models.group.value('group_name'))
this.viewmodel.attr('group_name',options.models.group.attr('group_name'))
this.render('group_settings/call_settings/call_settings_page')
this.on()
if(options.models.group.value('group_name') == 'Main')
this.viewmodel.attr("is_main_group",true)
this.options.group_options = new Tab(this.find('.main_group_tabs_container_js'), {
type:'call_settings_horizontal',
tabs:{
group: options.models.group
map:{
enable_auto_attendant:['Use Auto-Attendant Greeting',EnableAutoAttendant]
enable_custom_greeting: ['Use Custom Greeting',EnableCustomGreeting]
enable_group_ring: ['Ring Call Group Members',EnableGroupRing]
}
change:(key, item)=>
other_keys = _.without(["enablePI:KEY:<KEY>END_PI_autoPI:KEY:<KEY>END_PI_attendant","enable_PI:KEY:<KEY>END_PIgreeting","enablePI:KEY:<KEY>END_PI_groupPI:KEY:<KEY>END_PI_ring"],key)
#hide other tabs
_.each other_keys, (key_map, map_item)=>
this.element.find('.'+key_map+ '_container_js').hide()
#show selected tab
this.element.find('.'+key+ '_container_js').show()
this.key = new item[1](this.element.find('.'+key+ '_container_js'),{group:options.models.group})
#if no greetings, no api call
if(!options.models.group.attr('has_custom_greeting') && key == "PI:KEY:<KEY>END_PIcustom_PI:KEY:<KEY>END_PI")
return;
_.each other_keys, (key_map, map_item)=>
options.models.group.attr(key_map,false)
#setting selected option to true
options.models.group.attr(key,true)
req = {
groupid: options.models.group.attr('groupid')
enable_auto_attendant: options.models.group.attr('enable_auto_attendant')
enable_custom_greeting: options.models.group.attr('enable_custom_greeting')
enable_group_ring: options.models.group.attr('enable_group_ring')
}
#updating settings
options.models.group.update_group_settings(req).done(()=>
).fail((resp)=>
console.log("setgroupsettings api failed")
)
renderer:(key, value)=>
"<span>#{value[0]}</span>"
}
})
if(options.models.group.attr('enable_auto_attendant'))
this.options.group_options.set_active('enable_auto_attendant')
this.key = new EnableAutoAttendant(this.element.find('.enable_auto_attendant_container_js'),{group:options.models.group})
else if(options.models.group.attr('enable_custom_greeting'))
this.options.group_options.set_active('enable_custom_greeting')
this.key = new EnableCustomGreeting(this.element.find('.enable_custom_greeting_container_js'),{group:options.models.group})
else if(options.models.group.attr('enable_group_ring'))
this.options.group_options.set_active('enable_group_ring')
this.key = new EnableGroupRing(this.element.find('.enable_group_ring_container_js'),{group:options.models.group})
else
this.auto_attendant_option = new EnableAutoAttendant(this.find('.enable_auto_attendant_container_js'),{group:options.models.group})
this.upload_greetings = new EnableCustomGreeting(this.find('.enable_custom_greeting_container_js'),{group:options.models.group})
this.set_group_ring = new EnableGroupRing(this.find('.enable_group_ring_container_js'),{group:options.models.group})
this.set_vm = new SetVM(this.find('.enable_vm_forward_email_container_js'),{group:options.models.group})
#this part is for reusing module change_voicemail_pin
window.settings = this.settings = this.options.settings = new Settings(Auth.get_auth().get_user().serialize())
if(this.options.models.group.attr('extensions'))
BaseModel = can.Model.extend({},{})
this.options.model = new BaseModel({extension_number: this.options.models.group.attr('extensions.0.extension_number')})
this.change_vm_pin = new ChangeVMPin(this.find('.vmpin_container_js'),this.options)
})
) |
[
{
"context": "# anison.js\n# https://github.com/hdemon/anison.js\n#\n# Copyright (c) 2014 Masami Yonehara\n",
"end": 39,
"score": 0.9996045231819153,
"start": 33,
"tag": "USERNAME",
"value": "hdemon"
},
{
"context": "github.com/hdemon/anison.js\n#\n# Copyright (c) 2014 Masami Yonehar... | lib/anison.coffee | hdemon/anison.js | 1 | # anison.js
# https://github.com/hdemon/anison.js
#
# Copyright (c) 2014 Masami Yonehara
# Licensed under the MIT license.
request = require 'request'
Promise = require 'bluebird'
$ = require 'cheerio'
Song = require './song'
Anison = {}
Anison._getSearchHtml = (title) ->
new Promise (resolve, reject) =>
request
url: "http://anison.info/data/n.php?q=#{encodeURIComponent title}&m=pro",
headers:
'User-Agent': 'request'
(err, res, body) -> resolve body
Anison._parseAnimeId = (searchHtmlBody) ->
_$ = $.load searchHtmlBody
Number _$(".sorted td[axis='sstring'] a").attr("href").toString().match(/\d{1,}/g)[0]
Anison._getAnimeId = (title) ->
new Promise (resolve, reject) ->
Anison._getSearchHtml(title)
.then(Anison._parseAnimeId)
.then (animeId) -> resolve animeId
Anison._getSongsHtml = (animeId) ->
new Promise (resolve, reject) ->
request
url: "http://anison.info/data/program/#{animeId}.html",
headers:
'User-Agent': 'request'
(err, res, body) -> resolve body
Anison._parseSongsHtml = (songsHtml) ->
array = []
$.load(songsHtml)(".sorted tbody tr").each ->
array.push new Song $(@)
array
Anison.get = (title) ->
new Promise (resolve, reject) ->
Anison._getAnimeId(title)
.then(Anison._getSongsHtml)
.then(Anison._parseSongsHtml)
.then (songs) -> resolve songs
module.exports = Anison
| 16879 | # anison.js
# https://github.com/hdemon/anison.js
#
# Copyright (c) 2014 <NAME>
# Licensed under the MIT license.
request = require 'request'
Promise = require 'bluebird'
$ = require 'cheerio'
Song = require './song'
Anison = {}
Anison._getSearchHtml = (title) ->
new Promise (resolve, reject) =>
request
url: "http://anison.info/data/n.php?q=#{encodeURIComponent title}&m=pro",
headers:
'User-Agent': 'request'
(err, res, body) -> resolve body
Anison._parseAnimeId = (searchHtmlBody) ->
_$ = $.load searchHtmlBody
Number _$(".sorted td[axis='sstring'] a").attr("href").toString().match(/\d{1,}/g)[0]
Anison._getAnimeId = (title) ->
new Promise (resolve, reject) ->
Anison._getSearchHtml(title)
.then(Anison._parseAnimeId)
.then (animeId) -> resolve animeId
Anison._getSongsHtml = (animeId) ->
new Promise (resolve, reject) ->
request
url: "http://anison.info/data/program/#{animeId}.html",
headers:
'User-Agent': 'request'
(err, res, body) -> resolve body
Anison._parseSongsHtml = (songsHtml) ->
array = []
$.load(songsHtml)(".sorted tbody tr").each ->
array.push new Song $(@)
array
Anison.get = (title) ->
new Promise (resolve, reject) ->
Anison._getAnimeId(title)
.then(Anison._getSongsHtml)
.then(Anison._parseSongsHtml)
.then (songs) -> resolve songs
module.exports = Anison
| true | # anison.js
# https://github.com/hdemon/anison.js
#
# Copyright (c) 2014 PI:NAME:<NAME>END_PI
# Licensed under the MIT license.
request = require 'request'
Promise = require 'bluebird'
$ = require 'cheerio'
Song = require './song'
Anison = {}
Anison._getSearchHtml = (title) ->
new Promise (resolve, reject) =>
request
url: "http://anison.info/data/n.php?q=#{encodeURIComponent title}&m=pro",
headers:
'User-Agent': 'request'
(err, res, body) -> resolve body
Anison._parseAnimeId = (searchHtmlBody) ->
_$ = $.load searchHtmlBody
Number _$(".sorted td[axis='sstring'] a").attr("href").toString().match(/\d{1,}/g)[0]
Anison._getAnimeId = (title) ->
new Promise (resolve, reject) ->
Anison._getSearchHtml(title)
.then(Anison._parseAnimeId)
.then (animeId) -> resolve animeId
Anison._getSongsHtml = (animeId) ->
new Promise (resolve, reject) ->
request
url: "http://anison.info/data/program/#{animeId}.html",
headers:
'User-Agent': 'request'
(err, res, body) -> resolve body
Anison._parseSongsHtml = (songsHtml) ->
array = []
$.load(songsHtml)(".sorted tbody tr").each ->
array.push new Song $(@)
array
Anison.get = (title) ->
new Promise (resolve, reject) ->
Anison._getAnimeId(title)
.then(Anison._getSongsHtml)
.then(Anison._parseSongsHtml)
.then (songs) -> resolve songs
module.exports = Anison
|
[
{
"context": " host: \"localhost\"\n # username: \"username\"\n # password: \"password\"\n # })\n #\n ",
"end": 1630,
"score": 0.9980002641677856,
"start": 1622,
"tag": "USERNAME",
"value": "username"
},
{
"context": " username: \"username\"\n # ... | lib/driver/driver.coffee | wanbok/mongo-model | 1 | _ = require 'underscore'
# ### Driver.
module.exports = Driver =
# Makes CRUD operation to throw error if there's something wrong (in native
# mongo driver by default it's false).
safe: true
# Update all elements, not just first (in native mongo driver by default it's false).
multi: true
# Generates short and nice string ids (native mongo driver by default generates
# BSON::ObjectId ids).
# Set it as `null` if You want to disable it.
idSize: 6
idSymbols: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".split('')
generateId: ->
[id, count] = ["", @idSize + 1]
while count -= 1
rand = Math.floor(Math.random() * @idSymbols.length)
id += @idSymbols[rand]
id
# Setting for pagination helper.
perPage: 25
maxPerPage: 100
# Handy shortcut for configuring.
configure: (options) -> _(@).extend options
# Handy shortcut, also support usage with callback.
# It's not actually async, but for consistency with other API it also
# support callback-style usage.
server: (args...) ->
callback = args.pop() if _.isFunction _(args).last()
server = new Driver.Server(args...)
process.nextTick -> callback null, server if callback
server
# Get database by alias, by using connection setting defined in options.
# It cache database and returns the same for the next calls.
#
# Sample:
#
# Define Your setting.
#
# Driver.configure({
# databases:
# blog:
# name: "blog_production"
# default:
# name: "default_production"
# host: "localhost"
# username: "username"
# password: "password"
# })
#
# And now You can use database alias to get the actual database.
#
# mongo.db 'blog', (err, db) -> ...
#
db: (dbAlias..., callback) ->
dbAlias = dbAlias[0] || 'default'
throw new Error "callback required!" unless callback
@dbCache ||= {}
if db = @dbCache[dbAlias]
callback null, db
else
dbOptions = @databases?[dbAlias] || {}
# throw new Error "no setting for '#{dbAlias}' db alias!" unless dbOptions
server = @server dbOptions.host, dbOptions.port, dbOptions.options
dbName = dbOptions.name || 'default'
# throw new Error "no database name for '#{dbAlias}' db alias!" unless dbName
server.db dbName, (err, db) =>
return callback err if err
if dbOptions.username
db.authenticate dbOptions.username, dbOptions.password, (err, db) =>
return callback err if err
@dbCache[dbAlias] = db
callback null, db
else
@dbCache[dbAlias] = db
callback null, db | 38079 | _ = require 'underscore'
# ### Driver.
module.exports = Driver =
# Makes CRUD operation to throw error if there's something wrong (in native
# mongo driver by default it's false).
safe: true
# Update all elements, not just first (in native mongo driver by default it's false).
multi: true
# Generates short and nice string ids (native mongo driver by default generates
# BSON::ObjectId ids).
# Set it as `null` if You want to disable it.
idSize: 6
idSymbols: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".split('')
generateId: ->
[id, count] = ["", @idSize + 1]
while count -= 1
rand = Math.floor(Math.random() * @idSymbols.length)
id += @idSymbols[rand]
id
# Setting for pagination helper.
perPage: 25
maxPerPage: 100
# Handy shortcut for configuring.
configure: (options) -> _(@).extend options
# Handy shortcut, also support usage with callback.
# It's not actually async, but for consistency with other API it also
# support callback-style usage.
server: (args...) ->
callback = args.pop() if _.isFunction _(args).last()
server = new Driver.Server(args...)
process.nextTick -> callback null, server if callback
server
# Get database by alias, by using connection setting defined in options.
# It cache database and returns the same for the next calls.
#
# Sample:
#
# Define Your setting.
#
# Driver.configure({
# databases:
# blog:
# name: "blog_production"
# default:
# name: "default_production"
# host: "localhost"
# username: "username"
# password: "<PASSWORD>"
# })
#
# And now You can use database alias to get the actual database.
#
# mongo.db 'blog', (err, db) -> ...
#
db: (dbAlias..., callback) ->
dbAlias = dbAlias[0] || 'default'
throw new Error "callback required!" unless callback
@dbCache ||= {}
if db = @dbCache[dbAlias]
callback null, db
else
dbOptions = @databases?[dbAlias] || {}
# throw new Error "no setting for '#{dbAlias}' db alias!" unless dbOptions
server = @server dbOptions.host, dbOptions.port, dbOptions.options
dbName = dbOptions.name || 'default'
# throw new Error "no database name for '#{dbAlias}' db alias!" unless dbName
server.db dbName, (err, db) =>
return callback err if err
if dbOptions.username
db.authenticate dbOptions.username, dbOptions.password, (err, db) =>
return callback err if err
@dbCache[dbAlias] = db
callback null, db
else
@dbCache[dbAlias] = db
callback null, db | true | _ = require 'underscore'
# ### Driver.
module.exports = Driver =
# Makes CRUD operation to throw error if there's something wrong (in native
# mongo driver by default it's false).
safe: true
# Update all elements, not just first (in native mongo driver by default it's false).
multi: true
# Generates short and nice string ids (native mongo driver by default generates
# BSON::ObjectId ids).
# Set it as `null` if You want to disable it.
idSize: 6
idSymbols: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".split('')
generateId: ->
[id, count] = ["", @idSize + 1]
while count -= 1
rand = Math.floor(Math.random() * @idSymbols.length)
id += @idSymbols[rand]
id
# Setting for pagination helper.
perPage: 25
maxPerPage: 100
# Handy shortcut for configuring.
configure: (options) -> _(@).extend options
# Handy shortcut, also support usage with callback.
# It's not actually async, but for consistency with other API it also
# support callback-style usage.
server: (args...) ->
callback = args.pop() if _.isFunction _(args).last()
server = new Driver.Server(args...)
process.nextTick -> callback null, server if callback
server
# Get database by alias, by using connection setting defined in options.
# It cache database and returns the same for the next calls.
#
# Sample:
#
# Define Your setting.
#
# Driver.configure({
# databases:
# blog:
# name: "blog_production"
# default:
# name: "default_production"
# host: "localhost"
# username: "username"
# password: "PI:PASSWORD:<PASSWORD>END_PI"
# })
#
# And now You can use database alias to get the actual database.
#
# mongo.db 'blog', (err, db) -> ...
#
db: (dbAlias..., callback) ->
dbAlias = dbAlias[0] || 'default'
throw new Error "callback required!" unless callback
@dbCache ||= {}
if db = @dbCache[dbAlias]
callback null, db
else
dbOptions = @databases?[dbAlias] || {}
# throw new Error "no setting for '#{dbAlias}' db alias!" unless dbOptions
server = @server dbOptions.host, dbOptions.port, dbOptions.options
dbName = dbOptions.name || 'default'
# throw new Error "no database name for '#{dbAlias}' db alias!" unless dbName
server.db dbName, (err, db) =>
return callback err if err
if dbOptions.username
db.authenticate dbOptions.username, dbOptions.password, (err, db) =>
return callback err if err
@dbCache[dbAlias] = db
callback null, db
else
@dbCache[dbAlias] = db
callback null, db |
[
{
"context": "c = _czc || [];\n @_czc.push([\"_setAccount\", \"1258121061\"]);\n if this.isWeixin()\n @openType = ",
"end": 202,
"score": 0.9761613011360168,
"start": 192,
"tag": "KEY",
"value": "1258121061"
}
] | demo-cache/scripts/stat.coffee | xiaocat/gulp-front-demo | 1 | 'use strict'
define ['zepto'], ($, _czc)->
class Stat
constructor: ()->
@ua = window.navigator.userAgent.toLowerCase()
@_czc = _czc || [];
@_czc.push(["_setAccount", "1258121061"]);
if this.isWeixin()
@openType = '1'
else if this.isIOS()
@openType = '3'
else
@openType = '2'
isAndroid: ->
/android/i.test(@ua)
isIOS: ->
/(iPhone|iPad|iPod|iOS)/i.test(@ua)
isWeixin: ->
@ua.match(/MicroMessenger/i)=="micromessenger"
# 用户行为统计
actionLog: (eventName)->
if this.isIOS()
window.location.href = 'native:event:' + eventName
else
try window.daka.exec('statis',[eventName])
# 分享统计
shareLog: (shareType, eventType)->
$.ajax
url: '/logs-mobile-api/shareLogs/webApi/add'
type: 'POST'
dataType: 'JSON'
data: $.param {shareType:shareType, eventType:eventType, openType:@openType},
success: (res)->
inApp: ->
in_app = 0
in_app = 1 if /^http:.+userId=.+/.test window.location.href
in_app = 1 if window.daka
in_app = 1 if parseInt(this.getCookie '__in_daka') == 1
this.setCookie '__in_daka',in_app
return in_app
setCookie: (name,value)->
exp = new Date()
exp.setTime(exp.getTime() + 30*24*60*60*1000)
document.cookie = "#{name}=#{escape(value)};expires=#{exp.toGMTString()}"
getCookie: (name)->
reg= new RegExp("(^| )" + name + "=([^;]*)(;|$)")
if arr=document.cookie.match(reg)
return unescape arr[2]
else
return null
pv: (options)->
if this.inApp()
this.actionLog options.eventName
else
this.shareLog options.shareType, 1
action: (options)->
if this.inApp()
this.actionLog options.eventName
else if options.download
this.shareLog options.shareType, 2
@_czc.push ["_trackEvent", options.pageName, options.actionName]
| 7447 | 'use strict'
define ['zepto'], ($, _czc)->
class Stat
constructor: ()->
@ua = window.navigator.userAgent.toLowerCase()
@_czc = _czc || [];
@_czc.push(["_setAccount", "<KEY>"]);
if this.isWeixin()
@openType = '1'
else if this.isIOS()
@openType = '3'
else
@openType = '2'
isAndroid: ->
/android/i.test(@ua)
isIOS: ->
/(iPhone|iPad|iPod|iOS)/i.test(@ua)
isWeixin: ->
@ua.match(/MicroMessenger/i)=="micromessenger"
# 用户行为统计
actionLog: (eventName)->
if this.isIOS()
window.location.href = 'native:event:' + eventName
else
try window.daka.exec('statis',[eventName])
# 分享统计
shareLog: (shareType, eventType)->
$.ajax
url: '/logs-mobile-api/shareLogs/webApi/add'
type: 'POST'
dataType: 'JSON'
data: $.param {shareType:shareType, eventType:eventType, openType:@openType},
success: (res)->
inApp: ->
in_app = 0
in_app = 1 if /^http:.+userId=.+/.test window.location.href
in_app = 1 if window.daka
in_app = 1 if parseInt(this.getCookie '__in_daka') == 1
this.setCookie '__in_daka',in_app
return in_app
setCookie: (name,value)->
exp = new Date()
exp.setTime(exp.getTime() + 30*24*60*60*1000)
document.cookie = "#{name}=#{escape(value)};expires=#{exp.toGMTString()}"
getCookie: (name)->
reg= new RegExp("(^| )" + name + "=([^;]*)(;|$)")
if arr=document.cookie.match(reg)
return unescape arr[2]
else
return null
pv: (options)->
if this.inApp()
this.actionLog options.eventName
else
this.shareLog options.shareType, 1
action: (options)->
if this.inApp()
this.actionLog options.eventName
else if options.download
this.shareLog options.shareType, 2
@_czc.push ["_trackEvent", options.pageName, options.actionName]
| true | 'use strict'
define ['zepto'], ($, _czc)->
class Stat
constructor: ()->
@ua = window.navigator.userAgent.toLowerCase()
@_czc = _czc || [];
@_czc.push(["_setAccount", "PI:KEY:<KEY>END_PI"]);
if this.isWeixin()
@openType = '1'
else if this.isIOS()
@openType = '3'
else
@openType = '2'
isAndroid: ->
/android/i.test(@ua)
isIOS: ->
/(iPhone|iPad|iPod|iOS)/i.test(@ua)
isWeixin: ->
@ua.match(/MicroMessenger/i)=="micromessenger"
# 用户行为统计
actionLog: (eventName)->
if this.isIOS()
window.location.href = 'native:event:' + eventName
else
try window.daka.exec('statis',[eventName])
# 分享统计
shareLog: (shareType, eventType)->
$.ajax
url: '/logs-mobile-api/shareLogs/webApi/add'
type: 'POST'
dataType: 'JSON'
data: $.param {shareType:shareType, eventType:eventType, openType:@openType},
success: (res)->
inApp: ->
in_app = 0
in_app = 1 if /^http:.+userId=.+/.test window.location.href
in_app = 1 if window.daka
in_app = 1 if parseInt(this.getCookie '__in_daka') == 1
this.setCookie '__in_daka',in_app
return in_app
setCookie: (name,value)->
exp = new Date()
exp.setTime(exp.getTime() + 30*24*60*60*1000)
document.cookie = "#{name}=#{escape(value)};expires=#{exp.toGMTString()}"
getCookie: (name)->
reg= new RegExp("(^| )" + name + "=([^;]*)(;|$)")
if arr=document.cookie.match(reg)
return unescape arr[2]
else
return null
pv: (options)->
if this.inApp()
this.actionLog options.eventName
else
this.shareLog options.shareType, 1
action: (options)->
if this.inApp()
this.actionLog options.eventName
else if options.download
this.shareLog options.shareType, 2
@_czc.push ["_trackEvent", options.pageName, options.actionName]
|
[
{
"context": "# Author: 易晓峰\n# E-mail: wvv8oo@gmail.com\n# Date: 6/24/15 ",
"end": 16,
"score": 0.9995814561843872,
"start": 13,
"tag": "NAME",
"value": "易晓峰"
},
{
"context": "# Author: 易晓峰\n# E-mail: wvv8oo@gmail.com\n# Date: 6/24/15 4:48 PM\n# Description:\n_as... | src/cache/index.coffee | kiteam/kiteam | 0 | # Author: 易晓峰
# E-mail: wvv8oo@gmail.com
# Date: 6/24/15 4:48 PM
# Description:
_async = require 'async'
_member = require './member'
_projectMember = require './project_member'
_gitMap = require './git_map'
_project = require './project'
module.exports =
member: _member
gitMap: _gitMap
projectMember: _projectMember
project: _project
init: (cb)->
queue = []
queue.push (done)-> _member.init (err)-> done err
queue.push (done)-> _projectMember.init (err)-> done err
queue.push (done)-> _gitMap.init (err)-> done err
queue.push (done)-> _project.init (err)-> done err
# queue.push(
# (done)->
# console.log _gitMap.get '17229398@qq.com'
# done null
# )
_async.waterfall queue, cb | 124826 | # Author: <NAME>
# E-mail: <EMAIL>
# Date: 6/24/15 4:48 PM
# Description:
_async = require 'async'
_member = require './member'
_projectMember = require './project_member'
_gitMap = require './git_map'
_project = require './project'
module.exports =
member: _member
gitMap: _gitMap
projectMember: _projectMember
project: _project
init: (cb)->
queue = []
queue.push (done)-> _member.init (err)-> done err
queue.push (done)-> _projectMember.init (err)-> done err
queue.push (done)-> _gitMap.init (err)-> done err
queue.push (done)-> _project.init (err)-> done err
# queue.push(
# (done)->
# console.log _gitMap.get '<EMAIL>'
# done null
# )
_async.waterfall queue, cb | true | # Author: PI:NAME:<NAME>END_PI
# E-mail: PI:EMAIL:<EMAIL>END_PI
# Date: 6/24/15 4:48 PM
# Description:
_async = require 'async'
_member = require './member'
_projectMember = require './project_member'
_gitMap = require './git_map'
_project = require './project'
module.exports =
member: _member
gitMap: _gitMap
projectMember: _projectMember
project: _project
init: (cb)->
queue = []
queue.push (done)-> _member.init (err)-> done err
queue.push (done)-> _projectMember.init (err)-> done err
queue.push (done)-> _gitMap.init (err)-> done err
queue.push (done)-> _project.init (err)-> done err
# queue.push(
# (done)->
# console.log _gitMap.get 'PI:EMAIL:<EMAIL>END_PI'
# done null
# )
_async.waterfall queue, cb |
[
{
"context": "************************** Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011-2012 cocos2d-x.org Copyright (",
"end": 6303,
"score": 0.9998722672462463,
"start": 6288,
"tag": "NAME",
"value": "Ricardo Quesada"
},
{
"context": "************************** Copyrigh... | output/cc.coffee | jeremyfa/node-cocos2d-coffee-autocomplete | 1 |
class cc
# Default Action tag
@ACTION_TAG_INVALID = {}
# The adjust factor is needed to prevent issue #442 One solution is to use DONT_RENDER_IN_SUBPIXELS images, but NO The other issue is that in some transitions (and I don't know why) the order should be reversed (In in top of Out or vice-versa).
# [Number]
@ADJUST_FACTOR = 1
# Horizontal center and vertical bottom.
# [Number]
@ALIGN_BOTTOM = 1
# Horizontal left and vertical bottom.
# [Number]
@ALIGN_BOTTOM_LEFT = 1
# Horizontal right and vertical bottom.
# [Number]
@ALIGN_BOTTOM_RIGHT = 1
# Horizontal center and vertical center.
# [Number]
@ALIGN_CENTER = 1
# Horizontal left and vertical center.
# [Number]
@ALIGN_LEFT = 1
# Horizontal right and vertical center.
# [Number]
@ALIGN_RIGHT = 1
# Horizontal center and vertical top.
# [Number]
@ALIGN_TOP = 1
# Horizontal left and vertical top.
# [Number]
@ALIGN_TOP_LEFT = 1
# Horizontal right and vertical top.
# [Number]
@ALIGN_TOP_RIGHT = 1
@ATTRIBUTE_NAME_COLOR = {}
@ATTRIBUTE_NAME_POSITION = {}
@ATTRIBUTE_NAME_TEX_COORD = {}
# default gl blend dst function.
# [Number]
@BLEND_DST = 1
# default gl blend src function.
# [Number]
@BLEND_SRC = 1
# A CCCamera is used in every CCNode.
@Camera = {}
# If enabled, the cc.Node objects (cc.Sprite, cc.Label,etc) will be able to render in subpixels.
@COCOSNODE_RENDER_SUBPIXEL = {}
# Number of kinds of control event.
@CONTROL_EVENT_TOTAL_NUMBER = {}
# Kinds of possible events for the control objects.
@CONTROL_EVENT_TOUCH_DOWN = {}
# The possible state for a control.
@CONTROL_STATE_NORMAL = {}
# returns a new clone of the controlPoints
# [Array]
@copyControlPoints = []
# default tag for current item
# [Number]
@CURRENT_ITEM = 1
# Default engine
@DEFAULT_ENGINE = {}
# [Number]
@DEFAULT_PADDING = 1
# [Number]
@DEFAULT_SPRITE_BATCH_CAPACITY = 1
# Default fps is 60
@defaultFPS = {}
# [Number]
@DEG = 1
# In browsers, we only support 2 orientations by change window size.
# [Number]
@DEVICE_MAX_ORIENTATIONS = 1
# Device oriented horizontally, home button on the right (UIDeviceOrientationLandscapeLeft)
# [Number]
@DEVICE_ORIENTATION_LANDSCAPE_LEFT = 1
# Device oriented horizontally, home button on the left (UIDeviceOrientationLandscapeRight)
# [Number]
@DEVICE_ORIENTATION_LANDSCAPE_RIGHT = 1
# Device oriented vertically, home button on the bottom (UIDeviceOrientationPortrait)
# [Number]
@DEVICE_ORIENTATION_PORTRAIT = 1
# Device oriented vertically, home button on the top (UIDeviceOrientationPortraitUpsideDown)
# [Number]
@DEVICE_ORIENTATION_PORTRAIT_UPSIDE_DOWN = 1
@director = {}
# Seconds between FPS updates.
@DIRECTOR_FPS_INTERVAL = {}
# Position of the FPS (Default: 0,0 (bottom-left corner)) To modify it, in Web engine please refer to CCConfig.js, in JSB please refer to CCConfig.h
@DIRECTOR_STATS_POSITION = {}
# default disabled tag
# [Number]
@DISABLE_TAG = 1
# ************************************************ implementation of DisplayLinkDirector ************************************************
@DisplayLinkDirector = {}
# [Number]
@DST_ALPHA = 1
# [Number]
@DST_COLOR = 1
# Capitalize all characters automatically.
# [Number]
@EDITBOX_INPUT_FLAG_INITIAL_CAPS_ALL_CHARACTERS = 1
# This flag is a hint to the implementation that during text editing, the initial letter of each sentence should be capitalized.
# [Number]
@EDITBOX_INPUT_FLAG_INITIAL_CAPS_SENTENCE = 1
# This flag is a hint to the implementation that during text editing, the initial letter of each word should be capitalized.
# [Number]
@EDITBOX_INPUT_FLAG_INITIAL_CAPS_WORD = 1
# Indicates that the text entered is confidential data that should be obscured whenever possible.
# [Number]
@EDITBOX_INPUT_FLAG_PASSWORD = 1
# Indicates that the text entered is sensitive data that the implementation must never store into a dictionary or table for use in predictive, auto-completing, or other accelerated input schemes.
# [Number]
@EDITBOX_INPUT_FLAG_SENSITIVE = 1
# The EditBoxInputMode defines the type of text that the user is allowed * to enter.
# [Number]
@EDITBOX_INPUT_MODE_ANY = 1
# The user is allowed to enter a real number value.
# [Number]
@EDITBOX_INPUT_MODE_DECIMAL = 1
# The user is allowed to enter an e-mail address.
# [Number]
@EDITBOX_INPUT_MODE_EMAILADDR = 1
# The user is allowed to enter an integer value.
# [Number]
@EDITBOX_INPUT_MODE_NUMERIC = 1
# The user is allowed to enter a phone number.
# [Number]
@EDITBOX_INPUT_MODE_PHONENUMBER = 1
# The user is allowed to enter any text, except for line breaks.
# [Number]
@EDITBOX_INPUT_MODE_SINGLELINE = 1
# The user is allowed to enter a URL.
# [Number]
@EDITBOX_INPUT_MODE_URL = 1
# If enabled, cocos2d will maintain an OpenGL state cache internally to avoid unnecessary switches.
@ENABLE_GL_STATE_CACHE = {}
# If enabled, actions that alter the position property (eg: CCMoveBy, CCJumpBy, CCBezierBy, etc.
@ENABLE_STACKABLE_ACTIONS = {}
# The current version of Cocos2d-JS being used.
@ENGINE_VERSION = {}
# If enabled, the texture coordinates will be calculated by using this formula: - texCoord.left = (rect.x*2+1) / (texture.wide*2); - texCoord.right = texCoord.left + (rect.width*2-2)/(texture.wide*2); The same for bottom and top.
@FIX_ARTIFACTS_BY_STRECHING_TEXEL = {}
# [Number]
@FLT_EPSILON = 1
# [Number]
@FLT_MAX = 1
# [Number]
@FLT_MIN = 1
# Image Format:JPG
@FMT_JPG = {}
# Image Format:PNG
@FMT_PNG = {}
# Image Format:RAWDATA
@FMT_RAWDATA = {}
# Image Format:TIFF
@FMT_TIFF = {}
# Image Format:UNKNOWN
@FMT_UNKNOWN = {}
# Image Format:WEBP
@FMT_WEBP = {}
# ************************************************************************* Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011-2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc.
@g_NumberOfDraws = {}
# GL server side states
@GL_ALL = {}
# A update entry list
@HashUpdateEntry = {}
# enum for jpg
# [Number]
@IMAGE_FORMAT_JPEG = 1
# enum for png
# [Number]
@IMAGE_FORMAT_PNG = 1
# enum for raw
# [Number]
@IMAGE_FORMAT_RAWDATA = 1
# [Number]
@INVALID_INDEX = 1
# Whether or not support retina display
@IS_RETINA_DISPLAY_SUPPORTED = {}
# default size for font size
# [Number]
@ITEM_SIZE = 1
# Key map for keyboard event
@KEY = {}
# [Number]
@KEYBOARD_RETURNTYPE_DEFAULT = 1
# [Number]
@KEYBOARD_RETURNTYPE_DONE = 1
# [Number]
@KEYBOARD_RETURNTYPE_GO = 1
# [Number]
@KEYBOARD_RETURNTYPE_SEARCH = 1
# [Number]
@KEYBOARD_RETURNTYPE_SEND = 1
# [Number]
@LABEL_AUTOMATIC_WIDTH = 1
# If enabled, all subclasses of cc.LabelAtlas will draw a bounding box Useful for debugging purposes only.
@LABELATLAS_DEBUG_DRAW = {}
# If enabled, all subclasses of cc.LabelBMFont will draw a bounding box Useful for debugging purposes only.
@LABELBMFONT_DEBUG_DRAW = {}
# A list double-linked list used for "updates with priority"
@ListEntry = {}
# The min corner of the box
@max = {}
# [Number]
@MENU_HANDLER_PRIORITY = 1
# [Number]
@MENU_STATE_TRACKING_TOUCH = 1
# [Number]
@MENU_STATE_WAITING = 1
# The max corner of the box
@min = {}
# Default Node tag
# [Number]
@NODE_TAG_INVALID = 1
# NodeGrid class is a class serves as a decorator of cc.Node, Grid node can run grid actions over all its children
@NodeGrid = {}
# default tag for normal
# [Number]
@NORMAL_TAG = 1
# [Number]
@ONE = 1
# [Number]
@ONE_MINUS_CONSTANT_ALPHA = 1
# [Number]
@ONE_MINUS_CONSTANT_COLOR = 1
# [Number]
@ONE_MINUS_DST_ALPHA = 1
# [Number]
@ONE_MINUS_DST_COLOR = 1
# [Number]
@ONE_MINUS_SRC_ALPHA = 1
# [Number]
@ONE_MINUS_SRC_COLOR = 1
# If most of your images have pre-multiplied alpha, set it to 1 (if you are going to use .PNG/.JPG file images).
@OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA = {}
# Device oriented horizontally, home button on the right
@ORIENTATION_LANDSCAPE_LEFT = {}
# Device oriented horizontally, home button on the left
@ORIENTATION_LANDSCAPE_RIGHT = {}
# Device oriented vertically, home button on the bottom
@ORIENTATION_PORTRAIT = {}
# Device oriented vertically, home button on the top
@ORIENTATION_PORTRAIT_UPSIDE_DOWN = {}
# paticle default capacity
# [Number]
@PARTICLE_DEFAULT_CAPACITY = 1
# PI is the ratio of a circle's circumference to its diameter.
# [Number]
@PI = 1
@plistParser A Plist Parser A Plist Parser = {}
# smallest such that 1.0+FLT_EPSILON != 1.0
# [Number]
@POINT_EPSILON = 1
# Minimum priority level for user scheduling.
# [Number]
@PRIORITY_NON_SYSTEM = 1
# [Number]
@RAD = 1
# [Number]
@REPEAT_FOREVER = 1
# It's the suffix that will be appended to the files in order to load "retina display" images.
@RETINA_DISPLAY_FILENAME_SUFFIX = {}
# If enabled, cocos2d supports retina display.
@RETINA_DISPLAY_SUPPORT = {}
# XXX: Yes, nodes might have a sort problem once every 15 days if the game runs at 60 FPS and each frame sprites are reordered.
@s_globalOrderOfArrival = {}
# A tag constant for identifying fade scenes
# [Number]
@SCENE_FADE = 1
# tag for scene redial
# [Number]
@SCENE_RADIAL = 1
# default selected tag
# [Number]
@SELECTED_TAG = 1
@SHADER_POSITION_COLOR = {}
@SHADER_POSITION_COLOR_FRAG = {}
@SHADER_POSITION_COLOR_LENGTH_TEXTURE_FRAG = {}
@SHADER_POSITION_COLOR_LENGTH_TEXTURE_VERT = {}
@SHADER_POSITION_COLOR_VERT = {}
@SHADER_POSITION_LENGTHTEXTURECOLOR = {}
@SHADER_POSITION_TEXTURE = {}
@SHADER_POSITION_TEXTURE_A8COLOR_FRAG = {}
@SHADER_POSITION_TEXTURE_A8COLOR_VERT = {}
@SHADER_POSITION_TEXTURE_COLOR_ALPHATEST_FRAG = {}
@SHADER_POSITION_TEXTURE_COLOR_FRAG = {}
@SHADER_POSITION_TEXTURE_COLOR_VERT = {}
@SHADER_POSITION_TEXTURE_FRAG = {}
@SHADER_POSITION_TEXTURE_UCOLOR = {}
@SHADER_POSITION_TEXTURE_UCOLOR_FRAG = {}
@SHADER_POSITION_TEXTURE_UCOLOR_VERT = {}
@SHADER_POSITION_TEXTURE_VERT = {}
@SHADER_POSITION_TEXTUREA8COLOR = {}
@SHADER_POSITION_TEXTURECOLOR = {}
@SHADER_POSITION_TEXTURECOLORALPHATEST = {}
@SHADER_POSITION_UCOLOR = {}
@SHADER_POSITION_UCOLOR_FRAG = {}
@SHADER_POSITION_UCOLOR_VERT = {}
@SHADEREX_SWITCHMASK_FRAG = {}
# If enabled, all subclasses of cc.Sprite will draw a bounding box Useful for debugging purposes only.
@SPRITE_DEBUG_DRAW = {}
# If enabled, all subclasses of cc.Sprite that are rendered using an cc.SpriteBatchNode draw a bounding box.
@SPRITEBATCHNODE_DEBUG_DRAW = {}
# If enabled, the cc.Sprite objects rendered with cc.SpriteBatchNode will be able to render in subpixels.
@SPRITEBATCHNODE_RENDER_SUBPIXEL = {}
# [Number]
@SRC_ALPHA = 1
# [Number]
@SRC_ALPHA_SATURATE = 1
# [Number]
@SRC_COLOR = 1
# the value of stencil bits.
# [Number]
@stencilBits = 1
# The constant value of the fill style from bottom to top for cc.TableView
@TABLEVIEW_FILL_BOTTOMUP = {}
# The constant value of the fill style from top to bottom for cc.TableView
@TABLEVIEW_FILL_TOPDOWN = {}
# Data source that governs table backend data.
@TableViewDataSource = {}
# Sole purpose of this delegate is to single touch event in this version.
@TableViewDelegate = {}
# text alignment : center
# [Number]
@TEXT_ALIGNMENT_CENTER = 1
# text alignment : left
# [Number]
@TEXT_ALIGNMENT_LEFT = 1
# text alignment : right
# [Number]
@TEXT_ALIGNMENT_RIGHT = 1
# Use GL_TRIANGLE_STRIP instead of GL_TRIANGLES when rendering the texture atlas.
@TEXTURE_ATLAS_USE_TRIANGLE_STRIP = {}
# By default, cc.TextureAtlas (used by many cocos2d classes) will use VAO (Vertex Array Objects).
@TEXTURE_ATLAS_USE_VAO = {}
# If enabled, NPOT textures will be used where available.
@TEXTURE_NPOT_SUPPORT = {}
# [Number]
@TGA_ERROR_COMPRESSED_FILE = 1
# [Number]
@TGA_ERROR_FILE_OPEN = 1
# [Number]
@TGA_ERROR_INDEXED_COLOR = 1
# [Number]
@TGA_ERROR_MEMORY = 1
# [Number]
@TGA_ERROR_READING_FILE = 1
# [Number]
@TGA_OK = 1
# A png file reader
@tiffReader = {}
# Hexagonal orientation
# [Number]
@TMX_ORIENTATION_HEX = 1
# Isometric orientation
# [Number]
@TMX_ORIENTATION_ISO = 1
# Orthogonal orientation
# [Number]
@TMX_ORIENTATION_ORTHO = 1
# [Number]
@TMX_PROPERTY_LAYER = 1
# [Number]
@TMX_PROPERTY_MAP = 1
# [Number]
@TMX_PROPERTY_NONE = 1
# [Number]
@TMX_PROPERTY_OBJECT = 1
# [Number]
@TMX_PROPERTY_OBJECTGROUP = 1
# [Number]
@TMX_PROPERTY_TILE = 1
# [Number]
@TMX_TILE_DIAGONAL_FLAG = 1
# [Number]
@TMX_TILE_FLIPPED_ALL = 1
# [Number]
@TMX_TILE_FLIPPED_MASK = 1
# [Number]
@TMX_TILE_HORIZONTAL_FLAG = 1
# [Number]
@TMX_TILE_VERTICAL_FLAG = 1
# vertical orientation type where the Bottom is nearer
# [Number]
@TRANSITION_ORIENTATION_DOWN_OVER = 1
# horizontal orientation Type where the Left is nearer
# [Number]
@TRANSITION_ORIENTATION_LEFT_OVER = 1
# horizontal orientation type where the Right is nearer
# [Number]
@TRANSITION_ORIENTATION_RIGHT_OVER = 1
# vertical orientation type where the Up is nearer
# [Number]
@TRANSITION_ORIENTATION_UP_OVER = 1
@UIInterfaceOrientationLandscapeLeft = {}
@UIInterfaceOrientationLandscapeRight = {}
@UIInterfaceOrientationPortrait = {}
@UIInterfaceOrientationPortraitUpsideDown = {}
# maximum unsigned int value
# [Number]
@UINT_MAX = 1
@UNIFORM_ALPHA_TEST_VALUE_S = {}
@UNIFORM_COSTIME = {}
@UNIFORM_COSTIME_S = {}
@UNIFORM_MAX = {}
@UNIFORM_MVMATRIX = {}
@UNIFORM_MVMATRIX_S = {}
@UNIFORM_MVPMATRIX = {}
@UNIFORM_MVPMATRIX_S = {}
@UNIFORM_PMATRIX = {}
@UNIFORM_PMATRIX_S = {}
@UNIFORM_RANDOM01 = {}
@UNIFORM_RANDOM01_S = {}
@UNIFORM_SAMPLER = {}
@UNIFORM_SAMPLER_S = {}
@UNIFORM_SINTIME = {}
@UNIFORM_SINTIME_S = {}
@UNIFORM_TIME = {}
@UNIFORM_TIME_S = {}
# If enabled, it will use LA88 (Luminance Alpha 16-bit textures) for CCLabelTTF objects.
@USE_LA88_LABELS = {}
@VERTEX_ATTRIB_COLOR = {}
@VERTEX_ATTRIB_FLAG_COLOR = {}
@VERTEX_ATTRIB_FLAG_NONE = {}
@VERTEX_ATTRIB_FLAG_POS_COLOR_TEX = {}
@VERTEX_ATTRIB_FLAG_POSITION = {}
@VERTEX_ATTRIB_FLAG_TEX_COORDS = {}
@VERTEX_ATTRIB_MAX = {}
@VERTEX_ATTRIB_POSITION = {}
@VERTEX_ATTRIB_TEX_COORDS = {}
# text alignment : bottom
# [Number]
@VERTICAL_TEXT_ALIGNMENT_BOTTOM = 1
# text alignment : center
# [Number]
@VERTICAL_TEXT_ALIGNMENT_CENTER = 1
# text alignment : top
# [Number]
@VERTICAL_TEXT_ALIGNMENT_TOP = 1
# [Number]
@ZERO = 1
# default tag for zoom action tag
# [Number]
@ZOOM_ACTION_TAG = 1
# the dollar sign, classic like jquery, this selector add extra methods to HTMLElement without touching its prototype it is also chainable like jquery
# @param [HTMLElement|String] x
# @return [$]
@$: (x) ->
# Creates a new element, and adds cc.$ methods
# @param [String] x
# @return [$]
@$new: (x) ->
# Allocates and initializes the action.
# @return [Action]
@action: ->
# creates the action of ActionEase
# @param [ActionInterval] action
# @return [ActionEase]
@actionEase: (action) ->
# An interval action is an action that takes place within a certain period of time.
# @param [Number] d
# @return [ActionInterval]
@actionInterval: (d) ->
# Creates an initializes the action with the property name (key), and the from and to parameters.
# @param [Number] duration
# @param [String] key
# @param [Number] from
# @param [Number] to
# @return [ActionTween]
@actionTween: (duration, key, from, to) ->
# Concatenate a transform matrix to another and return the result: t' = t1 * t2
# @param [AffineTransform] t1
# @param [AffineTransform] t2
# @return [AffineTransform]
@affineTransformConcat: (t1, t2) ->
# Return true if an affine transform equals to another, false otherwise.
# @param [AffineTransform] t1
# @param [AffineTransform] t2
# @return [Boolean]
@affineTransformEqualToTransform: (t1, t2) ->
# Create a identity transformation matrix: [ 1, 0, 0, 0, 1, 0 ]
# @return [AffineTransform]
@affineTransformIdentity: ->
# Get the invert transform of an AffineTransform object
# @param [AffineTransform] t
# @return [AffineTransform]
@affineTransformInvert: (t) ->
# Create a cc.AffineTransform object with all contents in the matrix
# @param [Number] a
# @param [Number] b
# @param [Number] c
# @param [Number] d
# @param [Number] tx
# @param [Number] ty
# @return [AffineTransform]
@affineTransformMake: (a, b, c, d, tx, ty) ->
# Create a identity transformation matrix: [ 1, 0, 0, 0, 1, 0 ]
# @return [AffineTransform]
@affineTransformMakeIdentity: ->
# Create a new affine transformation with a base transformation matrix and a rotation based on it.
# @param [AffineTransform] aTransform
# @param [Number] anAngle
# @return [AffineTransform]
@affineTransformRotate: (aTransform, anAngle) ->
# Create a new affine transformation with a base transformation matrix and a scale based on it.
# @param [AffineTransform] t
# @param [Number] sx
# @param [Number] sy
# @return [AffineTransform]
@affineTransformScale: (t, sx, sy) ->
# Create a new affine transformation with a base transformation matrix and a translation based on it.
# @param [AffineTransform] t
# @param [Number] tx
# @param [Number] ty
# @return [AffineTransform]
@affineTransformTranslate: (t, tx, ty) ->
# create the animate with animation
# @param [Animation] animation
# @return [Animate]
@animate: (animation) ->
# Inserts some objects at index
# @param [Array] arr
# @param [Array] addObjs
# @param [Number] index
# @return [Array]
@arrayAppendObjectsToIndex: (arr, addObjs, index) ->
# Removes from arr all values in minusArr.
# @param [Array] arr
# @param [Array] minusArr
@arrayRemoveArray: (arr, minusArr) ->
# Searches for the first occurance of object and removes it.
# @param [Array] arr
# @param [*] delObj
@arrayRemoveObject: (arr, delObj) ->
# Verify Array's Type
# @param [Array] arr
# @param [function] type
# @return [Boolean]
@arrayVerifyType: (arr, type) ->
# Function added for JS bindings compatibility.
# @param [object] jsObj
# @param [object] superclass
@associateWithNative: (jsObj, superclass) ->
# @param me
# @param opt_methodName
# @param var_args
@base: (me, opt_methodName, var_args) ->
# @param [Number] a
# @param [Number] b
# @param [Number] c
# @param [Number] d
# @param [Number] t
# @return [Number]
@bezierAt: (a, b, c, d, t) ->
# An action that moves the target with a cubic Bezier curve by a certain distance.
# @param [Number] t
# @param [Array] c
# @return [BezierBy]
@bezierBy: (t, c) ->
# An action that moves the target with a cubic Bezier curve to a destination point.
# @param [Number] t
# @param [Array] c
# @return [BezierTo]
@bezierTo: (t, c) ->
# Blend Function used for textures
# @param [Number] src1
# @param [Number] dst1
@BlendFunc: (src1, dst1) ->
# @return [BlendFunc]
@blendFuncDisable: ->
# Blinks a cc.Node object by modifying it's visible attribute.
# @param [Number] duration
# @param blinks
# @return [Blink]
@blink: (duration, blinks) ->
# Creates the action with the callback
# @param [function] selector
# @param [object|null] selectorTarget
# @param [*|null] data
# @return [CallFunc]
@callFunc: (selector, selectorTarget, data) ->
# Returns the Cardinal Spline position for a given set of control points, tension and time.
# @param [Point] p0
# @param [Point] p1
# @param [Point] p2
# @param [Point] p3
# @param [Number] tension
# @param [Number] t
# @return [Point]
@cardinalSplineAt: (p0, p1, p2, p3, tension, t) ->
# creates an action with a Cardinal Spline array of points and tension.
# @param [Number] duration
# @param [Array] points
# @param [Number] tension
# @return [CardinalSplineBy]
@cardinalSplineBy: (duration, points, tension) ->
# creates an action with a Cardinal Spline array of points and tension.
# @param [Number] duration
# @param [Array] points
# @param [Number] tension
# @return [CardinalSplineTo]
@cardinalSplineTo: (duration, points, tension) ->
# Creates an action with a Cardinal Spline array of points and tension
# @param [Number] dt
# @param [Array] points
# @return [CatmullRomBy]
@catmullRomBy: (dt, points) ->
# creates an action with a Cardinal Spline array of points and tension.
# @param [Number] dt
# @param [Array] points
# @return [CatmullRomTo]
@catmullRomTo: (dt, points) ->
# convert an affine transform object to a kmMat4 object
# @param [AffineTransform] trans
# @param [kmMat4] mat
@CGAffineToGL: (trans, mat) ->
# Check webgl error.Error will be shown in console if exists.
@checkGLErrorDebug: ->
# Clamp a value between from and to.
# @param [Number] value
# @param [Number] min_inclusive
# @param [Number] max_inclusive
# @return [Number]
@clampf: (value, min_inclusive, max_inclusive) ->
# Create a new object and copy all properties in an exist object to the new object
# @param [object|Array] obj
# @return [Array|object]
@clone: (obj) ->
# returns a new clone of the controlPoints
# @param controlPoints
# @return [Array]
@cloneControlPoints: (controlPoints) ->
# Generate a color object based on multiple forms of parameters
# @param [Number|String|cc.Color] r
# @param [Number] g
# @param [Number] b
# @param [Number] a
# @return [Color]
@color: (r, g, b, a) ->
# returns true if both ccColor3B are equal.
# @param [Color] color1
# @param [Color] color2
# @return [Boolean]
@colorEqual: (color1, color2) ->
# convert Color to a string of color for style.
# @param [Color] color
# @return [String]
@colorToHex: (color) ->
# On Mac it returns 1; On iPhone it returns 2 if RetinaDisplay is On.
# @return [Number]
@contentScaleFactor: ->
# Copy an array's item to a new array (its performance is better than Array.slice)
# @param [Array] arr
# @return [Array]
@copyArray: (arr) ->
# create a webgl context
# @param [HTMLCanvasElement] canvas
# @param [Object] opt_attribs
# @return [WebGLRenderingContext]
@create3DContext: (canvas, opt_attribs) ->
# Common getter setter configuration function
# @param [Object] proto
# @param [String] prop
# @param [function] getter
# @param [function] setter
# @param [String] getterName
# @param [String] setterName
@defineGetterSetter: (proto, prop, getter, setter, getterName, setterName) ->
# converts degrees to radians
# @param [Number] angle
# @return [Number]
@degreesToRadians: (angle) ->
# Delays the action a certain amount of seconds
# @param [Number] d
# @return [DelayTime]
@delayTime: (d) ->
# Disable default GL states: - GL_TEXTURE_2D - GL_TEXTURE_COORD_ARRAY - GL_COLOR_ARRAY
@disableDefaultGLStates: ->
# Iterate over an object or an array, executing a function for each matched element.
# @param [object|array] obj
# @param [function] iterator
# @param [object] context
@each: (obj, iterator, context) ->
# Creates the action easing object.
# @return [Object]
@easeBackIn: ->
# Creates the action easing object.
# @return [Object]
@easeBackInOut: ->
# Creates the action easing object.
# @return [Object]
@easeBackOut: ->
# Creates the action easing object.
# @param [Number] p0
# @param [Number] p1
# @param [Number] p2
# @param [Number] p3
# @return [Object]
@easeBezierAction: (p0, p1, p2, p3) ->
# Creates the action easing object.
# @return [Object]
@easeBounceIn: ->
# Creates the action easing object.
# @return [Object]
@easeBounceInOut: ->
# Creates the action easing object.
# @return [Object]
@easeBounceOut: ->
# Creates the action easing object.
# @return [Object]
@easeCircleActionIn: ->
# Creates the action easing object.
# @return [Object]
@easeCircleActionInOut: ->
# Creates the action easing object.
# @return [Object]
@easeCircleActionOut: ->
# Creates the action easing object.
# @return [Object]
@easeCubicActionIn: ->
# Creates the action easing object.
# @return [Object]
@easeCubicActionInOut: ->
# Creates the action easing object.
# @return [Object]
@easeCubicActionOut: ->
# Creates the action easing obejct with the period in radians (default is 0.3).
# @param [Number] period
# @return [Object]
@easeElasticIn: (period) ->
# Creates the action easing object with the period in radians (default is 0.3).
# @param [Number] period
# @return [Object]
@easeElasticInOut: (period) ->
# Creates the action easing object with the period in radians (default is 0.3).
# @param [Number] period
# @return [Object]
@easeElasticOut: (period) ->
# Creates the action easing object with the rate parameter.
# @return [Object]
@easeExponentialIn: ->
# creates an EaseExponentialInOut action easing object.
# @return [Object]
@easeExponentialInOut: ->
# creates the action easing object.
# @return [Object]
@easeExponentialOut: ->
# Creates the action easing object with the rate parameter.
# @param [Number] rate
# @return [Object]
@easeIn: (rate) ->
# Creates the action easing object with the rate parameter.
# @param [Number] rate
# @return [Object]
@easeInOut: (rate) ->
# Creates the action easing object with the rate parameter.
# @param [Number] rate
# @return [Object]
@easeOut: (rate) ->
# Creates the action easing object.
# @return [Object]
@easeQuadraticActionIn: ->
# Creates the action easing object.
# @return [Object]
@easeQuadraticActionInOut: ->
# Creates the action easing object.
# @return [Object]
@easeQuadraticActionOut: ->
# Creates the action easing object.
# @return [Object]
@easeQuarticActionIn: ->
# Creates the action easing object.
# @return [Object]
@easeQuarticActionInOut: ->
# Creates the action easing object.
# @return [Object]
@easeQuarticActionOut: ->
# Creates the action easing object.
# @return [Object]
@easeQuinticActionIn: ->
# Creates the action easing object.
# @return [Object]
@easeQuinticActionInOut: ->
# Creates the action easing object.
# @return [Object]
@easeQuinticActionOut: ->
# Creates the action with the inner action and the rate parameter.
# @param [ActionInterval] action
# @param [Number] rate
# @return [EaseRateAction]
@easeRateAction: (action, rate) ->
# creates an EaseSineIn action.
# @return [Object]
@easeSineIn: ->
# creates the action easing object.
# @return [Object]
@easeSineInOut: ->
# Creates an EaseSineOut action easing object.
# @return [Object]
@easeSineOut: ->
# GL states that are enabled: - GL_TEXTURE_2D - GL_VERTEX_ARRAY - GL_TEXTURE_COORD_ARRAY - GL_COLOR_ARRAY
@enableDefaultGLStates: ->
# Copy all of the properties in source objects to target object and return the target object.
# @param [object] target
# @param [object] *sources
# @return [object]
@extend: (target, *sources) ->
# Fades In an object that implements the cc.RGBAProtocol protocol.
# @param [Number] duration
# @return [FadeIn]
@fadeIn: (duration) ->
# Fades Out an object that implements the cc.RGBAProtocol protocol.
# @param [Number] d
# @return [FadeOut]
@fadeOut: (d) ->
# Creates the action with the grid size and the duration.
# @param duration
# @param gridSize
# @return [FadeOutBLTiles]
@fadeOutBLTiles: (duration, gridSize) ->
# Creates the action with the grid size and the duration.
# @param [Number] duration
# @param [Size] gridSize
# @return [FadeOutDownTiles]
@fadeOutDownTiles: (duration, gridSize) ->
# Creates the action with the grid size and the duration.
# @param duration
# @param gridSize
# @return [FadeOutTRTiles]
@fadeOutTRTiles: (duration, gridSize) ->
# Creates the action with the grid size and the duration.
# @param [Number] duration
# @param [Size] gridSize
# @return [FadeOutUpTiles]
@fadeOutUpTiles: (duration, gridSize) ->
# Fades an object that implements the cc.RGBAProtocol protocol.
# @param [Number] duration
# @param [Number] opacity
# @return [FadeTo]
@fadeTo: (duration, opacity) ->
# Create a FlipX action to flip or unflip the target.
# @param [Boolean] flip
# @return [FlipX]
@flipX: (flip) ->
# Create a Flip X 3D action with duration.
# @param [Number] duration
# @return [FlipX3D]
@flipX3D: (duration) ->
# Create a FlipY action to flip or unflip the target.
# @param [Boolean] flip
# @return [FlipY]
@flipY: (flip) ->
# Create a flip Y 3d action with duration.
# @param [Number] duration
# @return [FlipY3D]
@flipY3D: (duration) ->
# creates the action with a set boundary.
# @param [Node] followedNode
# @param [Rect] rect
# @return [Follow|Null]
@follow: (followedNode, rect) ->
# A string tool to construct a string with format string.
# @return [String]
@formatStr: ->
# Generates texture's cache for texture tint
# @param [HTMLImageElement] texture
# @return [Array]
@generateTextureCacheForColor: (texture) ->
# Generate tinted texture with lighter.
# @param [HTMLImageElement] texture
# @param [Array] tintedImgCache
# @param [Color] color
# @param [Rect] rect
# @param [HTMLCanvasElement] renderCanvas
# @return [HTMLCanvasElement]
@generateTintImage: (texture, tintedImgCache, color, rect, renderCanvas) ->
# Tint a texture using the "multiply" operation
# @param [HTMLImageElement] image
# @param [Color] color
# @param [Rect] rect
# @param [HTMLCanvasElement] renderCanvas
# @return [HTMLCanvasElement]
@generateTintImageWithMultiply: (image, color, rect, renderCanvas) ->
# returns a point from the array
# @param [Array] controlPoints
# @param [Number] pos
# @return [Array]
@getControlPointAt: (controlPoints, pos) ->
# get image format by image data
# @param [Array] imgData
# @return [Number]
@getImageFormatByData: (imgData) ->
# If the texture is not already bound, it binds it.
# @param [Texture2D] textureId
@glBindTexture2D: (textureId) ->
# If the texture is not already bound to a given unit, it binds it.
# @param [Number] textureUnit
# @param [Texture2D] textureId
@glBindTexture2DN: (textureUnit, textureId) ->
# If the vertex array is not already bound, it binds it.
# @param [Number] vaoId
@glBindVAO: (vaoId) ->
# Uses a blending function in case it not already used.
# @param [Number] sfactor
# @param [Number] dfactor
@glBlendFunc: (sfactor, dfactor) ->
# @param [Number] sfactor
# @param [Number] dfactor
@glBlendFuncForParticle: (sfactor, dfactor) ->
# Resets the blending mode back to the cached state in case you used glBlendFuncSeparate() or glBlendEquation().
@glBlendResetToCache: ->
# Deletes the GL program.
# @param [WebGLProgram] program
@glDeleteProgram: (program) ->
# It will delete a given texture.
# @param [WebGLTexture] textureId
@glDeleteTexture: (textureId) ->
# It will delete a given texture.
# @param [Number] textureUnit
# @param [WebGLTexture] textureId
@glDeleteTextureN: (textureUnit, textureId) ->
# It will enable / disable the server side GL states.
# @param [Number] flags
@glEnable: (flags) ->
# Will enable the vertex attribs that are passed as flags.
# @param [VERTEX_ATTRIB_FLAG_POSITION | cc.VERTEX_ATTRIB_FLAG_COLOR | cc.VERTEX_ATTRIB_FLAG_TEX_OORDS] flags
@glEnableVertexAttribs: (flags) ->
# Invalidates the GL state cache.
@glInvalidateStateCache: ->
# Convert a kmMat4 object to an affine transform object
# @param [kmMat4] mat
# @param [AffineTransform] trans
@GLToCGAffine: (mat, trans) ->
# Uses the GL program in case program is different than the current one.
# @param [WebGLProgram] program
@glUseProgram: (program) ->
# creates the action with size and duration
# @param [Number] duration
# @param [Size] gridSize
# @return [Grid3DAction]
@grid3DAction: (duration, gridSize) ->
# creates the action with size and duration
# @param [Number] duration
# @param [Size] gridSize
# @return [GridAction]
@gridAction: (duration, gridSize) ->
# Hash Element used for "selectors with interval"
# @param [Array] timers
# @param [Class] target
# @param [Number] timerIndex
# @param [Timer] currentTimer
# @param [Boolean] currentTimerSalvaged
# @param [Boolean] paused
# @param [Array] hh
@HashTimerEntry: (timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused, hh) ->
# ************************************************************************* Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011-2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc.
# @param value
# @param location
# @param hh
@HashUniformEntry: (value, location, hh) ->
# convert a string of color for style to Color.
# @param [String] hex
# @return [Color]
@hexToColor: (hex) ->
# Hide the node.
# @return [Hide]
@hide: ->
# IME Keyboard Notification Info structure
# @param [Rect] begin
# @param [Rect] end
# @param [Number] duration
@IMEKeyboardNotificationInfo: (begin, end, duration) ->
# Increments the GL Draws counts by one.
# @param [Number] addNumber
@incrementGLDraws: (addNumber) ->
# Another way to subclass: Using Google Closure.
# @param [Function] childCtor
# @param [Function] parentCtor
@inherits: (childCtor, parentCtor) ->
# Check the obj whether is array or not
# @param [*] obj
# @return [boolean]
@isArray: (obj) ->
# Check the url whether cross origin
# @param [String] url
# @return [boolean]
@isCrossOrigin: (url) ->
# Check the obj whether is function or not
# @param [*] obj
# @return [boolean]
@isFunction: (obj) ->
# Check the obj whether is number or not
# @param [*] obj
# @return [boolean]
@isNumber: (obj) ->
# Check the obj whether is object or not
# @param [*] obj
# @return [boolean]
@isObject: (obj) ->
# Check the obj whether is string or not
# @param [*] obj
# @return [boolean]
@isString: (obj) ->
# Check the obj whether is undefined or not
# @param [*] obj
# @return [boolean]
@isUndefined: (obj) ->
# Moves a cc.Node object simulating a parabolic jump movement by modifying it's position attribute.
# @param [Number] duration
# @param [Point|Number] position
# @param [Number] y
# @param [Number] height
# @param [Number] jumps
# @return [JumpBy]
@jumpBy: (duration, position, y, height, jumps) ->
# creates the action with the number of jumps, the sin amplitude, the grid size and the duration.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] numberOfJumps
# @param [Number] amplitude
# @return [JumpTiles3D]
@jumpTiles3D: (duration, gridSize, numberOfJumps, amplitude) ->
# Moves a cc.Node object to a parabolic position simulating a jump movement by modifying it's position attribute.
# @param [Number] duration
# @param [Point|Number] position
# @param [Number] y
# @param [Number] height
# @param [Number] jumps
# @return [JumpTo]
@jumpTo: (duration, position, y, height, jumps) ->
# A struture that represents an axis-aligned bounding box.
# @param min
# @param max
@kmAABB: (min, max) ->
# Assigns pIn to pOut, returns pOut.
# @param pOut
# @param pIn
@kmAABBAssign: (pOut, pIn) ->
# Returns KM_TRUE if point is in the specified AABB, returns KM_FALSE otherwise.
# @param pPoint
# @param pBox
@kmAABBContainsPoint: (pPoint, pBox) ->
# Scales pIn by s, stores the resulting AABB in pOut.
# @param pOut
# @param pIn
# @param s
@kmAABBScale: (pOut, pIn, s) ->
# A 4x4 matrix mat = | 0 4 8 12 | | 1 5 9 13 | | 2 6 10 14 | | 3 7 11 15 |
@kmMat4: ->
# Returns KM_TRUE if the 2 matrices are equal (approximately)
# @param pMat1
# @param pMat2
@kmMat4AreEqual: (pMat1, pMat2) ->
# Assigns the value of pIn to pOut
# @param pOut
# @param pIn
@kmMat4Assign: (pOut, pIn) ->
# Extract a 3x3 rotation matrix from the input 4x4 transformation.
# @param pOut
# @param pIn
@kmMat4ExtractRotation: (pOut, pIn) ->
# Fills a kmMat4 structure with the values from a 16 element array of floats
# @param pOut
# @param pMat
@kmMat4Fill: (pOut, pMat) ->
# Extract the forward vector from a 4x4 matrix.
# @param pOut
# @param pIn
@kmMat4GetForwardVec3: (pOut, pIn) ->
# Extract the right vector from a 4x4 matrix.
# @param pOut
# @param pIn
@kmMat4GetRightVec3: (pOut, pIn) ->
# Get the up vector from a matrix.
# @param pOut
# @param pIn
@kmMat4GetUpVec3: (pOut, pIn) ->
# Sets pOut to an identity matrix returns pOut
# @param pOut
@kmMat4Identity: (pOut) ->
# Calculates the inverse of pM and stores the result in pOut.
# @param pOut
# @param pM
@kmMat4Inverse: (pOut, pM) ->
# Returns KM_TRUE if pIn is an identity matrix KM_FALSE otherwise
# @param pIn
@kmMat4IsIdentity: (pIn) ->
# Builds a translation matrix in the same way as gluLookAt() the resulting matrix is stored in pOut.
# @param pOut
# @param pEye
# @param pCenter
# @param pUp
@kmMat4LookAt: (pOut, pEye, pCenter, pUp) ->
# Multiplies pM1 with pM2, stores the result in pOut, returns pOut
# @param pOut
# @param pM1
# @param pM2
@kmMat4Multiply: (pOut, pM1, pM2) ->
# Creates an orthographic projection matrix like glOrtho
# @param pOut
# @param left
# @param right
# @param bottom
# @param top
# @param nearVal
# @param farVal
@kmMat4OrthographicProjection: (pOut, left, right, bottom, top, nearVal, farVal) ->
# Creates a perspective projection matrix in the same way as gluPerspective
# @param pOut
# @param fovY
# @param aspect
# @param zNear
# @param zFar
@kmMat4PerspectiveProjection: (pOut, fovY, aspect, zNear, zFar) ->
# Build a rotation matrix from an axis and an angle.
# @param pOut
# @param axis
# @param radians
@kmMat4RotationAxisAngle: (pOut, axis, radians) ->
# Builds a rotation matrix from pitch, yaw and roll.
# @param pOut
# @param pitch
# @param yaw
# @param roll
@kmMat4RotationPitchYawRoll: (pOut, pitch, yaw, roll) ->
# Converts a quaternion to a rotation matrix, the result is stored in pOut, returns pOut
# @param pOut
# @param pQ
@kmMat4RotationQuaternion: (pOut, pQ) ->
# Take the rotation from a 4x4 transformation matrix, and return it as an axis and an angle (in radians) returns the output axis.
# @param pAxis
# @param radians
# @param pIn
@kmMat4RotationToAxisAngle: (pAxis, radians, pIn) ->
# Build a 4x4 OpenGL transformation matrix using a 3x3 rotation matrix, and a 3d vector representing a translation.
# @param pOut
# @param rotation
# @param translation
@kmMat4RotationTranslation: (pOut, rotation, translation) ->
# Builds an X-axis rotation matrix and stores it in pOut, returns pOut
# @param pOut
# @param radians
@kmMat4RotationX: (pOut, radians) ->
# Builds a rotation matrix using the rotation around the Y-axis The result is stored in pOut, pOut is returned.
# @param pOut
# @param radians
@kmMat4RotationY: (pOut, radians) ->
# Builds a rotation matrix around the Z-axis.
# @param pOut
# @param radians
@kmMat4RotationZ: (pOut, radians) ->
# Builds a scaling matrix
# @param pOut
# @param x
# @param y
# @param z
@kmMat4Scaling: (pOut, x, y, z) ->
# Builds a translation matrix.
# @param pOut
# @param x
# @param y
# @param z
@kmMat4Translation: (pOut, x, y, z) ->
# Sets pOut to the transpose of pIn, returns pOut
# @param pOut
# @param pIn
@kmMat4Transpose: (pOut, pIn) ->
# Returns POINT_INFRONT_OF_PLANE if pP is infront of pIn.
# @param pIn
# @param pP
@kmPlaneClassifyPoint: (pIn, pP) ->
# Creates a plane from 3 points.
# @param pOut
# @param p1
# @param p2
# @param p3
@kmPlaneFromPoints: (pOut, p1, p2, p3) ->
# Adapted from the OGRE engine! Gets the shortest arc quaternion to rotate this vector to the destination vector.
# @param pOut
# @param vec1
# @param vec2
# @param fallback
@kmQuaternionRotationBetweenVec3: (pOut, vec1, vec2, fallback) ->
# Returns the square of s (e.g.
# @param [Number] s
@kmSQR: (s) ->
# creates a lens 3d action with center position, radius
# @param [Number] duration
# @param [Size] gridSize
# @param [Point] position
# @param [Number] radius
# @return [Lens3D]
@lens3D: (duration, gridSize, position, radius) ->
# Linear interpolation between 2 numbers, the ratio sets how much it is biased to each end
# @param [Number] a
# @param [Number] b
# @param [Number] r
@lerp: (a, b, r) ->
# creates the action with amplitude, a grid and duration
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] waves
# @param [Number] amplitude
# @return [Liquid]
@liquid: (duration, gridSize, waves, amplitude) ->
# Create the action.
# @param [Number] duration
# @param [Point|Number] deltaPos
# @param [Number] deltaY
# @return [MoveBy]
@moveBy: (duration, deltaPos, deltaY) ->
# Create new action.
# @param [Number] duration
# @param [Point] position
# @param [Number] y
# @return [MoveBy]
@moveTo: (duration, position, y) ->
# @param [Number] x
# @return [Number]
@NextPOT: (x) ->
# Helpful macro that setups the GL server state, the correct GL program and sets the Model View Projection matrix
# @param [Node] node
@nodeDrawSetup: (node) ->
# Helper function that creates a cc.Point.
# @param [Number|cc.Point] x
# @param [Number] y
# @return [Point]
@p: (x, y) ->
# Calculates sum of two points.
# @param [Point] v1
# @param [Point] v2
# @return [Point]
@pAdd: (v1, v2) ->
# adds one point to another (inplace)
# @param [Point] v1
# @param [point] v2
@pAddIn: (v1, v2) ->
# create PageTurn3D action
# @param [Number] duration
# @param [Size] gridSize
# @return [PageTurn3D]
@pageTurn3D: (duration, gridSize) ->
# @param [Point] a
# @param [Point] b
# @return [Number]
@pAngle: (a, b) ->
# @param [Point] a
# @param [Point] b
# @return [Number]
@pAngleSigned: (a, b) ->
# Clamp a point between from and to.
# @param [Point] p
# @param [Number] min_inclusive
# @param [Number] max_inclusive
# @return [Point]
@pClamp: (p, min_inclusive, max_inclusive) ->
# Multiplies a nd b components, a.x*b.x, a.y*b.y
# @param [Point] a
# @param [Point] b
# @return [Point]
@pCompMult: (a, b) ->
# Run a math operation function on each point component Math.abs, Math.fllor, Math.ceil, Math.round.
# @param [Point] p
# @param [Function] opFunc
# @return [Point]
@pCompOp: (p, opFunc) ->
# Calculates cross product of two points.
# @param [Point] v1
# @param [Point] v2
# @return [Number]
@pCross: (v1, v2) ->
# Calculates the distance between two points
# @param [Point] v1
# @param [Point] v2
# @return [Number]
@pDistance: (v1, v2) ->
# Calculates the square distance between two points (not calling sqrt() )
# @param [Point] point1
# @param [Point] point2
# @return [Number]
@pDistanceSQ: (point1, point2) ->
# Calculates dot product of two points.
# @param [Point] v1
# @param [Point] v2
# @return [Number]
@pDot: (v1, v2) ->
# Converts radians to a normalized vector.
# @param [Number] a
# @return [Point]
@pForAngle: (a) ->
# Quickly convert cc.Size to a cc.Point
# @param [Size] s
# @return [Point]
@pFromSize: (s) ->
# @param [Point] a
# @param [Point] b
# @param [Number] variance
# @return [Boolean]
@pFuzzyEqual: (a, b, variance) ->
# copies the position of one point to another
# @param [Point] v1
# @param [Point] v2
@pIn: (v1, v2) ->
# ccpIntersectPoint return the intersection point of line A-B, C-D
# @param [Point] A
# @param [Point] B
# @param [Point] C
# @param [Point] D
# @return [Point]
@pIntersectPoint: (A, B, C, D) ->
# Creates a Place action with a position.
# @param [Point|Number] pos
# @param [Number] y
# @return [Place]
@place: (pos, y) ->
# Calculates distance between point an origin
# @param [Point] v
# @return [Number]
@pLength: (v) ->
# Calculates the square length of a cc.Point (not calling sqrt() )
# @param [Point] v
# @return [Number]
@pLengthSQ: (v) ->
# Linear Interpolation between two points a and b alpha == 0 ? a alpha == 1 ? b otherwise a value between a.
# @param [Point] a
# @param [Point] b
# @param [Number] alpha
# @return [pAdd]
@pLerp: (a, b, alpha) ->
# A general line-line intersection test indicating successful intersection of a line note that to truly test intersection for segments we have to make sure that s & t lie within [0.
# @param [Point] A
# @param [Point] B
# @param [Point] C
# @param [Point] D
# @param [Point] retP
# @return [Boolean]
@pLineIntersect: (A, B, C, D, retP) ->
# Calculates midpoint between two points.
# @param [Point] v1
# @param [Point] v2
# @return [pMult]
@pMidpoint: (v1, v2) ->
# Returns point multiplied by given factor.
# @param [Point] point
# @param [Number] floatVar
# @return [Point]
@pMult: (point, floatVar) ->
# multiplies the point with the given factor (inplace)
# @param [Point] point
# @param [Number] floatVar
@pMultIn: (point, floatVar) ->
# Returns opposite of point.
# @param [Point] point
# @return [Point]
@pNeg: (point) ->
# Returns point multiplied to a length of 1.
# @param [Point] v
# @return [Point]
@pNormalize: (v) ->
# normalizes the point (inplace)
# @param
@pNormalizeIn: ->
# Apply the affine transformation on a point.
# @param [Point] point
# @param [AffineTransform] t
# @return [Point]
@pointApplyAffineTransform: (point, t) ->
# Check whether a point's value equals to another
# @param [Point] point1
# @param [Point] point2
# @return [Boolean]
@pointEqualToPoint: (point1, point2) ->
# Converts a Point in pixels to points
# @param [Rect] pixels
# @return [Point]
@pointPixelsToPoints: (pixels) ->
# Converts a Point in points to pixels
# @param [Point] points
# @return [Point]
@pointPointsToPixels: (points) ->
# Calculates perpendicular of v, rotated 90 degrees counter-clockwise -- cross(v, perp(v)) = 0
# @param [Point] point
# @return [Point]
@pPerp: (point) ->
# Calculates the projection of v1 over v2.
# @param [Point] v1
# @param [Point] v2
# @return [pMult]
@pProject: (v1, v2) ->
# Creates and initializes the action with a duration, a "from" percentage and a "to" percentage
# @param [Number] duration
# @param [Number] fromPercentage
# @param [Number] toPercentage
# @return [ProgressFromTo]
@progressFromTo: (duration, fromPercentage, toPercentage) ->
# Creates and initializes with a duration and a percent
# @param [Number] duration
# @param [Number] percent
# @return [ProgressTo]
@progressTo: (duration, percent) ->
# Rotates two points.
# @param [Point] v1
# @param [Point] v2
# @return [Point]
@pRotate: (v1, v2) ->
# Rotates a point counter clockwise by the angle around a pivot
# @param [Point] v
# @param [Point] pivot
# @param [Number] angle
# @return [Point]
@pRotateByAngle: (v, pivot, angle) ->
# Calculates perpendicular of v, rotated 90 degrees clockwise -- cross(v, rperp(v))
# @param [Point] point
# @return [Point]
@pRPerp: (point) ->
# check to see if both points are equal
# @param [Point] A
# @param [Point] B
# @return [Boolean]
@pSameAs: (A, B) ->
# ccpSegmentIntersect return YES if Segment A-B intersects with segment C-D.
# @param [Point] A
# @param [Point] B
# @param [Point] C
# @param [Point] D
# @return [Boolean]
@pSegmentIntersect: (A, B, C, D) ->
# Calculates difference of two points.
# @param [Point] v1
# @param [Point] v2
# @return [Point]
@pSub: (v1, v2) ->
# subtracts one point from another (inplace)
# @param [Point] v1
# @param
@pSubIn: (v1, ) ->
# Converts a vector to radians.
# @param [Point] v
# @return [Number]
@pToAngle: (v) ->
# Unrotates two points.
# @param [Point] v1
# @param [Point] v2
# @return [Point]
@pUnrotate: (v1, v2) ->
# sets the position of the point to 0
# @param [Point] v
@pZeroIn: (v) ->
# converts radians to degrees
# @param [Number] angle
# @return [Number]
@radiansToDegrees: (angle) ->
# converts radians to degrees
# @param [Number] angle
# @return [Number]
@radiansToDegress: (angle) ->
# get a random number from 0 to 0xffffff
# @return [number]
@rand: ->
# returns a random float between 0 and 1
# @return [Number]
@random0To1: ->
# returns a random float between -1 and 1
# @return [Number]
@randomMinus1To1: ->
# Helper function that creates a cc.Rect.
# @param [Number|cc.Rect] x
# @param [Number] y
# @param [Number] w
# @param [Number] h
# @return [Rect]
@rect: (x, y, w, h) ->
# Apply the affine transformation on a rect.
# @param [Rect] rect
# @param [AffineTransform] anAffineTransform
# @return [Rect]
@rectApplyAffineTransform: (rect, anAffineTransform) ->
# Check whether a rect contains a point
# @param [Rect] rect
# @param [Point] point
# @return [Boolean]
@rectContainsPoint: (rect, point) ->
# Check whether the rect1 contains rect2
# @param [Rect] rect1
# @param [Rect] rect2
# @return [Boolean]
@rectContainsRect: (rect1, rect2) ->
# Check whether a rect's value equals to another
# @param [Rect] rect1
# @param [Rect] rect2
# @return [Boolean]
@rectEqualToRect: (rect1, rect2) ->
# Returns the rightmost x-value of a rect
# @param [Rect] rect
# @return [Number]
@rectGetMaxX: (rect) ->
# Return the topmost y-value of a rect
# @param [Rect] rect
# @return [Number]
@rectGetMaxY: (rect) ->
# Return the midpoint x-value of a rect
# @param [Rect] rect
# @return [Number]
@rectGetMidX: (rect) ->
# Return the midpoint y-value of `rect'
# @param [Rect] rect
# @return [Number]
@rectGetMidY: (rect) ->
# Returns the leftmost x-value of a rect
# @param [Rect] rect
# @return [Number]
@rectGetMinX: (rect) ->
# Return the bottommost y-value of a rect
# @param [Rect] rect
# @return [Number]
@rectGetMinY: (rect) ->
# Returns the overlapping portion of 2 rectangles
# @param [Rect] rectA
# @param [Rect] rectB
# @return [Rect]
@rectIntersection: (rectA, rectB) ->
# Check whether a rect intersect with another
# @param [Rect] rectA
# @param [Rect] rectB
# @return [Boolean]
@rectIntersectsRect: (rectA, rectB) ->
# Check whether a rect overlaps another
# @param [Rect] rectA
# @param [Rect] rectB
# @return [Boolean]
@rectOverlapsRect: (rectA, rectB) ->
# Converts a rect in pixels to points
# @param [Rect] pixel
# @return [Rect]
@rectPixelsToPoints: (pixel) ->
# Converts a rect in points to pixels
# @param [Rect] point
# @return [Rect]
@rectPointsToPixels: (point) ->
# Returns the smallest rectangle that contains the two source rectangles.
# @param [Rect] rectA
# @param [Rect] rectB
# @return [Rect]
@rectUnion: (rectA, rectB) ->
# Create a RemoveSelf object with a flag indicate whether the target should be cleaned up while removing.
# @param [Boolean] isNeedCleanUp
# @return [RemoveSelf]
@removeSelf: (isNeedCleanUp) ->
# Creates a Repeat action.
# @param [FiniteTimeAction] action
# @param [Number] times
# @return [Repeat]
@repeat: (action, times) ->
# Create a acton which repeat forever
# @param [FiniteTimeAction] action
# @return [RepeatForever]
@repeatForever: (action) ->
# creates an action with the number of times that the current grid will be reused
# @param [Number] times
# @return [ReuseGrid]
@reuseGrid: (times) ->
# returns a new copy of the array reversed.
# @param controlPoints
# @return [Array]
@reverseControlPoints: (controlPoints) ->
# reverse the current control point array inline, without generating a new one
# @param controlPoints
@reverseControlPointsInline: (controlPoints) ->
# Executes an action in reverse order, from time=duration to time=0.
# @param [FiniteTimeAction] action
# @return [ReverseTime]
@reverseTime: (action) ->
# creates a ripple 3d action with radius, number of waves, amplitude
# @param [Number] duration
# @param [Size] gridSize
# @param [Point] position
# @param [Number] radius
# @param [Number] waves
# @param [Number] amplitude
# @return [Ripple3D]
@ripple3D: (duration, gridSize, position, radius, waves, amplitude) ->
# Rotates a cc.Node object clockwise a number of degrees by modifying it's rotation attribute.
# @param [Number] duration
# @param [Number] deltaAngleX
# @param [Number] deltaAngleY
# @return [RotateBy]
@rotateBy: (duration, deltaAngleX, deltaAngleY) ->
# Creates a RotateTo action with separate rotation angles.
# @param [Number] duration
# @param [Number] deltaAngleX
# @param [Number] deltaAngleY
# @return [RotateTo]
@rotateTo: (duration, deltaAngleX, deltaAngleY) ->
# Scales a cc.Node object a zoom factor by modifying it's scale attribute.
# @param [Number] duration
# @param [Number] sx
# @param [Number|Null] sy
# @return [ScaleBy]
@scaleBy: (duration, sx, sy) ->
# Scales a cc.Node object to a zoom factor by modifying it's scale attribute.
# @param [Number] duration
# @param [Number] sx
# @param [Number] sy
# @return [ScaleTo]
@scaleTo: (duration, sx, sy) ->
# helper constructor to create an array of sequenceable actions
# @param [Array|cc.FiniteTimeAction] tempArray
# @return [Sequence]
@sequence: (tempArray) ->
# @param [Number] sfactor
# @param [Number] dfactor
@setBlending: (sfactor, dfactor) ->
# Sets the shader program for this node Since v2.0, each rendering node must set its shader program.
# @param [Node] node
# @param [GLProgram] program
@setProgram: (node, program) ->
# sets the projection matrix as dirty
@setProjectionMatrixDirty: ->
# creates the action with a range, shake Z vertices, a grid and duration
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] range
# @param [Boolean] shakeZ
# @return [Shaky3D]
@shaky3D: (duration, gridSize, range, shakeZ) ->
# Creates the action with a range, whether or not to shake Z vertices, a grid size, and duration.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] range
# @param [Boolean] shakeZ
# @return [ShakyTiles3D]
@shakyTiles3D: (duration, gridSize, range, shakeZ) ->
# Creates the action with a range, whether of not to shatter Z vertices, a grid size and duration.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] range
# @param [Boolean] shatterZ
# @return [ShatteredTiles3D]
@shatteredTiles3D: (duration, gridSize, range, shatterZ) ->
# Show the Node.
# @return [Show]
@show: ->
# Creates the action with a random seed, the grid size and the duration.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] seed
# @return [ShuffleTiles]
@shuffleTiles: (duration, gridSize, seed) ->
# Helper function that creates a cc.Size.
# @param [Number|cc.Size] w
# @param [Number] h
# @return [Size]
@size: (w, h) ->
# Apply the affine transformation on a size.
# @param [Size] size
# @param [AffineTransform] t
# @return [Size]
@sizeApplyAffineTransform: (size, t) ->
# Check whether a point's value equals to another
# @param [Size] size1
# @param [Size] size2
# @return [Boolean]
@sizeEqualToSize: (size1, size2) ->
# Converts a size in pixels to points
# @param [Size] sizeInPixels
# @return [Size]
@sizePixelsToPoints: (sizeInPixels) ->
# Converts a Size in points to pixels
# @param [Size] sizeInPoints
# @return [Size]
@sizePointsToPixels: (sizeInPoints) ->
# Skews a cc.Node object by skewX and skewY degrees.
# @param [Number] t
# @param [Number] sx
# @param [Number] sy
# @return [SkewBy]
@skewBy: (t, sx, sy) ->
# Create new action.
# @param [Number] t
# @param [Number] sx
# @param [Number] sy
# @return [SkewTo]
@skewTo: (t, sx, sy) ->
# Create a spawn action which runs several actions in parallel.
# @param [Array|cc.FiniteTimeAction] tempArray
# @return [FiniteTimeAction]
@spawn: (tempArray) ->
# creates the speed action.
# @param [ActionInterval] action
# @param [Number] speed
# @return [Speed]
@speed: (action, speed) ->
# creates the action with the number of columns to split and the duration.
# @param [Number] duration
# @param [Number] cols
# @return [SplitCols]
@splitCols: (duration, cols) ->
# creates the action with the number of rows to split and the duration.
# @param [Number] duration
# @param [Number] rows
# @return [SplitRows]
@splitRows: (duration, rows) ->
# Allocates and initializes the action
# @return [StopGrid]
@stopGrid: ->
# simple macro that swaps 2 variables modified from c++ macro, you need to pass in the x and y variables names in string, and then a reference to the whole object as third variable
# @param [String] x
# @param [String] y
# @param [Object] ref
@swap: (x, y, ref) ->
# Create an action with the specified action and forced target
# @param [Node] target
# @param [FiniteTimeAction] action
# @return [TargetedAction]
@targetedAction: (target, action) ->
# Helper macro that creates an Tex2F type: A texcoord composed of 2 floats: u, y
# @param [Number] u
# @param [Number] v
# @return [Tex2F]
@tex2: (u, v) ->
# releases the memory used for the image
# @param [ImageTGA] psInfo
@tgaDestroy: (psInfo) ->
# ImageTGA Flip
# @param [ImageTGA] psInfo
@tgaFlipImage: (psInfo) ->
# load the image header field from stream.
# @param [Array] buffer
# @param [Number] bufSize
# @param [ImageTGA] psInfo
# @return [Boolean]
@tgaLoadHeader: (buffer, bufSize, psInfo) ->
# loads the image pixels.
# @param [Array] buffer
# @param [Number] bufSize
# @param [ImageTGA] psInfo
# @return [Boolean]
@tgaLoadImageData: (buffer, bufSize, psInfo) ->
# Load RLE image data
# @param buffer
# @param bufSize
# @param psInfo
# @return [boolean]
@tgaLoadRLEImageData: (buffer, bufSize, psInfo) ->
# converts RGB to grayscale
# @param [ImageTGA] psInfo
@tgaRGBtogreyscale: (psInfo) ->
# Creates the action with duration and grid size
# @param [Number] duration
# @param [Size] gridSize
# @return [TiledGrid3DAction]
@tiledGrid3DAction: (duration, gridSize) ->
# Tints a cc.Node that implements the cc.NodeRGB protocol from current tint to a custom one.
# @param [Number] duration
# @param [Number] deltaRed
# @param [Number] deltaGreen
# @param [Number] deltaBlue
# @return [TintBy]
@tintBy: (duration, deltaRed, deltaGreen, deltaBlue) ->
# Tints a cc.Node that implements the cc.NodeRGB protocol from current tint to a custom one.
# @param [Number] duration
# @param [Number] red
# @param [Number] green
# @param [Number] blue
# @return [TintTo]
@tintTo: (duration, red, green, blue) ->
# Toggles the visibility of a node.
# @return [ToggleVisibility]
@toggleVisibility: ->
# Creates the action with a random seed, the grid size and the duration.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number|Null] seed
# @return [TurnOffTiles]
@turnOffTiles: (duration, gridSize, seed) ->
# creates the action with center position, number of twirls, amplitude, a grid size and duration
# @param [Number] duration
# @param [Size] gridSize
# @param [Point] position
# @param [Number] twirls
# @param [Number] amplitude
# @return [Twirl]
@twirl: (duration, gridSize, position, twirls, amplitude) ->
# Code copied & pasted from SpacePatrol game https://github.com/slembcke/SpacePatrol Renamed and added some changes for cocos2d
@v2fzero: ->
# Helper macro that creates an Vertex2F type composed of 2 floats: x, y
# @param [Number] x
# @param [Number] y
# @return [Vertex2F]
@vertex2: (x, y) ->
# Helper macro that creates an Vertex3F type composed of 3 floats: x, y, z
# @param [Number] x
# @param [Number] y
# @param [Number] z
# @return [Vertex3F]
@vertex3: (x, y, z) ->
# returns whether or not the line intersects
# @param [Number] Ax
# @param [Number] Ay
# @param [Number] Bx
# @param [Number] By
# @param [Number] Cx
# @param [Number] Cy
# @param [Number] Dx
# @param [Number] Dy
# @return [Object]
@vertexLineIntersect: (Ax, Ay, Bx, By, Cx, Cy, Dx, Dy) ->
# converts a line to a polygon
# @param [Float32Array] points
# @param [Number] stroke
# @param [Float32Array] vertices
# @param [Number] offset
# @param [Number] nuPoints
@vertexLineToPolygon: (points, stroke, vertices, offset, nuPoints) ->
# returns wheter or not polygon defined by vertex list is clockwise
# @param [Array] verts
# @return [Boolean]
@vertexListIsClockwise: (verts) ->
# initializes the action with amplitude, horizontal sin, vertical sin, a grid and duration
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] waves
# @param [Number] amplitude
# @param [Boolean] horizontal
# @param [Boolean] vertical
# @return [Waves]
@waves: (duration, gridSize, waves, amplitude, horizontal, vertical) ->
# Create a wave 3d action with duration, grid size, waves and amplitude.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] waves
# @param [Number] amplitude
@waves3D: (duration, gridSize, waves, amplitude) ->
# creates the action with a number of waves, the waves amplitude, the grid size and the duration.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] waves
# @param [Number] amplitude
# @return [WavesTiles3D]
@wavesTiles3D: (duration, gridSize, waves, amplitude) ->
# cc.Acceleration
# @param [Number] x
# @param [Number] y
# @param [Number] z
# @param [Number] timestamp
# @return [Acceleration]
@Acceleration: (x, y, z, timestamp) ->
# Base class for cc.Action objects.
# @return [Action]
@Action: ->
# Base class for Easing actions
# @param [ActionInterval] action
# @return [ActionEase]
@ActionEase: (action) ->
# Instant actions are immediate actions.
# @return [ActionInstant]
@ActionInstant: ->
# An interval action is an action that takes place within a certain period of time.
# @param [Number] d
# @return [ActionInterval]
@ActionInterval: (d) ->
# cc.ActionManager is a class that can manage actions.
# @return [ActionManager]
@ActionManager: ->
# cc.ActionTween cc.ActionTween is an action that lets you update any property of an object.
# @param [Number] duration
# @param [String] key
# @param [Number] from
# @param [Number] to
# @return [ActionTween]
@ActionTween: (duration, key, from, to) ->
# @return [ActionTweenDelegate]
@ActionTweenDelegate: ->
# cc.AffineTransform
# @param [Number] a
# @param [Number] b
# @param [Number] c
# @param [Number] d
# @param [Number] tx
# @param [Number] ty
# @return [AffineTransform]
@AffineTransform: (a, b, c, d, tx, ty) ->
# Animates a sprite given the name of an Animation
# @param [Animation] animation
# @return [Animate]
@Animate: (animation) ->
# A cc.Animation object is used to perform animations on the cc.Sprite objects.
# @param [Array] frames
# @param [Number] delay
# @param [Number] loops
# @return [Animation]
@Animation: (frames, delay, loops) ->
# cc.animationCache is a singleton object that manages the Animations.
# @return [animationCache]
@animationCache: ->
# cc.AnimationFrame A frame of the animation.
# @param spriteFrame
# @param delayUnits
# @param userInfo
# @return [AnimationFrame]
@AnimationFrame: (spriteFrame, delayUnits, userInfo) ->
# Array for object sorting utils
# @return [ArrayForObjectSorting]
@ArrayForObjectSorting: ->
# @return [async]
@async: ->
# Async Pool class, a helper of cc.async
# @param [Object|Array] srcObj
# @param [Number] limit
# @param [function] iterator
# @param [function] onEnd
# @param [object] target
# @return [AsyncPool]
@AsyncPool: (srcObj, limit, iterator, onEnd, target) ->
# cc.AtlasNode is a subclass of cc.Node, it knows how to render a TextureAtlas object.
# @param [String] tile
# @param [Number] tileWidth
# @param [Number] tileHeight
# @param [Number] itemsToRender
# @return [AtlasNode]
@AtlasNode: (tile, tileWidth, tileHeight, itemsToRender) ->
# cc.audioEngine is the singleton object, it provide simple audio APIs.
# @return [audioEngine]
@audioEngine: ->
# An action that moves the target with a cubic Bezier curve by a certain distance.
# @param [Number] t
# @param [Array] c
# @return [BezierBy]
@BezierBy: (t, c) ->
# An action that moves the target with a cubic Bezier curve to a destination point.
# @param [Number] t
# @param [Array] c
# @return [BezierTo]
@BezierTo: (t, c) ->
# Binary Stream Reader
# @param binaryData
# @return [BinaryStreamReader]
@BinaryStreamReader: (binaryData) ->
# Blinks a cc.Node object by modifying it's visible attribute
# @param [Number] duration
# @param [Number] blinks
# @return [Blink]
@Blink: (duration, blinks) ->
# Calls a 'callback'.
# @param [function] selector
# @param [object|null] selectorTarget
# @param [*|null] data
# @return [CallFunc]
@CallFunc: (selector, selectorTarget, data) ->
# Cardinal Spline path.
# @param [Number] duration
# @param [Array] points
# @param [Number] tension
# @return [CardinalSplineBy]
@CardinalSplineBy: (duration, points, tension) ->
# Cardinal Spline path.
# @param [Number] duration
# @param [Array] points
# @param [Number] tension
# @return [CardinalSplineTo]
@CardinalSplineTo: (duration, points, tension) ->
# An action that moves the target with a CatmullRom curve by a certain distance.
# @param [Number] dt
# @param [Array] points
# @return [CatmullRomBy]
@CatmullRomBy: (dt, points) ->
# An action that moves the target with a CatmullRom curve to a destination point.
# @param [Number] dt
# @param [Array] points
# @return [CatmullRomTo]
@CatmullRomTo: (dt, points) ->
# The base Class implementation (does nothing)
# @return [Class]
@Class: ->
# cc.ClippingNode is a subclass of cc.Node.
# @param [Node] stencil
# @return [ClippingNode]
@ClippingNode: (stencil) ->
# cc.Color
# @param [Number] r
# @param [Number] g
# @param [Number] b
# @param [Number] a
# @return [Color]
@Color: (r, g, b, a) ->
# The base class of component in CocoStudio
# @return [Component]
@Component: ->
# The component container for Cocostudio, it has some components.
# @return [ComponentContainer]
@ComponentContainer: ->
# cc.configuration is a singleton object which contains some openGL variables
# @return [configuration]
@configuration: ->
# cc.ContainerStrategy class is the root strategy class of container's scale strategy, it controls the behavior of how to scale the cc.container and cc._canvas object
# @return [ContainerStrategy]
@ContainerStrategy: ->
# cc.ContentStrategy class is the root strategy class of content's scale strategy, it controls the behavior of how to scale the scene and setup the viewport for the game
# @return [ContentStrategy]
@ContentStrategy: ->
# CCControl is inspired by the UIControl API class from the UIKit library of CocoaTouch.
# @return [Control]
@Control: ->
# CCControlButton: Button control for Cocos2D.
# @return [ControlButton]
@ControlButton: ->
# ControlColourPicker: color picker ui component.
# @return [ControlColourPicker]
@ControlColourPicker: ->
# ControlHuePicker: HUE picker ui component.
# @return [ControlHuePicker]
@ControlHuePicker: ->
# CCControlPotentiometer: Potentiometer control for Cocos2D.
# @return [ControlPotentiometer]
@ControlPotentiometer: ->
# ControlSaturationBrightnessPicker: Saturation brightness picker ui component.
# @return [ControlSaturationBrightnessPicker]
@ControlSaturationBrightnessPicker: ->
# ControlSlider: Slider ui component.
# @return [ControlSlider]
@ControlSlider: ->
# ControlStepper: Stepper ui component.
# @return [ControlStepper]
@ControlStepper: ->
# CCControlSwitch: Switch control ui component
# @return [ControlSwitch]
@ControlSwitch: ->
# ControlSwitchSprite: Sprite switch control ui component
# @return [ControlSwitchSprite]
@ControlSwitchSprite: ->
# Delays the action a certain amount of seconds
# @return [DelayTime]
@DelayTime: ->
# ATTENTION: USE cc.director INSTEAD OF cc.Director.
# @return [Director]
@Director: ->
# CCDrawNode Node that draws dots, segments and polygons.
# @return [DrawNode]
@DrawNode: ->
# cc.EaseBackIn action.
# @return [EaseBackIn]
@EaseBackIn: ->
# cc.EaseBackInOut action.
# @return [EaseBackInOut]
@EaseBackInOut: ->
# cc.EaseBackOut action.
# @return [EaseBackOut]
@EaseBackOut: ->
# cc.EaseBezierAction action.
# @param [Action] action
# @return [EaseBezierAction]
@EaseBezierAction: (action) ->
# cc.EaseBounce abstract class.
# @return [EaseBounce]
@EaseBounce: ->
# cc.EaseBounceIn action.
# @return [EaseBounceIn]
@EaseBounceIn: ->
# cc.EaseBounceInOut action.
# @return [EaseBounceInOut]
@EaseBounceInOut: ->
# cc.EaseBounceOut action.
# @return [EaseBounceOut]
@EaseBounceOut: ->
# cc.EaseCircleActionIn action.
# @return [EaseCircleActionIn]
@EaseCircleActionIn: ->
# cc.EaseCircleActionInOut action.
# @return [EaseCircleActionInOut]
@EaseCircleActionInOut: ->
# cc.EaseCircleActionOut action.
# @return [EaseCircleActionOut]
@EaseCircleActionOut: ->
# cc.EaseCubicActionIn action.
# @return [EaseCubicActionIn]
@EaseCubicActionIn: ->
# cc.EaseCubicActionInOut action.
# @return [EaseCubicActionInOut]
@EaseCubicActionInOut: ->
# cc.EaseCubicActionOut action.
# @return [EaseCubicActionOut]
@EaseCubicActionOut: ->
# Ease Elastic abstract class.
# @param [ActionInterval] action
# @param [Number] period
# @return [EaseElastic]
@EaseElastic: (action, period) ->
# Ease Elastic In action.
# @return [EaseElasticIn]
@EaseElasticIn: ->
# Ease Elastic InOut action.
# @return [EaseElasticInOut]
@EaseElasticInOut: ->
# Ease Elastic Out action.
# @return [EaseElasticOut]
@EaseElasticOut: ->
# cc.Ease Exponential In.
# @return [EaseExponentialIn]
@EaseExponentialIn: ->
# Ease Exponential InOut.
# @return [EaseExponentialInOut]
@EaseExponentialInOut: ->
# Ease Exponential Out.
# @return [EaseExponentialOut]
@EaseExponentialOut: ->
# cc.EaseIn action with a rate.
# @return [EaseIn]
@EaseIn: ->
# cc.EaseInOut action with a rate.
# @return [EaseInOut]
@EaseInOut: ->
# cc.EaseOut action with a rate.
# @return [EaseOut]
@EaseOut: ->
# cc.EaseQuadraticActionIn action.
# @return [EaseQuadraticActionIn]
@EaseQuadraticActionIn: ->
# cc.EaseQuadraticActionInOut action.
# @return [EaseQuadraticActionInOut]
@EaseQuadraticActionInOut: ->
# cc.EaseQuadraticActionIn action.
# @return [EaseQuadraticActionOut]
@EaseQuadraticActionOut: ->
# cc.EaseQuarticActionIn action.
# @return [EaseQuarticActionIn]
@EaseQuarticActionIn: ->
# cc.EaseQuarticActionInOut action.
# @return [EaseQuarticActionInOut]
@EaseQuarticActionInOut: ->
# cc.EaseQuarticActionOut action.
# @return [EaseQuarticActionOut]
@EaseQuarticActionOut: ->
# cc.EaseQuinticActionIn action.
# @return [EaseQuinticActionIn]
@EaseQuinticActionIn: ->
# cc.EaseQuinticActionInOut action.
# @return [EaseQuinticActionInOut]
@EaseQuinticActionInOut: ->
# cc.EaseQuinticActionOut action.
# @return [EaseQuinticActionOut]
@EaseQuinticActionOut: ->
# Base class for Easing actions with rate parameters
# @param [ActionInterval] action
# @param [Number] rate
# @return [EaseRateAction]
@EaseRateAction: (action, rate) ->
# Ease Sine In.
# @return [EaseSineIn]
@EaseSineIn: ->
# Ease Sine InOut.
# @return [EaseSineInOut]
@EaseSineInOut: ->
# Ease Sine Out.
# @return [EaseSineOut]
@EaseSineOut: ->
# cc.EditBox is a brief Class for edit box.
# @return [EditBox]
@EditBox: ->
# @return [EditBoxDelegate]
@EditBoxDelegate: ->
# Base class of all kinds of events.
# @return [Event]
@Event: ->
# The Custom event
# @return [EventCustom]
@EventCustom: ->
# The widget focus event.
# @return [EventFocus]
@EventFocus: ->
# The base class of event listener.
# @return [EventListener]
@EventListener: ->
# cc.eventManager is a singleton object which manages event listener subscriptions and event dispatching.
# @return [eventManager]
@eventManager: ->
# The mouse event
# @return [EventMouse]
@EventMouse: ->
# The touch event
# @return [EventTouch]
@EventTouch: ->
# Fades In an object that implements the cc.RGBAProtocol protocol.
# @param [Number] duration
# @return [FadeIn]
@FadeIn: (duration) ->
# Fades Out an object that implements the cc.RGBAProtocol protocol.
# @param [Number] duration
# @return [FadeOut]
@FadeOut: (duration) ->
# cc.FadeOutBLTiles action.
# @return [FadeOutBLTiles]
@FadeOutBLTiles: ->
# cc.FadeOutDownTiles action.
# @return [FadeOutDownTiles]
@FadeOutDownTiles: ->
# cc.FadeOutTRTiles action.
# @return [FadeOutTRTiles]
@FadeOutTRTiles: ->
# cc.FadeOutUpTiles action.
# @return [FadeOutUpTiles]
@FadeOutUpTiles: ->
# Fades an object that implements the cc.RGBAProtocol protocol.
# @param [Number] duration
# @param [Number] opacity
# @return [FadeTo]
@FadeTo: (duration, opacity) ->
# Base class actions that do have a finite time duration.
# @return [FiniteTimeAction]
@FiniteTimeAction: ->
# Flips the sprite horizontally.
# @param [Boolean] flip
# @return [FlipX]
@FlipX: (flip) ->
# cc.FlipX3D action.
# @param [Number] duration
# @return [FlipX3D]
@FlipX3D: (duration) ->
# Flips the sprite vertically
# @param [Boolean] flip
# @return [FlipY]
@FlipY: (flip) ->
# cc.FlipY3D action.
# @param [Number] duration
# @return [FlipY3D]
@FlipY3D: (duration) ->
# cc.Follow is an action that "follows" a node.
# @param [Node] followedNode
# @param [Rect] rect
# @return [Follow]
@Follow: (followedNode, rect) ->
# cc.FontDefinition
# @return [FontDefinition]
@FontDefinition: ->
# An object to boot the game.
# @return [game]
@game: ->
# Class that implements a WebGL program
# @return [GLProgram]
@GLProgram: ->
# FBO class that grabs the the contents of the screen
# @return [Grabber]
@Grabber: ->
# cc.Grid3D is a 3D grid implementation.
# @return [Grid3D]
@Grid3D: ->
# Base class for cc.Grid3D actions.
# @return [Grid3DAction]
@Grid3DAction: ->
# Base class for Grid actions
# @param [Number] duration
# @param [Size] gridSize
# @return [GridAction]
@GridAction: (duration, gridSize) ->
# Base class for cc.Grid
# @return [GridBase]
@GridBase: ->
# @return [HashElement]
@HashElement: ->
# Hide the node.
# @return [Hide]
@Hide: ->
# TGA format
# @param [Number] status
# @param [Number] type
# @param [Number] pixelDepth
# @param [Number] width
# @param [Number] height
# @param [Array] imageData
# @param [Number] flipped
# @return [ImageTGA]
@ImageTGA: (status, type, pixelDepth, width, height, imageData, flipped) ->
# Input method editor delegate.
# @return [IMEDelegate]
@IMEDelegate: ->
# cc.imeDispatcher is a singleton object which manage input message dispatching.
# @return [imeDispatcher]
@imeDispatcher: ->
# This class manages all events of input.
# @return [inputManager]
@inputManager: ->
# An Invocation class
# @return [Invocation]
@Invocation: ->
# Moves a cc.Node object simulating a parabolic jump movement by modifying it's position attribute.
# @param [Number] duration
# @param [Point|Number] position
# @param [Number] y
# @param [Number] height
# @param [Number] jumps
# @return [JumpBy]
@JumpBy: (duration, position, y, height, jumps) ->
# cc.JumpTiles3D action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] numberOfJumps
# @param [Number] amplitude
# @return [JumpTiles3D]
@JumpTiles3D: (duration, gridSize, numberOfJumps, amplitude) ->
# Moves a cc.Node object to a parabolic position simulating a jump movement by modifying it's position attribute.
# @param [Number] duration
# @param [Point|Number] position
# @param [Number] y
# @param [Number] height
# @param [Number] jumps
# @return [JumpTo]
@JumpTo: (duration, position, y, height, jumps) ->
# The Quaternion class
# @param [Number] x
# @param [Number] y
# @param [Number] z
# @param [Number] w
# @return [kmQuaternion]
@kmQuaternion: (x, y, z, w) ->
# using image file to print text label on the screen, might be a bit slower than cc.Label, similar to cc.LabelBMFont
# @param [String] strText
# @param [String] charMapFile
# @param [Number] itemWidth
# @param [Number] itemHeight
# @param [Number] startCharMap
# @return [LabelAtlas]
@LabelAtlas: (strText, charMapFile, itemWidth, itemHeight, startCharMap) ->
# cc.LabelBMFont is a subclass of cc.SpriteBatchNode.
# @param [String] str
# @param [String] fntFile
# @param [Number] width
# @param [Number] alignment
# @param [Point] imageOffset
# @return [LabelBMFont]
@LabelBMFont: (str, fntFile, width, alignment, imageOffset) ->
# cc.LabelTTF is a subclass of cc.TextureNode that knows how to render text labels with system font or a ttf font file All features from cc.Sprite are valid in cc.LabelTTF cc.LabelTTF objects are slow for js-binding on mobile devices.
# @param [String] text
# @param [String|cc.FontDefinition] fontName
# @param [Number] fontSize
# @param [Size] dimensions
# @param [Number] hAlignment
# @param [Number] vAlignment
# @return [LabelTTF]
@LabelTTF: (text, fontName, fontSize, dimensions, hAlignment, vAlignment) ->
# cc.Layer is a subclass of cc.Node that implements the TouchEventsDelegate protocol.
# @return [Layer]
@Layer: ->
# CCLayerColor is a subclass of CCLayer that implements the CCRGBAProtocol protocol.
# @param [Color] color
# @param [Number] width
# @param [Number] height
# @return [LayerColor]
@LayerColor: (color, width, height) ->
# CCLayerGradient is a subclass of cc.LayerColor that draws gradients across the background.
# @param [Color] start
# @param [Color] end
# @param [Point] v
# @return [LayerGradient]
@LayerGradient: (start, end, v) ->
# CCMultipleLayer is a CCLayer with the ability to multiplex it's children.
# @param [Array] layers
# @return [LayerMultiplex]
@LayerMultiplex: (layers) ->
# cc.Lens3D action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Point] position
# @param [Number] radius
# @return [Lens3D]
@Lens3D: (duration, gridSize, position, radius) ->
# cc.Liquid action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] waves
# @param [Number] amplitude
# @return [Liquid]
@Liquid: (duration, gridSize, waves, amplitude) ->
# Loader for resource loading process.
# @return [loader]
@loader: ->
# Features and Limitation: - You can add MenuItem objects in runtime using addChild: - But the only accepted children are MenuItem objects
# @param [...cc.MenuItem|null] menuItems}
# @return [Menu]
@Menu: (menuItems}) ->
# Subclass cc.MenuItem (or any subclass) to create your custom cc.MenuItem objects.
# @param [function|String] callback
# @param [Node] target
# @return [MenuItem]
@MenuItem: (callback, target) ->
# Helper class that creates a MenuItemLabel class with a LabelAtlas
# @param [String] value
# @param [String] charMapFile
# @param [Number] itemWidth
# @param [Number] itemHeight
# @param [String] startCharMap
# @param [function|String|Null] callback
# @param [Node|Null] target
# @return [MenuItemAtlasFont]
@MenuItemAtlasFont: (value, charMapFile, itemWidth, itemHeight, startCharMap, callback, target) ->
# Helper class that creates a CCMenuItemLabel class with a Label
# @param [String] value
# @param [function|String] callback
# @param [Node] target
# @return [MenuItemFont]
@MenuItemFont: (value, callback, target) ->
# cc.MenuItemImage accepts images as items.
# @param [string|null] normalImage
# @param [string|null] selectedImage
# @param [string|null] disabledImage
# @param [function|string|null] callback
# @param [Node|null] target
# @return [MenuItemImage]
@MenuItemImage: (normalImage, selectedImage, disabledImage, callback, target) ->
# Any cc.Node that supports the cc.LabelProtocol protocol can be added.
# @param [Node] label
# @param [function|String] selector
# @param [Node] target
# @return [MenuItemLabel]
@MenuItemLabel: (label, selector, target) ->
# CCMenuItemSprite accepts CCNode objects as items.
# @param [Image|Null] normalSprite
# @param [Image|Null] selectedSprite
# @param [Image|cc.Node|Null] three
# @param [String|function|cc.Node|Null] four
# @param [String|function|Null] five
# @return [MenuItemSprite]
@MenuItemSprite: (normalSprite, selectedSprite, three, four, five) ->
# A simple container class that "toggles" it's inner items The inner items can be any MenuItem
# @return [MenuItemToggle]
@MenuItemToggle: ->
# MenuPassive: The menu passive ui component
# @return [MenuPassive]
@MenuPassive: ->
# cc.MotionStreak manages a Ribbon based on it's motion in absolute space.
# @return [MotionStreak]
@MotionStreak: ->
# Moves a CCNode object x,y pixels by modifying it's position attribute.
# @param [Number] duration
# @param [Point|Number] deltaPos
# @param [Number] deltaY
# @return [MoveBy]
@MoveBy: (duration, deltaPos, deltaY) ->
# Moves a CCNode object to the position x,y.
# @param [Number] duration
# @param [Point|Number] position
# @param [Number] y
# @return [MoveTo]
@MoveTo: (duration, position, y) ->
# cc.Node is the root class of all node.
# @return [Node]
@Node: ->
# This action simulates a page turn from the bottom right hand corner of the screen.
# @return [PageTurn3D]
@PageTurn3D: ->
# cc.ParallaxNode: A node that simulates a parallax scroller The children will be moved faster / slower than the parent according the the parallax ratio.
# @return [ParallaxNode]
@ParallaxNode: ->
# Structure that contains the values of each particle
# @param [Point] pos
# @param [Point] startPos
# @param [Color] color
# @param [Color] deltaColor
# @param [Size] size
# @param [Size] deltaSize
# @param [Number] rotation
# @param [Number] deltaRotation
# @param [Number] timeToLive
# @param [Number] atlasIndex
# @param [Particle.ModeA] modeA
# @param [Particle.ModeA] modeB
# @return [Particle]
@Particle: (pos, startPos, color, deltaColor, size, deltaSize, rotation, deltaRotation, timeToLive, atlasIndex, modeA, modeB) ->
# cc.ParticleBatchNode is like a batch node: if it contains children, it will draw them in 1 single OpenGL call (often known as "batch draw").
# @param [String|cc.Texture2D] fileImage
# @param [Number] capacity
# @return [ParticleBatchNode]
@ParticleBatchNode: (fileImage, capacity) ->
# An explosion particle system
# @return [ParticleExplosion]
@ParticleExplosion: ->
# A fire particle system
# @return [ParticleFire]
@ParticleFire: ->
# A fireworks particle system
# @return [ParticleFireworks]
@ParticleFireworks: ->
# A flower particle system
# @return [ParticleFlower]
@ParticleFlower: ->
# A galaxy particle system
# @return [ParticleGalaxy]
@ParticleGalaxy: ->
# A meteor particle system
# @return [ParticleMeteor]
@ParticleMeteor: ->
# A rain particle system
# @return [ParticleRain]
@ParticleRain: ->
# A smoke particle system
# @return [ParticleSmoke]
@ParticleSmoke: ->
# A snow particle system
# @return [ParticleSnow]
@ParticleSnow: ->
# A spiral particle system
# @return [ParticleSpiral]
@ParticleSpiral: ->
# A sun particle system
# @return [ParticleSun]
@ParticleSun: ->
# Particle System base class.
# @return [ParticleSystem]
@ParticleSystem: ->
# @return [path]
@path: ->
# Places the node in a certain position
# @param [Point|Number] pos
# @param [Number] y
# @return [Place]
@Place: (pos, y) ->
# cc.plistParser is a singleton object for parsing plist files
# @return [plistParser]
@plistParser: ->
# cc.Point
# @param [Number] x
# @param [Number] y
# @return [Point]
@Point: (x, y) ->
# Parallax Object.
# @return [PointObject]
@PointObject: ->
# Progress from a percentage to another percentage
# @param [Number] duration
# @param [Number] fromPercentage
# @param [Number] toPercentage
# @return [ProgressFromTo]
@ProgressFromTo: (duration, fromPercentage, toPercentage) ->
# cc.Progresstimer is a subclass of cc.Node.
# @return [ProgressTimer]
@ProgressTimer: ->
# Progress to percentage
# @param [Number] duration
# @param [Number] percent
# @return [ProgressTo]
@ProgressTo: (duration, percent) ->
# A class inhert from cc.Node, use for saving some protected children in other list.
# @return [ProtectedNode]
@ProtectedNode: ->
# cc.Rect
# @param [Number] width
# @param [Number] height
# @param width
# @param height
# @return [Rect]
@Rect: (width, height, width, height) ->
# Delete self in the next frame.
# @param [Boolean] isNeedCleanUp
# @return [RemoveSelf]
@RemoveSelf: (isNeedCleanUp) ->
# cc.RenderTexture is a generic rendering target.
# @return [RenderTexture]
@RenderTexture: ->
# Repeats an action a number of times.
# @param [FiniteTimeAction] action
# @param [Number] times
# @return [Repeat]
@Repeat: (action, times) ->
# Repeats an action for ever.
# @param [FiniteTimeAction] action
# @return [RepeatForever]
@RepeatForever: (action) ->
# cc.ResolutionPolicy class is the root strategy class of scale strategy, its main task is to maintain the compatibility with Cocos2d-x
# @param [ContainerStrategy] containerStg
# @param [ContentStrategy] contentStg
# @return [ResolutionPolicy]
@ResolutionPolicy: (containerStg, contentStg) ->
# cc.ReuseGrid action
# @param [Number] times
# @return [ReuseGrid]
@ReuseGrid: (times) ->
# Executes an action in reverse order, from time=duration to time=0
# @param [FiniteTimeAction] action
# @return [ReverseTime]
@ReverseTime: (action) ->
# An RGBA color class, its value present as percent
# @param [Number] r
# @param [Number] g
# @param [Number] b
# @param [Number] a
# @return [RGBA]
@RGBA: (r, g, b, a) ->
# cc.Ripple3D action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Point] position
# @param [Number] radius
# @param [Number] waves
# @param [Number] amplitude
# @return [Ripple3D]
@Ripple3D: (duration, gridSize, position, radius, waves, amplitude) ->
# Rotates a cc.Node object clockwise a number of degrees by modifying it's rotation attribute.
# @param [Number] duration
# @param [Number] deltaAngleX
# @param [Number] deltaAngleY
# @return [RotateBy]
@RotateBy: (duration, deltaAngleX, deltaAngleY) ->
# Rotates a cc.Node object to a certain angle by modifying it's.
# @param [Number] duration
# @param [Number] deltaAngleX
# @param [Number] deltaAngleY
# @return [RotateTo]
@RotateTo: (duration, deltaAngleX, deltaAngleY) ->
# A SAX Parser
# @return [saxParser]
@saxParser: ->
# A 9-slice sprite for cocos2d.
# @return [Scale9Sprite]
@Scale9Sprite: ->
# Scales a cc.Node object a zoom factor by modifying it's scale attribute.
# @return [ScaleBy]
@ScaleBy: ->
# Scales a cc.Node object to a zoom factor by modifying it's scale attribute.
# @param [Number] duration
# @param [Number] sx
# @param [Number] sy
# @return [ScaleTo]
@ScaleTo: (duration, sx, sy) ->
# cc.Scene is a subclass of cc.Node that is used only as an abstract concept.
# @return [Scene]
@Scene: ->
# Scheduler is responsible of triggering the scheduled callbacks.
# @return [Scheduler]
@Scheduler: ->
# The fullscreen API provides an easy way for web content to be presented using the user's entire screen.
# @return [screen]
@screen: ->
# ScrollView support for cocos2d -x.
# @return [ScrollView]
@ScrollView: ->
# Runs actions sequentially, one after another.
# @param [Array|cc.FiniteTimeAction] tempArray
# @return [Sequence]
@Sequence: (tempArray) ->
# cc.shaderCache is a singleton object that stores manages GL shaders
# @return [shaderCache]
@shaderCache: ->
# cc.Shaky3D action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] range
# @param [Boolean] shakeZ
# @return [Shaky3D]
@Shaky3D: (duration, gridSize, range, shakeZ) ->
# cc.ShakyTiles3D action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] range
# @param [Boolean] shakeZ
# @return [ShakyTiles3D]
@ShakyTiles3D: (duration, gridSize, range, shakeZ) ->
# cc.ShatteredTiles3D action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] range
# @param [Boolean] shatterZ
# @return [ShatteredTiles3D]
@ShatteredTiles3D: (duration, gridSize, range, shatterZ) ->
# Show the node.
# @return [Show]
@Show: ->
# cc.ShuffleTiles action, Shuffle the tiles in random order.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] seed
# @return [ShuffleTiles]
@ShuffleTiles: (duration, gridSize, seed) ->
# cc.Size
# @param [Number] width
# @param [Number] height
# @return [Size]
@Size: (width, height) ->
# Skews a cc.Node object by skewX and skewY degrees.
# @param [Number] t
# @param [Number] sx
# @param [Number] sy
# @return [SkewBy]
@SkewBy: (t, sx, sy) ->
# Skews a cc.Node object to given angles by modifying it's skewX and skewY attributes
# @param [Number] t
# @param [Number] sx
# @param [Number] sy
# @return [SkewTo]
@SkewTo: (t, sx, sy) ->
# The sortable object interface
# @return [SortableObject]
@SortableObject: ->
# The SortedObject class
# @return [SortedObject]
@SortedObject: ->
# The Spacer class
# @return [Spacer]
@Spacer: ->
# Spawn a new action immediately
# @return [Spawn]
@Spawn: ->
# Changes the speed of an action, making it take longer (speed 1) or less (speed
# @param [ActionInterval] action
# @param [Number] speed
# @return [Speed]
@Speed: (action, speed) ->
# cc.SplitCols action.
# @param [Number] duration
# @param [Number] cols
# @return [SplitCols]
@SplitCols: (duration, cols) ->
# cc.SplitRows action.
# @param [Number] duration
# @param [Number] rows
# @return [SplitRows]
@SplitRows: (duration, rows) ->
# cc.Sprite is a 2d image ( http://en.wikipedia.org/wiki/Sprite_(computer_graphics) ) cc.Sprite can be created with an image, or with a sub-rectangle of an image.
# @param [String|cc.SpriteFrame|HTMLImageElement|cc.Texture2D] fileName
# @param [Rect] rect
# @param [Boolean] rotated
# @return [Sprite]
@Sprite: (fileName, rect, rotated) ->
# In Canvas render mode ,cc.SpriteBatchNodeCanvas is like a normal node: if it contains children.
# @param [String|cc.Texture2D] fileImage
# @param [Number] capacity
# @return [SpriteBatchNode]
@SpriteBatchNode: (fileImage, capacity) ->
# A cc.SpriteFrame has: - texture: A cc.Texture2D that will be used by the cc.Sprite - rectangle: A rectangle of the texture You can modify the frame of a cc.Sprite by doing:
# @param [String|cc.Texture2D] filename
# @param [Rect] rect
# @param [Boolean] rotated
# @param [Point] offset
# @param [Size] originalSize
# @return [SpriteFrame]
@SpriteFrame: (filename, rect, rotated, offset, originalSize) ->
# cc.spriteFrameCache is a singleton that handles the loading of the sprite frames.
# @return [spriteFrameCache]
@spriteFrameCache: ->
# cc.StopGrid action.
# @return [StopGrid]
@StopGrid: ->
# UITableView counterpart for cocos2d for iphone.
# @return [TableView]
@TableView: ->
# Abstract class for SWTableView cell node
# @return [TableViewCell]
@TableViewCell: ->
# Overrides the target of an action so that it always runs on the target specified at action creation rather than the one specified by runAction.
# @param [Node] target
# @param [FiniteTimeAction] action
# @return [TargetedAction]
@TargetedAction: (target, action) ->
# cc.Tex2F
# @param [Number] u1
# @param [Number] v1
# @return [Tex2F]
@Tex2F: (u1, v1) ->
# Text field delegate
# @return [TextFieldDelegate]
@TextFieldDelegate: ->
# A simple text input field with TTF font.
# @param [String] placeholder
# @param [Size] dimensions
# @param [Number] alignment
# @param [String] fontName
# @param [Number] fontSize
# @return [TextFieldTTF]
@TextFieldTTF: (placeholder, dimensions, alignment, fontName, fontSize) ->
# This class allows to easily create OpenGL or Canvas 2D textures from images, text or raw data.
# @return [Texture2D]
@Texture2D: ->
# A class that implements a Texture Atlas.
# @return [TextureAtlas]
@TextureAtlas: ->
# cc.textureCache is a singleton object, it's the global cache for cc.Texture2D
# @return [textureCache]
@textureCache: ->
# A Tile composed of position, startPosition and delta.
# @param [Point] position
# @param [Point] startPosition
# @param [Size] delta
# @return [Tile]
@Tile: (position, startPosition, delta) ->
# cc.TiledGrid3D is a 3D grid implementation.
# @return [TiledGrid3D]
@TiledGrid3D: ->
# Base class for cc.TiledGrid3D actions.
# @return [TiledGrid3DAction]
@TiledGrid3DAction: ->
# Light weight timer
# @return [Timer]
@Timer: ->
# Tints a cc.Node that implements the cc.NodeRGB protocol from current tint to a custom one.
# @param [Number] duration
# @param [Number] deltaRed
# @param [Number] deltaGreen
# @param [Number] deltaBlue
# @return [TintBy]
@TintBy: (duration, deltaRed, deltaGreen, deltaBlue) ->
# Tints a cc.Node that implements the cc.NodeRGB protocol from current tint to a custom one.
# @param [Number] duration
# @param [Number] red
# @param [Number] green
# @param [Number] blue
# @return [TintTo]
@TintTo: (duration, red, green, blue) ->
# cc.TMXLayer represents the TMX layer.
# @return [TMXLayer]
@TMXLayer: ->
# cc.TMXLayerInfo contains the information about the layers like: - Layer name - Layer size - Layer opacity at creation time (it can be modified at runtime) - Whether the layer is visible (if it's not visible, then the CocosNode won't be created) This information is obtained from the TMX file.
# @return [TMXLayerInfo]
@TMXLayerInfo: ->
# cc.TMXMapInfo contains the information about the map like: - Map orientation (hexagonal, isometric or orthogonal) - Tile size - Map size And it also contains: - Layers (an array of TMXLayerInfo objects) - Tilesets (an array of TMXTilesetInfo objects) - ObjectGroups (an array of TMXObjectGroupInfo objects) This information is obtained from the TMX file.
# @param [String] tmxFile
# @param [String] resourcePath
# @return [TMXMapInfo]
@TMXMapInfo: (tmxFile, resourcePath) ->
# cc.TMXObjectGroup represents the TMX object group.
# @return [TMXObjectGroup]
@TMXObjectGroup: ->
# cc.TMXTiledMap knows how to parse and render a TMX map.
# @param [String] tmxFile
# @param [String] resourcePath
# @return [TMXTiledMap]
@TMXTiledMap: (tmxFile, resourcePath) ->
# cc.TMXTilesetInfo contains the information about the tilesets like: - Tileset name - Tileset spacing - Tileset margin - size of the tiles - Image used for the tiles - Image size This information is obtained from the TMX file.
# @return [TMXTilesetInfo]
@TMXTilesetInfo: ->
# Toggles the visibility of a node.
# @return [ToggleVisibility]
@ToggleVisibility: ->
# The touch event class
# @param [Number] x
# @param [Number] y
# @param [Number] id
# @return [Touch]
@Touch: (x, y, id) ->
# Cross fades two scenes using the cc.RenderTexture object.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionCrossFade]
@TransitionCrossFade: (t, scene) ->
# Fade out the outgoing scene and then fade in the incoming scene.
# @param [Number] t
# @param [Scene] scene
# @param [TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER] o
# @return [TransitionFade]
@TransitionFade: (t, scene, o) ->
# Fade the tiles of the outgoing scene from the top-right corner to the bottom-left corner.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionFadeBL]
@TransitionFadeBL: (t, scene) ->
# Fade the tiles of the outgoing scene from the top to the bottom.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionFadeDown]
@TransitionFadeDown: (t, scene) ->
# Fade the tiles of the outgoing scene from the left-bottom corner the to top-right corner.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionFadeTR]
@TransitionFadeTR: (t, scene) ->
# Fade the tiles of the outgoing scene from the top-right corner to the bottom-left corner.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionFadeUp]
@TransitionFadeUp: (t, scene) ->
# Flips the screen half horizontally and half vertically.
# @param [Number] t
# @param [Scene] scene
# @param [TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER] o
# @return [TransitionFlipAngular]
@TransitionFlipAngular: (t, scene, o) ->
# Flips the screen horizontally.
# @param [Number] t
# @param [Scene] scene
# @param [TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER] o
# @return [TransitionFlipX]
@TransitionFlipX: (t, scene, o) ->
# Flips the screen vertically.
# @param [Number] t
# @param [Scene] scene
# @param [TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER] o
# @return [TransitionFlipY]
@TransitionFlipY: (t, scene, o) ->
# Zoom out and jump the outgoing scene, and then jump and zoom in the incoming
# @param [Number] t
# @param [Scene] scene
# @return [TransitionJumpZoom]
@TransitionJumpZoom: (t, scene) ->
# Move in from to the bottom the incoming scene.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionMoveInB]
@TransitionMoveInB: (t, scene) ->
# Move in from to the left the incoming scene.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionMoveInL]
@TransitionMoveInL: (t, scene) ->
# Move in from to the right the incoming scene.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionMoveInR]
@TransitionMoveInR: (t, scene) ->
# Move in from to the top the incoming scene.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionMoveInT]
@TransitionMoveInT: (t, scene) ->
# A transition which peels back the bottom right hand corner of a scene to transition to the scene beneath it simulating a page turn.
# @param [Number] t
# @param [Scene] scene
# @param [Boolean] backwards
# @return [TransitionPageTurn]
@TransitionPageTurn: (t, scene, backwards) ->
# cc.TransitionProgress transition.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionProgress]
@TransitionProgress: (t, scene) ->
# cc.TransitionProgressHorizontal transition.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionProgressHorizontal]
@TransitionProgressHorizontal: (t, scene) ->
# cc.TransitionProgressInOut transition.
# @return [TransitionProgressInOut]
@TransitionProgressInOut: ->
# cc.TransitionProgressOutIn transition.
# @return [TransitionProgressOutIn]
@TransitionProgressOutIn: ->
# cc.TransitionRadialCCW transition.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionProgressRadialCCW]
@TransitionProgressRadialCCW: (t, scene) ->
# cc.TransitionRadialCW transition.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionProgressRadialCW]
@TransitionProgressRadialCW: (t, scene) ->
# cc.TransitionProgressVertical transition.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionProgressVertical]
@TransitionProgressVertical: (t, scene) ->
# Rotate and zoom out the outgoing scene, and then rotate and zoom in the incoming
# @param [Number] t
# @param [Scene] scene
# @return [TransitionRotoZoom]
@TransitionRotoZoom: (t, scene) ->
# @param [Number] t
# @param [Scene] scene
# @return [TransitionScene]
@TransitionScene: (t, scene) ->
# A cc.Transition that supports orientation like.
# @param [Number] t
# @param [Scene] scene
# @param [TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER] orientation
# @return [TransitionSceneOriented]
@TransitionSceneOriented: (t, scene, orientation) ->
# Shrink the outgoing scene while grow the incoming scene
# @param [Number] t
# @param [Scene] scene
# @return [TransitionShrinkGrow]
@TransitionShrinkGrow: (t, scene) ->
# Slide in the incoming scene from the bottom border.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionSlideInB]
@TransitionSlideInB: (t, scene) ->
# a transition that a new scene is slided from left
# @param [Number] t
# @param [Scene] scene
# @return [TransitionSlideInL]
@TransitionSlideInL: (t, scene) ->
# Slide in the incoming scene from the right border.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionSlideInR]
@TransitionSlideInR: (t, scene) ->
# Slide in the incoming scene from the top border.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionSlideInT]
@TransitionSlideInT: (t, scene) ->
# The odd columns goes upwards while the even columns goes downwards.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionSplitCols]
@TransitionSplitCols: (t, scene) ->
# The odd rows goes to the left while the even rows goes to the right.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionSplitRows]
@TransitionSplitRows: (t, scene) ->
# Turn off the tiles of the outgoing scene in random order
# @param [Number] t
# @param [Scene] scene
# @return [TransitionTurnOffTiles]
@TransitionTurnOffTiles: (t, scene) ->
# Flips the screen half horizontally and half vertically doing a little zooming out/in.
# @param [Number] t
# @param [Scene] scene
# @param [TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER] o
# @return [TransitionZoomFlipAngular]
@TransitionZoomFlipAngular: (t, scene, o) ->
# Flips the screen horizontally doing a zoom out/in The front face is the outgoing scene and the back face is the incoming scene.
# @param [Number] t
# @param [Scene] scene
# @param [TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER] o
# @return [TransitionZoomFlipX]
@TransitionZoomFlipX: (t, scene, o) ->
# Flips the screen vertically doing a little zooming out/in The front face is the outgoing scene and the back face is the incoming scene.
# @param [Number] t
# @param [Scene] scene
# @param [TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER] o
# @return [TransitionZoomFlipY]
@TransitionZoomFlipY: (t, scene, o) ->
# cc.TurnOffTiles action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number|Null] seed
# @return [TurnOffTiles]
@TurnOffTiles: (duration, gridSize, seed) ->
# cc.Twirl action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Point] position
# @param [Number] twirls
# @param [Number] amplitude
# @return [Twirl]
@Twirl: (duration, gridSize, position, twirls, amplitude) ->
# cc.Vertex2F
# @param [Number] x1
# @param [Number] y1
# @return [Vertex2F]
@Vertex2F: (x1, y1) ->
# cc.Vertex3F
# @param [Number] x1
# @param [Number] y1
# @param [Number] z1
# @return [Vertex3F]
@Vertex3F: (x1, y1, z1) ->
# cc.view is the singleton object which represents the game window.
# @return [view]
@view: ->
# cc.visibleRect is a singleton object which defines the actual visible rect of the current view, it should represent the same rect as cc.view.getViewportRect()
# @return [visibleRect]
@visibleRect: ->
# cc.Waves action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] waves
# @param [Number] amplitude
# @param [Boolean] horizontal
# @param [Boolean] vertical
# @return [Waves]
@Waves: (duration, gridSize, waves, amplitude, horizontal, vertical) ->
# cc.Waves3D action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] waves
# @param [Number] amplitude
# @return [Waves3D]
@Waves3D: (duration, gridSize, waves, amplitude) ->
# cc.WavesTiles3D action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] waves
# @param [Number] amplitude
# @return [WavesTiles3D]
@WavesTiles3D: (duration, gridSize, waves, amplitude) ->
# A class of Web Audio.
# @param src
# @return [WebAudio]
@WebAudio: (src) ->
| 94134 |
class cc
# Default Action tag
@ACTION_TAG_INVALID = {}
# The adjust factor is needed to prevent issue #442 One solution is to use DONT_RENDER_IN_SUBPIXELS images, but NO The other issue is that in some transitions (and I don't know why) the order should be reversed (In in top of Out or vice-versa).
# [Number]
@ADJUST_FACTOR = 1
# Horizontal center and vertical bottom.
# [Number]
@ALIGN_BOTTOM = 1
# Horizontal left and vertical bottom.
# [Number]
@ALIGN_BOTTOM_LEFT = 1
# Horizontal right and vertical bottom.
# [Number]
@ALIGN_BOTTOM_RIGHT = 1
# Horizontal center and vertical center.
# [Number]
@ALIGN_CENTER = 1
# Horizontal left and vertical center.
# [Number]
@ALIGN_LEFT = 1
# Horizontal right and vertical center.
# [Number]
@ALIGN_RIGHT = 1
# Horizontal center and vertical top.
# [Number]
@ALIGN_TOP = 1
# Horizontal left and vertical top.
# [Number]
@ALIGN_TOP_LEFT = 1
# Horizontal right and vertical top.
# [Number]
@ALIGN_TOP_RIGHT = 1
@ATTRIBUTE_NAME_COLOR = {}
@ATTRIBUTE_NAME_POSITION = {}
@ATTRIBUTE_NAME_TEX_COORD = {}
# default gl blend dst function.
# [Number]
@BLEND_DST = 1
# default gl blend src function.
# [Number]
@BLEND_SRC = 1
# A CCCamera is used in every CCNode.
@Camera = {}
# If enabled, the cc.Node objects (cc.Sprite, cc.Label,etc) will be able to render in subpixels.
@COCOSNODE_RENDER_SUBPIXEL = {}
# Number of kinds of control event.
@CONTROL_EVENT_TOTAL_NUMBER = {}
# Kinds of possible events for the control objects.
@CONTROL_EVENT_TOUCH_DOWN = {}
# The possible state for a control.
@CONTROL_STATE_NORMAL = {}
# returns a new clone of the controlPoints
# [Array]
@copyControlPoints = []
# default tag for current item
# [Number]
@CURRENT_ITEM = 1
# Default engine
@DEFAULT_ENGINE = {}
# [Number]
@DEFAULT_PADDING = 1
# [Number]
@DEFAULT_SPRITE_BATCH_CAPACITY = 1
# Default fps is 60
@defaultFPS = {}
# [Number]
@DEG = 1
# In browsers, we only support 2 orientations by change window size.
# [Number]
@DEVICE_MAX_ORIENTATIONS = 1
# Device oriented horizontally, home button on the right (UIDeviceOrientationLandscapeLeft)
# [Number]
@DEVICE_ORIENTATION_LANDSCAPE_LEFT = 1
# Device oriented horizontally, home button on the left (UIDeviceOrientationLandscapeRight)
# [Number]
@DEVICE_ORIENTATION_LANDSCAPE_RIGHT = 1
# Device oriented vertically, home button on the bottom (UIDeviceOrientationPortrait)
# [Number]
@DEVICE_ORIENTATION_PORTRAIT = 1
# Device oriented vertically, home button on the top (UIDeviceOrientationPortraitUpsideDown)
# [Number]
@DEVICE_ORIENTATION_PORTRAIT_UPSIDE_DOWN = 1
@director = {}
# Seconds between FPS updates.
@DIRECTOR_FPS_INTERVAL = {}
# Position of the FPS (Default: 0,0 (bottom-left corner)) To modify it, in Web engine please refer to CCConfig.js, in JSB please refer to CCConfig.h
@DIRECTOR_STATS_POSITION = {}
# default disabled tag
# [Number]
@DISABLE_TAG = 1
# ************************************************ implementation of DisplayLinkDirector ************************************************
@DisplayLinkDirector = {}
# [Number]
@DST_ALPHA = 1
# [Number]
@DST_COLOR = 1
# Capitalize all characters automatically.
# [Number]
@EDITBOX_INPUT_FLAG_INITIAL_CAPS_ALL_CHARACTERS = 1
# This flag is a hint to the implementation that during text editing, the initial letter of each sentence should be capitalized.
# [Number]
@EDITBOX_INPUT_FLAG_INITIAL_CAPS_SENTENCE = 1
# This flag is a hint to the implementation that during text editing, the initial letter of each word should be capitalized.
# [Number]
@EDITBOX_INPUT_FLAG_INITIAL_CAPS_WORD = 1
# Indicates that the text entered is confidential data that should be obscured whenever possible.
# [Number]
@EDITBOX_INPUT_FLAG_PASSWORD = 1
# Indicates that the text entered is sensitive data that the implementation must never store into a dictionary or table for use in predictive, auto-completing, or other accelerated input schemes.
# [Number]
@EDITBOX_INPUT_FLAG_SENSITIVE = 1
# The EditBoxInputMode defines the type of text that the user is allowed * to enter.
# [Number]
@EDITBOX_INPUT_MODE_ANY = 1
# The user is allowed to enter a real number value.
# [Number]
@EDITBOX_INPUT_MODE_DECIMAL = 1
# The user is allowed to enter an e-mail address.
# [Number]
@EDITBOX_INPUT_MODE_EMAILADDR = 1
# The user is allowed to enter an integer value.
# [Number]
@EDITBOX_INPUT_MODE_NUMERIC = 1
# The user is allowed to enter a phone number.
# [Number]
@EDITBOX_INPUT_MODE_PHONENUMBER = 1
# The user is allowed to enter any text, except for line breaks.
# [Number]
@EDITBOX_INPUT_MODE_SINGLELINE = 1
# The user is allowed to enter a URL.
# [Number]
@EDITBOX_INPUT_MODE_URL = 1
# If enabled, cocos2d will maintain an OpenGL state cache internally to avoid unnecessary switches.
@ENABLE_GL_STATE_CACHE = {}
# If enabled, actions that alter the position property (eg: CCMoveBy, CCJumpBy, CCBezierBy, etc.
@ENABLE_STACKABLE_ACTIONS = {}
# The current version of Cocos2d-JS being used.
@ENGINE_VERSION = {}
# If enabled, the texture coordinates will be calculated by using this formula: - texCoord.left = (rect.x*2+1) / (texture.wide*2); - texCoord.right = texCoord.left + (rect.width*2-2)/(texture.wide*2); The same for bottom and top.
@FIX_ARTIFACTS_BY_STRECHING_TEXEL = {}
# [Number]
@FLT_EPSILON = 1
# [Number]
@FLT_MAX = 1
# [Number]
@FLT_MIN = 1
# Image Format:JPG
@FMT_JPG = {}
# Image Format:PNG
@FMT_PNG = {}
# Image Format:RAWDATA
@FMT_RAWDATA = {}
# Image Format:TIFF
@FMT_TIFF = {}
# Image Format:UNKNOWN
@FMT_UNKNOWN = {}
# Image Format:WEBP
@FMT_WEBP = {}
# ************************************************************************* Copyright (c) 2008-2010 <NAME> Copyright (c) 2011-2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc.
@g_NumberOfDraws = {}
# GL server side states
@GL_ALL = {}
# A update entry list
@HashUpdateEntry = {}
# enum for jpg
# [Number]
@IMAGE_FORMAT_JPEG = 1
# enum for png
# [Number]
@IMAGE_FORMAT_PNG = 1
# enum for raw
# [Number]
@IMAGE_FORMAT_RAWDATA = 1
# [Number]
@INVALID_INDEX = 1
# Whether or not support retina display
@IS_RETINA_DISPLAY_SUPPORTED = {}
# default size for font size
# [Number]
@ITEM_SIZE = 1
# Key map for keyboard event
@KEY = {}
# [Number]
@KEYBOARD_RETURNTYPE_DEFAULT = 1
# [Number]
@KEYBOARD_RETURNTYPE_DONE = 1
# [Number]
@KEYBOARD_RETURNTYPE_GO = 1
# [Number]
@KEYBOARD_RETURNTYPE_SEARCH = 1
# [Number]
@KEYBOARD_RETURNTYPE_SEND = 1
# [Number]
@LABEL_AUTOMATIC_WIDTH = 1
# If enabled, all subclasses of cc.LabelAtlas will draw a bounding box Useful for debugging purposes only.
@LABELATLAS_DEBUG_DRAW = {}
# If enabled, all subclasses of cc.LabelBMFont will draw a bounding box Useful for debugging purposes only.
@LABELBMFONT_DEBUG_DRAW = {}
# A list double-linked list used for "updates with priority"
@ListEntry = {}
# The min corner of the box
@max = {}
# [Number]
@MENU_HANDLER_PRIORITY = 1
# [Number]
@MENU_STATE_TRACKING_TOUCH = 1
# [Number]
@MENU_STATE_WAITING = 1
# The max corner of the box
@min = {}
# Default Node tag
# [Number]
@NODE_TAG_INVALID = 1
# NodeGrid class is a class serves as a decorator of cc.Node, Grid node can run grid actions over all its children
@NodeGrid = {}
# default tag for normal
# [Number]
@NORMAL_TAG = 1
# [Number]
@ONE = 1
# [Number]
@ONE_MINUS_CONSTANT_ALPHA = 1
# [Number]
@ONE_MINUS_CONSTANT_COLOR = 1
# [Number]
@ONE_MINUS_DST_ALPHA = 1
# [Number]
@ONE_MINUS_DST_COLOR = 1
# [Number]
@ONE_MINUS_SRC_ALPHA = 1
# [Number]
@ONE_MINUS_SRC_COLOR = 1
# If most of your images have pre-multiplied alpha, set it to 1 (if you are going to use .PNG/.JPG file images).
@OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA = {}
# Device oriented horizontally, home button on the right
@ORIENTATION_LANDSCAPE_LEFT = {}
# Device oriented horizontally, home button on the left
@ORIENTATION_LANDSCAPE_RIGHT = {}
# Device oriented vertically, home button on the bottom
@ORIENTATION_PORTRAIT = {}
# Device oriented vertically, home button on the top
@ORIENTATION_PORTRAIT_UPSIDE_DOWN = {}
# paticle default capacity
# [Number]
@PARTICLE_DEFAULT_CAPACITY = 1
# PI is the ratio of a circle's circumference to its diameter.
# [Number]
@PI = 1
@plistParser A Plist Parser A Plist Parser = {}
# smallest such that 1.0+FLT_EPSILON != 1.0
# [Number]
@POINT_EPSILON = 1
# Minimum priority level for user scheduling.
# [Number]
@PRIORITY_NON_SYSTEM = 1
# [Number]
@RAD = 1
# [Number]
@REPEAT_FOREVER = 1
# It's the suffix that will be appended to the files in order to load "retina display" images.
@RETINA_DISPLAY_FILENAME_SUFFIX = {}
# If enabled, cocos2d supports retina display.
@RETINA_DISPLAY_SUPPORT = {}
# XXX: Yes, nodes might have a sort problem once every 15 days if the game runs at 60 FPS and each frame sprites are reordered.
@s_globalOrderOfArrival = {}
# A tag constant for identifying fade scenes
# [Number]
@SCENE_FADE = 1
# tag for scene redial
# [Number]
@SCENE_RADIAL = 1
# default selected tag
# [Number]
@SELECTED_TAG = 1
@SHADER_POSITION_COLOR = {}
@SHADER_POSITION_COLOR_FRAG = {}
@SHADER_POSITION_COLOR_LENGTH_TEXTURE_FRAG = {}
@SHADER_POSITION_COLOR_LENGTH_TEXTURE_VERT = {}
@SHADER_POSITION_COLOR_VERT = {}
@SHADER_POSITION_LENGTHTEXTURECOLOR = {}
@SHADER_POSITION_TEXTURE = {}
@SHADER_POSITION_TEXTURE_A8COLOR_FRAG = {}
@SHADER_POSITION_TEXTURE_A8COLOR_VERT = {}
@SHADER_POSITION_TEXTURE_COLOR_ALPHATEST_FRAG = {}
@SHADER_POSITION_TEXTURE_COLOR_FRAG = {}
@SHADER_POSITION_TEXTURE_COLOR_VERT = {}
@SHADER_POSITION_TEXTURE_FRAG = {}
@SHADER_POSITION_TEXTURE_UCOLOR = {}
@SHADER_POSITION_TEXTURE_UCOLOR_FRAG = {}
@SHADER_POSITION_TEXTURE_UCOLOR_VERT = {}
@SHADER_POSITION_TEXTURE_VERT = {}
@SHADER_POSITION_TEXTUREA8COLOR = {}
@SHADER_POSITION_TEXTURECOLOR = {}
@SHADER_POSITION_TEXTURECOLORALPHATEST = {}
@SHADER_POSITION_UCOLOR = {}
@SHADER_POSITION_UCOLOR_FRAG = {}
@SHADER_POSITION_UCOLOR_VERT = {}
@SHADEREX_SWITCHMASK_FRAG = {}
# If enabled, all subclasses of cc.Sprite will draw a bounding box Useful for debugging purposes only.
@SPRITE_DEBUG_DRAW = {}
# If enabled, all subclasses of cc.Sprite that are rendered using an cc.SpriteBatchNode draw a bounding box.
@SPRITEBATCHNODE_DEBUG_DRAW = {}
# If enabled, the cc.Sprite objects rendered with cc.SpriteBatchNode will be able to render in subpixels.
@SPRITEBATCHNODE_RENDER_SUBPIXEL = {}
# [Number]
@SRC_ALPHA = 1
# [Number]
@SRC_ALPHA_SATURATE = 1
# [Number]
@SRC_COLOR = 1
# the value of stencil bits.
# [Number]
@stencilBits = 1
# The constant value of the fill style from bottom to top for cc.TableView
@TABLEVIEW_FILL_BOTTOMUP = {}
# The constant value of the fill style from top to bottom for cc.TableView
@TABLEVIEW_FILL_TOPDOWN = {}
# Data source that governs table backend data.
@TableViewDataSource = {}
# Sole purpose of this delegate is to single touch event in this version.
@TableViewDelegate = {}
# text alignment : center
# [Number]
@TEXT_ALIGNMENT_CENTER = 1
# text alignment : left
# [Number]
@TEXT_ALIGNMENT_LEFT = 1
# text alignment : right
# [Number]
@TEXT_ALIGNMENT_RIGHT = 1
# Use GL_TRIANGLE_STRIP instead of GL_TRIANGLES when rendering the texture atlas.
@TEXTURE_ATLAS_USE_TRIANGLE_STRIP = {}
# By default, cc.TextureAtlas (used by many cocos2d classes) will use VAO (Vertex Array Objects).
@TEXTURE_ATLAS_USE_VAO = {}
# If enabled, NPOT textures will be used where available.
@TEXTURE_NPOT_SUPPORT = {}
# [Number]
@TGA_ERROR_COMPRESSED_FILE = 1
# [Number]
@TGA_ERROR_FILE_OPEN = 1
# [Number]
@TGA_ERROR_INDEXED_COLOR = 1
# [Number]
@TGA_ERROR_MEMORY = 1
# [Number]
@TGA_ERROR_READING_FILE = 1
# [Number]
@TGA_OK = 1
# A png file reader
@tiffReader = {}
# Hexagonal orientation
# [Number]
@TMX_ORIENTATION_HEX = 1
# Isometric orientation
# [Number]
@TMX_ORIENTATION_ISO = 1
# Orthogonal orientation
# [Number]
@TMX_ORIENTATION_ORTHO = 1
# [Number]
@TMX_PROPERTY_LAYER = 1
# [Number]
@TMX_PROPERTY_MAP = 1
# [Number]
@TMX_PROPERTY_NONE = 1
# [Number]
@TMX_PROPERTY_OBJECT = 1
# [Number]
@TMX_PROPERTY_OBJECTGROUP = 1
# [Number]
@TMX_PROPERTY_TILE = 1
# [Number]
@TMX_TILE_DIAGONAL_FLAG = 1
# [Number]
@TMX_TILE_FLIPPED_ALL = 1
# [Number]
@TMX_TILE_FLIPPED_MASK = 1
# [Number]
@TMX_TILE_HORIZONTAL_FLAG = 1
# [Number]
@TMX_TILE_VERTICAL_FLAG = 1
# vertical orientation type where the Bottom is nearer
# [Number]
@TRANSITION_ORIENTATION_DOWN_OVER = 1
# horizontal orientation Type where the Left is nearer
# [Number]
@TRANSITION_ORIENTATION_LEFT_OVER = 1
# horizontal orientation type where the Right is nearer
# [Number]
@TRANSITION_ORIENTATION_RIGHT_OVER = 1
# vertical orientation type where the Up is nearer
# [Number]
@TRANSITION_ORIENTATION_UP_OVER = 1
@UIInterfaceOrientationLandscapeLeft = {}
@UIInterfaceOrientationLandscapeRight = {}
@UIInterfaceOrientationPortrait = {}
@UIInterfaceOrientationPortraitUpsideDown = {}
# maximum unsigned int value
# [Number]
@UINT_MAX = 1
@UNIFORM_ALPHA_TEST_VALUE_S = {}
@UNIFORM_COSTIME = {}
@UNIFORM_COSTIME_S = {}
@UNIFORM_MAX = {}
@UNIFORM_MVMATRIX = {}
@UNIFORM_MVMATRIX_S = {}
@UNIFORM_MVPMATRIX = {}
@UNIFORM_MVPMATRIX_S = {}
@UNIFORM_PMATRIX = {}
@UNIFORM_PMATRIX_S = {}
@UNIFORM_RANDOM01 = {}
@UNIFORM_RANDOM01_S = {}
@UNIFORM_SAMPLER = {}
@UNIFORM_SAMPLER_S = {}
@UNIFORM_SINTIME = {}
@UNIFORM_SINTIME_S = {}
@UNIFORM_TIME = {}
@UNIFORM_TIME_S = {}
# If enabled, it will use LA88 (Luminance Alpha 16-bit textures) for CCLabelTTF objects.
@USE_LA88_LABELS = {}
@VERTEX_ATTRIB_COLOR = {}
@VERTEX_ATTRIB_FLAG_COLOR = {}
@VERTEX_ATTRIB_FLAG_NONE = {}
@VERTEX_ATTRIB_FLAG_POS_COLOR_TEX = {}
@VERTEX_ATTRIB_FLAG_POSITION = {}
@VERTEX_ATTRIB_FLAG_TEX_COORDS = {}
@VERTEX_ATTRIB_MAX = {}
@VERTEX_ATTRIB_POSITION = {}
@VERTEX_ATTRIB_TEX_COORDS = {}
# text alignment : bottom
# [Number]
@VERTICAL_TEXT_ALIGNMENT_BOTTOM = 1
# text alignment : center
# [Number]
@VERTICAL_TEXT_ALIGNMENT_CENTER = 1
# text alignment : top
# [Number]
@VERTICAL_TEXT_ALIGNMENT_TOP = 1
# [Number]
@ZERO = 1
# default tag for zoom action tag
# [Number]
@ZOOM_ACTION_TAG = 1
# the dollar sign, classic like jquery, this selector add extra methods to HTMLElement without touching its prototype it is also chainable like jquery
# @param [HTMLElement|String] x
# @return [$]
@$: (x) ->
# Creates a new element, and adds cc.$ methods
# @param [String] x
# @return [$]
@$new: (x) ->
# Allocates and initializes the action.
# @return [Action]
@action: ->
# creates the action of ActionEase
# @param [ActionInterval] action
# @return [ActionEase]
@actionEase: (action) ->
# An interval action is an action that takes place within a certain period of time.
# @param [Number] d
# @return [ActionInterval]
@actionInterval: (d) ->
# Creates an initializes the action with the property name (key), and the from and to parameters.
# @param [Number] duration
# @param [String] key
# @param [Number] from
# @param [Number] to
# @return [ActionTween]
@actionTween: (duration, key, from, to) ->
# Concatenate a transform matrix to another and return the result: t' = t1 * t2
# @param [AffineTransform] t1
# @param [AffineTransform] t2
# @return [AffineTransform]
@affineTransformConcat: (t1, t2) ->
# Return true if an affine transform equals to another, false otherwise.
# @param [AffineTransform] t1
# @param [AffineTransform] t2
# @return [Boolean]
@affineTransformEqualToTransform: (t1, t2) ->
# Create a identity transformation matrix: [ 1, 0, 0, 0, 1, 0 ]
# @return [AffineTransform]
@affineTransformIdentity: ->
# Get the invert transform of an AffineTransform object
# @param [AffineTransform] t
# @return [AffineTransform]
@affineTransformInvert: (t) ->
# Create a cc.AffineTransform object with all contents in the matrix
# @param [Number] a
# @param [Number] b
# @param [Number] c
# @param [Number] d
# @param [Number] tx
# @param [Number] ty
# @return [AffineTransform]
@affineTransformMake: (a, b, c, d, tx, ty) ->
# Create a identity transformation matrix: [ 1, 0, 0, 0, 1, 0 ]
# @return [AffineTransform]
@affineTransformMakeIdentity: ->
# Create a new affine transformation with a base transformation matrix and a rotation based on it.
# @param [AffineTransform] aTransform
# @param [Number] anAngle
# @return [AffineTransform]
@affineTransformRotate: (aTransform, anAngle) ->
# Create a new affine transformation with a base transformation matrix and a scale based on it.
# @param [AffineTransform] t
# @param [Number] sx
# @param [Number] sy
# @return [AffineTransform]
@affineTransformScale: (t, sx, sy) ->
# Create a new affine transformation with a base transformation matrix and a translation based on it.
# @param [AffineTransform] t
# @param [Number] tx
# @param [Number] ty
# @return [AffineTransform]
@affineTransformTranslate: (t, tx, ty) ->
# create the animate with animation
# @param [Animation] animation
# @return [Animate]
@animate: (animation) ->
# Inserts some objects at index
# @param [Array] arr
# @param [Array] addObjs
# @param [Number] index
# @return [Array]
@arrayAppendObjectsToIndex: (arr, addObjs, index) ->
# Removes from arr all values in minusArr.
# @param [Array] arr
# @param [Array] minusArr
@arrayRemoveArray: (arr, minusArr) ->
# Searches for the first occurance of object and removes it.
# @param [Array] arr
# @param [*] delObj
@arrayRemoveObject: (arr, delObj) ->
# Verify Array's Type
# @param [Array] arr
# @param [function] type
# @return [Boolean]
@arrayVerifyType: (arr, type) ->
# Function added for JS bindings compatibility.
# @param [object] jsObj
# @param [object] superclass
@associateWithNative: (jsObj, superclass) ->
# @param me
# @param opt_methodName
# @param var_args
@base: (me, opt_methodName, var_args) ->
# @param [Number] a
# @param [Number] b
# @param [Number] c
# @param [Number] d
# @param [Number] t
# @return [Number]
@bezierAt: (a, b, c, d, t) ->
# An action that moves the target with a cubic Bezier curve by a certain distance.
# @param [Number] t
# @param [Array] c
# @return [BezierBy]
@bezierBy: (t, c) ->
# An action that moves the target with a cubic Bezier curve to a destination point.
# @param [Number] t
# @param [Array] c
# @return [BezierTo]
@bezierTo: (t, c) ->
# Blend Function used for textures
# @param [Number] src1
# @param [Number] dst1
@BlendFunc: (src1, dst1) ->
# @return [BlendFunc]
@blendFuncDisable: ->
# Blinks a cc.Node object by modifying it's visible attribute.
# @param [Number] duration
# @param blinks
# @return [Blink]
@blink: (duration, blinks) ->
# Creates the action with the callback
# @param [function] selector
# @param [object|null] selectorTarget
# @param [*|null] data
# @return [CallFunc]
@callFunc: (selector, selectorTarget, data) ->
# Returns the Cardinal Spline position for a given set of control points, tension and time.
# @param [Point] p0
# @param [Point] p1
# @param [Point] p2
# @param [Point] p3
# @param [Number] tension
# @param [Number] t
# @return [Point]
@cardinalSplineAt: (p0, p1, p2, p3, tension, t) ->
# creates an action with a Cardinal Spline array of points and tension.
# @param [Number] duration
# @param [Array] points
# @param [Number] tension
# @return [CardinalSplineBy]
@cardinalSplineBy: (duration, points, tension) ->
# creates an action with a Cardinal Spline array of points and tension.
# @param [Number] duration
# @param [Array] points
# @param [Number] tension
# @return [CardinalSplineTo]
@cardinalSplineTo: (duration, points, tension) ->
# Creates an action with a Cardinal Spline array of points and tension
# @param [Number] dt
# @param [Array] points
# @return [CatmullRomBy]
@catmullRomBy: (dt, points) ->
# creates an action with a Cardinal Spline array of points and tension.
# @param [Number] dt
# @param [Array] points
# @return [CatmullRomTo]
@catmullRomTo: (dt, points) ->
# convert an affine transform object to a kmMat4 object
# @param [AffineTransform] trans
# @param [kmMat4] mat
@CGAffineToGL: (trans, mat) ->
# Check webgl error.Error will be shown in console if exists.
@checkGLErrorDebug: ->
# Clamp a value between from and to.
# @param [Number] value
# @param [Number] min_inclusive
# @param [Number] max_inclusive
# @return [Number]
@clampf: (value, min_inclusive, max_inclusive) ->
# Create a new object and copy all properties in an exist object to the new object
# @param [object|Array] obj
# @return [Array|object]
@clone: (obj) ->
# returns a new clone of the controlPoints
# @param controlPoints
# @return [Array]
@cloneControlPoints: (controlPoints) ->
# Generate a color object based on multiple forms of parameters
# @param [Number|String|cc.Color] r
# @param [Number] g
# @param [Number] b
# @param [Number] a
# @return [Color]
@color: (r, g, b, a) ->
# returns true if both ccColor3B are equal.
# @param [Color] color1
# @param [Color] color2
# @return [Boolean]
@colorEqual: (color1, color2) ->
# convert Color to a string of color for style.
# @param [Color] color
# @return [String]
@colorToHex: (color) ->
# On Mac it returns 1; On iPhone it returns 2 if RetinaDisplay is On.
# @return [Number]
@contentScaleFactor: ->
# Copy an array's item to a new array (its performance is better than Array.slice)
# @param [Array] arr
# @return [Array]
@copyArray: (arr) ->
# create a webgl context
# @param [HTMLCanvasElement] canvas
# @param [Object] opt_attribs
# @return [WebGLRenderingContext]
@create3DContext: (canvas, opt_attribs) ->
# Common getter setter configuration function
# @param [Object] proto
# @param [String] prop
# @param [function] getter
# @param [function] setter
# @param [String] getterName
# @param [String] setterName
@defineGetterSetter: (proto, prop, getter, setter, getterName, setterName) ->
# converts degrees to radians
# @param [Number] angle
# @return [Number]
@degreesToRadians: (angle) ->
# Delays the action a certain amount of seconds
# @param [Number] d
# @return [DelayTime]
@delayTime: (d) ->
# Disable default GL states: - GL_TEXTURE_2D - GL_TEXTURE_COORD_ARRAY - GL_COLOR_ARRAY
@disableDefaultGLStates: ->
# Iterate over an object or an array, executing a function for each matched element.
# @param [object|array] obj
# @param [function] iterator
# @param [object] context
@each: (obj, iterator, context) ->
# Creates the action easing object.
# @return [Object]
@easeBackIn: ->
# Creates the action easing object.
# @return [Object]
@easeBackInOut: ->
# Creates the action easing object.
# @return [Object]
@easeBackOut: ->
# Creates the action easing object.
# @param [Number] p0
# @param [Number] p1
# @param [Number] p2
# @param [Number] p3
# @return [Object]
@easeBezierAction: (p0, p1, p2, p3) ->
# Creates the action easing object.
# @return [Object]
@easeBounceIn: ->
# Creates the action easing object.
# @return [Object]
@easeBounceInOut: ->
# Creates the action easing object.
# @return [Object]
@easeBounceOut: ->
# Creates the action easing object.
# @return [Object]
@easeCircleActionIn: ->
# Creates the action easing object.
# @return [Object]
@easeCircleActionInOut: ->
# Creates the action easing object.
# @return [Object]
@easeCircleActionOut: ->
# Creates the action easing object.
# @return [Object]
@easeCubicActionIn: ->
# Creates the action easing object.
# @return [Object]
@easeCubicActionInOut: ->
# Creates the action easing object.
# @return [Object]
@easeCubicActionOut: ->
# Creates the action easing obejct with the period in radians (default is 0.3).
# @param [Number] period
# @return [Object]
@easeElasticIn: (period) ->
# Creates the action easing object with the period in radians (default is 0.3).
# @param [Number] period
# @return [Object]
@easeElasticInOut: (period) ->
# Creates the action easing object with the period in radians (default is 0.3).
# @param [Number] period
# @return [Object]
@easeElasticOut: (period) ->
# Creates the action easing object with the rate parameter.
# @return [Object]
@easeExponentialIn: ->
# creates an EaseExponentialInOut action easing object.
# @return [Object]
@easeExponentialInOut: ->
# creates the action easing object.
# @return [Object]
@easeExponentialOut: ->
# Creates the action easing object with the rate parameter.
# @param [Number] rate
# @return [Object]
@easeIn: (rate) ->
# Creates the action easing object with the rate parameter.
# @param [Number] rate
# @return [Object]
@easeInOut: (rate) ->
# Creates the action easing object with the rate parameter.
# @param [Number] rate
# @return [Object]
@easeOut: (rate) ->
# Creates the action easing object.
# @return [Object]
@easeQuadraticActionIn: ->
# Creates the action easing object.
# @return [Object]
@easeQuadraticActionInOut: ->
# Creates the action easing object.
# @return [Object]
@easeQuadraticActionOut: ->
# Creates the action easing object.
# @return [Object]
@easeQuarticActionIn: ->
# Creates the action easing object.
# @return [Object]
@easeQuarticActionInOut: ->
# Creates the action easing object.
# @return [Object]
@easeQuarticActionOut: ->
# Creates the action easing object.
# @return [Object]
@easeQuinticActionIn: ->
# Creates the action easing object.
# @return [Object]
@easeQuinticActionInOut: ->
# Creates the action easing object.
# @return [Object]
@easeQuinticActionOut: ->
# Creates the action with the inner action and the rate parameter.
# @param [ActionInterval] action
# @param [Number] rate
# @return [EaseRateAction]
@easeRateAction: (action, rate) ->
# creates an EaseSineIn action.
# @return [Object]
@easeSineIn: ->
# creates the action easing object.
# @return [Object]
@easeSineInOut: ->
# Creates an EaseSineOut action easing object.
# @return [Object]
@easeSineOut: ->
# GL states that are enabled: - GL_TEXTURE_2D - GL_VERTEX_ARRAY - GL_TEXTURE_COORD_ARRAY - GL_COLOR_ARRAY
@enableDefaultGLStates: ->
# Copy all of the properties in source objects to target object and return the target object.
# @param [object] target
# @param [object] *sources
# @return [object]
@extend: (target, *sources) ->
# Fades In an object that implements the cc.RGBAProtocol protocol.
# @param [Number] duration
# @return [FadeIn]
@fadeIn: (duration) ->
# Fades Out an object that implements the cc.RGBAProtocol protocol.
# @param [Number] d
# @return [FadeOut]
@fadeOut: (d) ->
# Creates the action with the grid size and the duration.
# @param duration
# @param gridSize
# @return [FadeOutBLTiles]
@fadeOutBLTiles: (duration, gridSize) ->
# Creates the action with the grid size and the duration.
# @param [Number] duration
# @param [Size] gridSize
# @return [FadeOutDownTiles]
@fadeOutDownTiles: (duration, gridSize) ->
# Creates the action with the grid size and the duration.
# @param duration
# @param gridSize
# @return [FadeOutTRTiles]
@fadeOutTRTiles: (duration, gridSize) ->
# Creates the action with the grid size and the duration.
# @param [Number] duration
# @param [Size] gridSize
# @return [FadeOutUpTiles]
@fadeOutUpTiles: (duration, gridSize) ->
# Fades an object that implements the cc.RGBAProtocol protocol.
# @param [Number] duration
# @param [Number] opacity
# @return [FadeTo]
@fadeTo: (duration, opacity) ->
# Create a FlipX action to flip or unflip the target.
# @param [Boolean] flip
# @return [FlipX]
@flipX: (flip) ->
# Create a Flip X 3D action with duration.
# @param [Number] duration
# @return [FlipX3D]
@flipX3D: (duration) ->
# Create a FlipY action to flip or unflip the target.
# @param [Boolean] flip
# @return [FlipY]
@flipY: (flip) ->
# Create a flip Y 3d action with duration.
# @param [Number] duration
# @return [FlipY3D]
@flipY3D: (duration) ->
# creates the action with a set boundary.
# @param [Node] followedNode
# @param [Rect] rect
# @return [Follow|Null]
@follow: (followedNode, rect) ->
# A string tool to construct a string with format string.
# @return [String]
@formatStr: ->
# Generates texture's cache for texture tint
# @param [HTMLImageElement] texture
# @return [Array]
@generateTextureCacheForColor: (texture) ->
# Generate tinted texture with lighter.
# @param [HTMLImageElement] texture
# @param [Array] tintedImgCache
# @param [Color] color
# @param [Rect] rect
# @param [HTMLCanvasElement] renderCanvas
# @return [HTMLCanvasElement]
@generateTintImage: (texture, tintedImgCache, color, rect, renderCanvas) ->
# Tint a texture using the "multiply" operation
# @param [HTMLImageElement] image
# @param [Color] color
# @param [Rect] rect
# @param [HTMLCanvasElement] renderCanvas
# @return [HTMLCanvasElement]
@generateTintImageWithMultiply: (image, color, rect, renderCanvas) ->
# returns a point from the array
# @param [Array] controlPoints
# @param [Number] pos
# @return [Array]
@getControlPointAt: (controlPoints, pos) ->
# get image format by image data
# @param [Array] imgData
# @return [Number]
@getImageFormatByData: (imgData) ->
# If the texture is not already bound, it binds it.
# @param [Texture2D] textureId
@glBindTexture2D: (textureId) ->
# If the texture is not already bound to a given unit, it binds it.
# @param [Number] textureUnit
# @param [Texture2D] textureId
@glBindTexture2DN: (textureUnit, textureId) ->
# If the vertex array is not already bound, it binds it.
# @param [Number] vaoId
@glBindVAO: (vaoId) ->
# Uses a blending function in case it not already used.
# @param [Number] sfactor
# @param [Number] dfactor
@glBlendFunc: (sfactor, dfactor) ->
# @param [Number] sfactor
# @param [Number] dfactor
@glBlendFuncForParticle: (sfactor, dfactor) ->
# Resets the blending mode back to the cached state in case you used glBlendFuncSeparate() or glBlendEquation().
@glBlendResetToCache: ->
# Deletes the GL program.
# @param [WebGLProgram] program
@glDeleteProgram: (program) ->
# It will delete a given texture.
# @param [WebGLTexture] textureId
@glDeleteTexture: (textureId) ->
# It will delete a given texture.
# @param [Number] textureUnit
# @param [WebGLTexture] textureId
@glDeleteTextureN: (textureUnit, textureId) ->
# It will enable / disable the server side GL states.
# @param [Number] flags
@glEnable: (flags) ->
# Will enable the vertex attribs that are passed as flags.
# @param [VERTEX_ATTRIB_FLAG_POSITION | cc.VERTEX_ATTRIB_FLAG_COLOR | cc.VERTEX_ATTRIB_FLAG_TEX_OORDS] flags
@glEnableVertexAttribs: (flags) ->
# Invalidates the GL state cache.
@glInvalidateStateCache: ->
# Convert a kmMat4 object to an affine transform object
# @param [kmMat4] mat
# @param [AffineTransform] trans
@GLToCGAffine: (mat, trans) ->
# Uses the GL program in case program is different than the current one.
# @param [WebGLProgram] program
@glUseProgram: (program) ->
# creates the action with size and duration
# @param [Number] duration
# @param [Size] gridSize
# @return [Grid3DAction]
@grid3DAction: (duration, gridSize) ->
# creates the action with size and duration
# @param [Number] duration
# @param [Size] gridSize
# @return [GridAction]
@gridAction: (duration, gridSize) ->
# Hash Element used for "selectors with interval"
# @param [Array] timers
# @param [Class] target
# @param [Number] timerIndex
# @param [Timer] currentTimer
# @param [Boolean] currentTimerSalvaged
# @param [Boolean] paused
# @param [Array] hh
@HashTimerEntry: (timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused, hh) ->
# ************************************************************************* Copyright (c) 2008-2010 <NAME> Copyright (c) 2011-2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc.
# @param value
# @param location
# @param hh
@HashUniformEntry: (value, location, hh) ->
# convert a string of color for style to Color.
# @param [String] hex
# @return [Color]
@hexToColor: (hex) ->
# Hide the node.
# @return [Hide]
@hide: ->
# IME Keyboard Notification Info structure
# @param [Rect] begin
# @param [Rect] end
# @param [Number] duration
@IMEKeyboardNotificationInfo: (begin, end, duration) ->
# Increments the GL Draws counts by one.
# @param [Number] addNumber
@incrementGLDraws: (addNumber) ->
# Another way to subclass: Using Google Closure.
# @param [Function] childCtor
# @param [Function] parentCtor
@inherits: (childCtor, parentCtor) ->
# Check the obj whether is array or not
# @param [*] obj
# @return [boolean]
@isArray: (obj) ->
# Check the url whether cross origin
# @param [String] url
# @return [boolean]
@isCrossOrigin: (url) ->
# Check the obj whether is function or not
# @param [*] obj
# @return [boolean]
@isFunction: (obj) ->
# Check the obj whether is number or not
# @param [*] obj
# @return [boolean]
@isNumber: (obj) ->
# Check the obj whether is object or not
# @param [*] obj
# @return [boolean]
@isObject: (obj) ->
# Check the obj whether is string or not
# @param [*] obj
# @return [boolean]
@isString: (obj) ->
# Check the obj whether is undefined or not
# @param [*] obj
# @return [boolean]
@isUndefined: (obj) ->
# Moves a cc.Node object simulating a parabolic jump movement by modifying it's position attribute.
# @param [Number] duration
# @param [Point|Number] position
# @param [Number] y
# @param [Number] height
# @param [Number] jumps
# @return [JumpBy]
@jumpBy: (duration, position, y, height, jumps) ->
# creates the action with the number of jumps, the sin amplitude, the grid size and the duration.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] numberOfJumps
# @param [Number] amplitude
# @return [JumpTiles3D]
@jumpTiles3D: (duration, gridSize, numberOfJumps, amplitude) ->
# Moves a cc.Node object to a parabolic position simulating a jump movement by modifying it's position attribute.
# @param [Number] duration
# @param [Point|Number] position
# @param [Number] y
# @param [Number] height
# @param [Number] jumps
# @return [JumpTo]
@jumpTo: (duration, position, y, height, jumps) ->
# A struture that represents an axis-aligned bounding box.
# @param min
# @param max
@kmAABB: (min, max) ->
# Assigns pIn to pOut, returns pOut.
# @param pOut
# @param pIn
@kmAABBAssign: (pOut, pIn) ->
# Returns KM_TRUE if point is in the specified AABB, returns KM_FALSE otherwise.
# @param pPoint
# @param pBox
@kmAABBContainsPoint: (pPoint, pBox) ->
# Scales pIn by s, stores the resulting AABB in pOut.
# @param pOut
# @param pIn
# @param s
@kmAABBScale: (pOut, pIn, s) ->
# A 4x4 matrix mat = | 0 4 8 12 | | 1 5 9 13 | | 2 6 10 14 | | 3 7 11 15 |
@kmMat4: ->
# Returns KM_TRUE if the 2 matrices are equal (approximately)
# @param pMat1
# @param pMat2
@kmMat4AreEqual: (pMat1, pMat2) ->
# Assigns the value of pIn to pOut
# @param pOut
# @param pIn
@kmMat4Assign: (pOut, pIn) ->
# Extract a 3x3 rotation matrix from the input 4x4 transformation.
# @param pOut
# @param pIn
@kmMat4ExtractRotation: (pOut, pIn) ->
# Fills a kmMat4 structure with the values from a 16 element array of floats
# @param pOut
# @param pMat
@kmMat4Fill: (pOut, pMat) ->
# Extract the forward vector from a 4x4 matrix.
# @param pOut
# @param pIn
@kmMat4GetForwardVec3: (pOut, pIn) ->
# Extract the right vector from a 4x4 matrix.
# @param pOut
# @param pIn
@kmMat4GetRightVec3: (pOut, pIn) ->
# Get the up vector from a matrix.
# @param pOut
# @param pIn
@kmMat4GetUpVec3: (pOut, pIn) ->
# Sets pOut to an identity matrix returns pOut
# @param pOut
@kmMat4Identity: (pOut) ->
# Calculates the inverse of pM and stores the result in pOut.
# @param pOut
# @param pM
@kmMat4Inverse: (pOut, pM) ->
# Returns KM_TRUE if pIn is an identity matrix KM_FALSE otherwise
# @param pIn
@kmMat4IsIdentity: (pIn) ->
# Builds a translation matrix in the same way as gluLookAt() the resulting matrix is stored in pOut.
# @param pOut
# @param pEye
# @param pCenter
# @param pUp
@kmMat4LookAt: (pOut, pEye, pCenter, pUp) ->
# Multiplies pM1 with pM2, stores the result in pOut, returns pOut
# @param pOut
# @param pM1
# @param pM2
@kmMat4Multiply: (pOut, pM1, pM2) ->
# Creates an orthographic projection matrix like glOrtho
# @param pOut
# @param left
# @param right
# @param bottom
# @param top
# @param nearVal
# @param farVal
@kmMat4OrthographicProjection: (pOut, left, right, bottom, top, nearVal, farVal) ->
# Creates a perspective projection matrix in the same way as gluPerspective
# @param pOut
# @param fovY
# @param aspect
# @param zNear
# @param zFar
@kmMat4PerspectiveProjection: (pOut, fovY, aspect, zNear, zFar) ->
# Build a rotation matrix from an axis and an angle.
# @param pOut
# @param axis
# @param radians
@kmMat4RotationAxisAngle: (pOut, axis, radians) ->
# Builds a rotation matrix from pitch, yaw and roll.
# @param pOut
# @param pitch
# @param yaw
# @param roll
@kmMat4RotationPitchYawRoll: (pOut, pitch, yaw, roll) ->
# Converts a quaternion to a rotation matrix, the result is stored in pOut, returns pOut
# @param pOut
# @param pQ
@kmMat4RotationQuaternion: (pOut, pQ) ->
# Take the rotation from a 4x4 transformation matrix, and return it as an axis and an angle (in radians) returns the output axis.
# @param pAxis
# @param radians
# @param pIn
@kmMat4RotationToAxisAngle: (pAxis, radians, pIn) ->
# Build a 4x4 OpenGL transformation matrix using a 3x3 rotation matrix, and a 3d vector representing a translation.
# @param pOut
# @param rotation
# @param translation
@kmMat4RotationTranslation: (pOut, rotation, translation) ->
# Builds an X-axis rotation matrix and stores it in pOut, returns pOut
# @param pOut
# @param radians
@kmMat4RotationX: (pOut, radians) ->
# Builds a rotation matrix using the rotation around the Y-axis The result is stored in pOut, pOut is returned.
# @param pOut
# @param radians
@kmMat4RotationY: (pOut, radians) ->
# Builds a rotation matrix around the Z-axis.
# @param pOut
# @param radians
@kmMat4RotationZ: (pOut, radians) ->
# Builds a scaling matrix
# @param pOut
# @param x
# @param y
# @param z
@kmMat4Scaling: (pOut, x, y, z) ->
# Builds a translation matrix.
# @param pOut
# @param x
# @param y
# @param z
@kmMat4Translation: (pOut, x, y, z) ->
# Sets pOut to the transpose of pIn, returns pOut
# @param pOut
# @param pIn
@kmMat4Transpose: (pOut, pIn) ->
# Returns POINT_INFRONT_OF_PLANE if pP is infront of pIn.
# @param pIn
# @param pP
@kmPlaneClassifyPoint: (pIn, pP) ->
# Creates a plane from 3 points.
# @param pOut
# @param p1
# @param p2
# @param p3
@kmPlaneFromPoints: (pOut, p1, p2, p3) ->
# Adapted from the OGRE engine! Gets the shortest arc quaternion to rotate this vector to the destination vector.
# @param pOut
# @param vec1
# @param vec2
# @param fallback
@kmQuaternionRotationBetweenVec3: (pOut, vec1, vec2, fallback) ->
# Returns the square of s (e.g.
# @param [Number] s
@kmSQR: (s) ->
# creates a lens 3d action with center position, radius
# @param [Number] duration
# @param [Size] gridSize
# @param [Point] position
# @param [Number] radius
# @return [Lens3D]
@lens3D: (duration, gridSize, position, radius) ->
# Linear interpolation between 2 numbers, the ratio sets how much it is biased to each end
# @param [Number] a
# @param [Number] b
# @param [Number] r
@lerp: (a, b, r) ->
# creates the action with amplitude, a grid and duration
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] waves
# @param [Number] amplitude
# @return [Liquid]
@liquid: (duration, gridSize, waves, amplitude) ->
# Create the action.
# @param [Number] duration
# @param [Point|Number] deltaPos
# @param [Number] deltaY
# @return [MoveBy]
@moveBy: (duration, deltaPos, deltaY) ->
# Create new action.
# @param [Number] duration
# @param [Point] position
# @param [Number] y
# @return [MoveBy]
@moveTo: (duration, position, y) ->
# @param [Number] x
# @return [Number]
@NextPOT: (x) ->
# Helpful macro that setups the GL server state, the correct GL program and sets the Model View Projection matrix
# @param [Node] node
@nodeDrawSetup: (node) ->
# Helper function that creates a cc.Point.
# @param [Number|cc.Point] x
# @param [Number] y
# @return [Point]
@p: (x, y) ->
# Calculates sum of two points.
# @param [Point] v1
# @param [Point] v2
# @return [Point]
@pAdd: (v1, v2) ->
# adds one point to another (inplace)
# @param [Point] v1
# @param [point] v2
@pAddIn: (v1, v2) ->
# create PageTurn3D action
# @param [Number] duration
# @param [Size] gridSize
# @return [PageTurn3D]
@pageTurn3D: (duration, gridSize) ->
# @param [Point] a
# @param [Point] b
# @return [Number]
@pAngle: (a, b) ->
# @param [Point] a
# @param [Point] b
# @return [Number]
@pAngleSigned: (a, b) ->
# Clamp a point between from and to.
# @param [Point] p
# @param [Number] min_inclusive
# @param [Number] max_inclusive
# @return [Point]
@pClamp: (p, min_inclusive, max_inclusive) ->
# Multiplies a nd b components, a.x*b.x, a.y*b.y
# @param [Point] a
# @param [Point] b
# @return [Point]
@pCompMult: (a, b) ->
# Run a math operation function on each point component Math.abs, Math.fllor, Math.ceil, Math.round.
# @param [Point] p
# @param [Function] opFunc
# @return [Point]
@pCompOp: (p, opFunc) ->
# Calculates cross product of two points.
# @param [Point] v1
# @param [Point] v2
# @return [Number]
@pCross: (v1, v2) ->
# Calculates the distance between two points
# @param [Point] v1
# @param [Point] v2
# @return [Number]
@pDistance: (v1, v2) ->
# Calculates the square distance between two points (not calling sqrt() )
# @param [Point] point1
# @param [Point] point2
# @return [Number]
@pDistanceSQ: (point1, point2) ->
# Calculates dot product of two points.
# @param [Point] v1
# @param [Point] v2
# @return [Number]
@pDot: (v1, v2) ->
# Converts radians to a normalized vector.
# @param [Number] a
# @return [Point]
@pForAngle: (a) ->
# Quickly convert cc.Size to a cc.Point
# @param [Size] s
# @return [Point]
@pFromSize: (s) ->
# @param [Point] a
# @param [Point] b
# @param [Number] variance
# @return [Boolean]
@pFuzzyEqual: (a, b, variance) ->
# copies the position of one point to another
# @param [Point] v1
# @param [Point] v2
@pIn: (v1, v2) ->
# ccpIntersectPoint return the intersection point of line A-B, C-D
# @param [Point] A
# @param [Point] B
# @param [Point] C
# @param [Point] D
# @return [Point]
@pIntersectPoint: (A, B, C, D) ->
# Creates a Place action with a position.
# @param [Point|Number] pos
# @param [Number] y
# @return [Place]
@place: (pos, y) ->
# Calculates distance between point an origin
# @param [Point] v
# @return [Number]
@pLength: (v) ->
# Calculates the square length of a cc.Point (not calling sqrt() )
# @param [Point] v
# @return [Number]
@pLengthSQ: (v) ->
# Linear Interpolation between two points a and b alpha == 0 ? a alpha == 1 ? b otherwise a value between a.
# @param [Point] a
# @param [Point] b
# @param [Number] alpha
# @return [pAdd]
@pLerp: (a, b, alpha) ->
# A general line-line intersection test indicating successful intersection of a line note that to truly test intersection for segments we have to make sure that s & t lie within [0.
# @param [Point] A
# @param [Point] B
# @param [Point] C
# @param [Point] D
# @param [Point] retP
# @return [Boolean]
@pLineIntersect: (A, B, C, D, retP) ->
# Calculates midpoint between two points.
# @param [Point] v1
# @param [Point] v2
# @return [pMult]
@pMidpoint: (v1, v2) ->
# Returns point multiplied by given factor.
# @param [Point] point
# @param [Number] floatVar
# @return [Point]
@pMult: (point, floatVar) ->
# multiplies the point with the given factor (inplace)
# @param [Point] point
# @param [Number] floatVar
@pMultIn: (point, floatVar) ->
# Returns opposite of point.
# @param [Point] point
# @return [Point]
@pNeg: (point) ->
# Returns point multiplied to a length of 1.
# @param [Point] v
# @return [Point]
@pNormalize: (v) ->
# normalizes the point (inplace)
# @param
@pNormalizeIn: ->
# Apply the affine transformation on a point.
# @param [Point] point
# @param [AffineTransform] t
# @return [Point]
@pointApplyAffineTransform: (point, t) ->
# Check whether a point's value equals to another
# @param [Point] point1
# @param [Point] point2
# @return [Boolean]
@pointEqualToPoint: (point1, point2) ->
# Converts a Point in pixels to points
# @param [Rect] pixels
# @return [Point]
@pointPixelsToPoints: (pixels) ->
# Converts a Point in points to pixels
# @param [Point] points
# @return [Point]
@pointPointsToPixels: (points) ->
# Calculates perpendicular of v, rotated 90 degrees counter-clockwise -- cross(v, perp(v)) = 0
# @param [Point] point
# @return [Point]
@pPerp: (point) ->
# Calculates the projection of v1 over v2.
# @param [Point] v1
# @param [Point] v2
# @return [pMult]
@pProject: (v1, v2) ->
# Creates and initializes the action with a duration, a "from" percentage and a "to" percentage
# @param [Number] duration
# @param [Number] fromPercentage
# @param [Number] toPercentage
# @return [ProgressFromTo]
@progressFromTo: (duration, fromPercentage, toPercentage) ->
# Creates and initializes with a duration and a percent
# @param [Number] duration
# @param [Number] percent
# @return [ProgressTo]
@progressTo: (duration, percent) ->
# Rotates two points.
# @param [Point] v1
# @param [Point] v2
# @return [Point]
@pRotate: (v1, v2) ->
# Rotates a point counter clockwise by the angle around a pivot
# @param [Point] v
# @param [Point] pivot
# @param [Number] angle
# @return [Point]
@pRotateByAngle: (v, pivot, angle) ->
# Calculates perpendicular of v, rotated 90 degrees clockwise -- cross(v, rperp(v))
# @param [Point] point
# @return [Point]
@pRPerp: (point) ->
# check to see if both points are equal
# @param [Point] A
# @param [Point] B
# @return [Boolean]
@pSameAs: (A, B) ->
# ccpSegmentIntersect return YES if Segment A-B intersects with segment C-D.
# @param [Point] A
# @param [Point] B
# @param [Point] C
# @param [Point] D
# @return [Boolean]
@pSegmentIntersect: (A, B, C, D) ->
# Calculates difference of two points.
# @param [Point] v1
# @param [Point] v2
# @return [Point]
@pSub: (v1, v2) ->
# subtracts one point from another (inplace)
# @param [Point] v1
# @param
@pSubIn: (v1, ) ->
# Converts a vector to radians.
# @param [Point] v
# @return [Number]
@pToAngle: (v) ->
# Unrotates two points.
# @param [Point] v1
# @param [Point] v2
# @return [Point]
@pUnrotate: (v1, v2) ->
# sets the position of the point to 0
# @param [Point] v
@pZeroIn: (v) ->
# converts radians to degrees
# @param [Number] angle
# @return [Number]
@radiansToDegrees: (angle) ->
# converts radians to degrees
# @param [Number] angle
# @return [Number]
@radiansToDegress: (angle) ->
# get a random number from 0 to 0xffffff
# @return [number]
@rand: ->
# returns a random float between 0 and 1
# @return [Number]
@random0To1: ->
# returns a random float between -1 and 1
# @return [Number]
@randomMinus1To1: ->
# Helper function that creates a cc.Rect.
# @param [Number|cc.Rect] x
# @param [Number] y
# @param [Number] w
# @param [Number] h
# @return [Rect]
@rect: (x, y, w, h) ->
# Apply the affine transformation on a rect.
# @param [Rect] rect
# @param [AffineTransform] anAffineTransform
# @return [Rect]
@rectApplyAffineTransform: (rect, anAffineTransform) ->
# Check whether a rect contains a point
# @param [Rect] rect
# @param [Point] point
# @return [Boolean]
@rectContainsPoint: (rect, point) ->
# Check whether the rect1 contains rect2
# @param [Rect] rect1
# @param [Rect] rect2
# @return [Boolean]
@rectContainsRect: (rect1, rect2) ->
# Check whether a rect's value equals to another
# @param [Rect] rect1
# @param [Rect] rect2
# @return [Boolean]
@rectEqualToRect: (rect1, rect2) ->
# Returns the rightmost x-value of a rect
# @param [Rect] rect
# @return [Number]
@rectGetMaxX: (rect) ->
# Return the topmost y-value of a rect
# @param [Rect] rect
# @return [Number]
@rectGetMaxY: (rect) ->
# Return the midpoint x-value of a rect
# @param [Rect] rect
# @return [Number]
@rectGetMidX: (rect) ->
# Return the midpoint y-value of `rect'
# @param [Rect] rect
# @return [Number]
@rectGetMidY: (rect) ->
# Returns the leftmost x-value of a rect
# @param [Rect] rect
# @return [Number]
@rectGetMinX: (rect) ->
# Return the bottommost y-value of a rect
# @param [Rect] rect
# @return [Number]
@rectGetMinY: (rect) ->
# Returns the overlapping portion of 2 rectangles
# @param [Rect] rectA
# @param [Rect] rectB
# @return [Rect]
@rectIntersection: (rectA, rectB) ->
# Check whether a rect intersect with another
# @param [Rect] rectA
# @param [Rect] rectB
# @return [Boolean]
@rectIntersectsRect: (rectA, rectB) ->
# Check whether a rect overlaps another
# @param [Rect] rectA
# @param [Rect] rectB
# @return [Boolean]
@rectOverlapsRect: (rectA, rectB) ->
# Converts a rect in pixels to points
# @param [Rect] pixel
# @return [Rect]
@rectPixelsToPoints: (pixel) ->
# Converts a rect in points to pixels
# @param [Rect] point
# @return [Rect]
@rectPointsToPixels: (point) ->
# Returns the smallest rectangle that contains the two source rectangles.
# @param [Rect] rectA
# @param [Rect] rectB
# @return [Rect]
@rectUnion: (rectA, rectB) ->
# Create a RemoveSelf object with a flag indicate whether the target should be cleaned up while removing.
# @param [Boolean] isNeedCleanUp
# @return [RemoveSelf]
@removeSelf: (isNeedCleanUp) ->
# Creates a Repeat action.
# @param [FiniteTimeAction] action
# @param [Number] times
# @return [Repeat]
@repeat: (action, times) ->
# Create a acton which repeat forever
# @param [FiniteTimeAction] action
# @return [RepeatForever]
@repeatForever: (action) ->
# creates an action with the number of times that the current grid will be reused
# @param [Number] times
# @return [ReuseGrid]
@reuseGrid: (times) ->
# returns a new copy of the array reversed.
# @param controlPoints
# @return [Array]
@reverseControlPoints: (controlPoints) ->
# reverse the current control point array inline, without generating a new one
# @param controlPoints
@reverseControlPointsInline: (controlPoints) ->
# Executes an action in reverse order, from time=duration to time=0.
# @param [FiniteTimeAction] action
# @return [ReverseTime]
@reverseTime: (action) ->
# creates a ripple 3d action with radius, number of waves, amplitude
# @param [Number] duration
# @param [Size] gridSize
# @param [Point] position
# @param [Number] radius
# @param [Number] waves
# @param [Number] amplitude
# @return [Ripple3D]
@ripple3D: (duration, gridSize, position, radius, waves, amplitude) ->
# Rotates a cc.Node object clockwise a number of degrees by modifying it's rotation attribute.
# @param [Number] duration
# @param [Number] deltaAngleX
# @param [Number] deltaAngleY
# @return [RotateBy]
@rotateBy: (duration, deltaAngleX, deltaAngleY) ->
# Creates a RotateTo action with separate rotation angles.
# @param [Number] duration
# @param [Number] deltaAngleX
# @param [Number] deltaAngleY
# @return [RotateTo]
@rotateTo: (duration, deltaAngleX, deltaAngleY) ->
# Scales a cc.Node object a zoom factor by modifying it's scale attribute.
# @param [Number] duration
# @param [Number] sx
# @param [Number|Null] sy
# @return [ScaleBy]
@scaleBy: (duration, sx, sy) ->
# Scales a cc.Node object to a zoom factor by modifying it's scale attribute.
# @param [Number] duration
# @param [Number] sx
# @param [Number] sy
# @return [ScaleTo]
@scaleTo: (duration, sx, sy) ->
# helper constructor to create an array of sequenceable actions
# @param [Array|cc.FiniteTimeAction] tempArray
# @return [Sequence]
@sequence: (tempArray) ->
# @param [Number] sfactor
# @param [Number] dfactor
@setBlending: (sfactor, dfactor) ->
# Sets the shader program for this node Since v2.0, each rendering node must set its shader program.
# @param [Node] node
# @param [GLProgram] program
@setProgram: (node, program) ->
# sets the projection matrix as dirty
@setProjectionMatrixDirty: ->
# creates the action with a range, shake Z vertices, a grid and duration
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] range
# @param [Boolean] shakeZ
# @return [Shaky3D]
@shaky3D: (duration, gridSize, range, shakeZ) ->
# Creates the action with a range, whether or not to shake Z vertices, a grid size, and duration.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] range
# @param [Boolean] shakeZ
# @return [ShakyTiles3D]
@shakyTiles3D: (duration, gridSize, range, shakeZ) ->
# Creates the action with a range, whether of not to shatter Z vertices, a grid size and duration.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] range
# @param [Boolean] shatterZ
# @return [ShatteredTiles3D]
@shatteredTiles3D: (duration, gridSize, range, shatterZ) ->
# Show the Node.
# @return [Show]
@show: ->
# Creates the action with a random seed, the grid size and the duration.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] seed
# @return [ShuffleTiles]
@shuffleTiles: (duration, gridSize, seed) ->
# Helper function that creates a cc.Size.
# @param [Number|cc.Size] w
# @param [Number] h
# @return [Size]
@size: (w, h) ->
# Apply the affine transformation on a size.
# @param [Size] size
# @param [AffineTransform] t
# @return [Size]
@sizeApplyAffineTransform: (size, t) ->
# Check whether a point's value equals to another
# @param [Size] size1
# @param [Size] size2
# @return [Boolean]
@sizeEqualToSize: (size1, size2) ->
# Converts a size in pixels to points
# @param [Size] sizeInPixels
# @return [Size]
@sizePixelsToPoints: (sizeInPixels) ->
# Converts a Size in points to pixels
# @param [Size] sizeInPoints
# @return [Size]
@sizePointsToPixels: (sizeInPoints) ->
# Skews a cc.Node object by skewX and skewY degrees.
# @param [Number] t
# @param [Number] sx
# @param [Number] sy
# @return [SkewBy]
@skewBy: (t, sx, sy) ->
# Create new action.
# @param [Number] t
# @param [Number] sx
# @param [Number] sy
# @return [SkewTo]
@skewTo: (t, sx, sy) ->
# Create a spawn action which runs several actions in parallel.
# @param [Array|cc.FiniteTimeAction] tempArray
# @return [FiniteTimeAction]
@spawn: (tempArray) ->
# creates the speed action.
# @param [ActionInterval] action
# @param [Number] speed
# @return [Speed]
@speed: (action, speed) ->
# creates the action with the number of columns to split and the duration.
# @param [Number] duration
# @param [Number] cols
# @return [SplitCols]
@splitCols: (duration, cols) ->
# creates the action with the number of rows to split and the duration.
# @param [Number] duration
# @param [Number] rows
# @return [SplitRows]
@splitRows: (duration, rows) ->
# Allocates and initializes the action
# @return [StopGrid]
@stopGrid: ->
# simple macro that swaps 2 variables modified from c++ macro, you need to pass in the x and y variables names in string, and then a reference to the whole object as third variable
# @param [String] x
# @param [String] y
# @param [Object] ref
@swap: (x, y, ref) ->
# Create an action with the specified action and forced target
# @param [Node] target
# @param [FiniteTimeAction] action
# @return [TargetedAction]
@targetedAction: (target, action) ->
# Helper macro that creates an Tex2F type: A texcoord composed of 2 floats: u, y
# @param [Number] u
# @param [Number] v
# @return [Tex2F]
@tex2: (u, v) ->
# releases the memory used for the image
# @param [ImageTGA] psInfo
@tgaDestroy: (psInfo) ->
# ImageTGA Flip
# @param [ImageTGA] psInfo
@tgaFlipImage: (psInfo) ->
# load the image header field from stream.
# @param [Array] buffer
# @param [Number] bufSize
# @param [ImageTGA] psInfo
# @return [Boolean]
@tgaLoadHeader: (buffer, bufSize, psInfo) ->
# loads the image pixels.
# @param [Array] buffer
# @param [Number] bufSize
# @param [ImageTGA] psInfo
# @return [Boolean]
@tgaLoadImageData: (buffer, bufSize, psInfo) ->
# Load RLE image data
# @param buffer
# @param bufSize
# @param psInfo
# @return [boolean]
@tgaLoadRLEImageData: (buffer, bufSize, psInfo) ->
# converts RGB to grayscale
# @param [ImageTGA] psInfo
@tgaRGBtogreyscale: (psInfo) ->
# Creates the action with duration and grid size
# @param [Number] duration
# @param [Size] gridSize
# @return [TiledGrid3DAction]
@tiledGrid3DAction: (duration, gridSize) ->
# Tints a cc.Node that implements the cc.NodeRGB protocol from current tint to a custom one.
# @param [Number] duration
# @param [Number] deltaRed
# @param [Number] deltaGreen
# @param [Number] deltaBlue
# @return [TintBy]
@tintBy: (duration, deltaRed, deltaGreen, deltaBlue) ->
# Tints a cc.Node that implements the cc.NodeRGB protocol from current tint to a custom one.
# @param [Number] duration
# @param [Number] red
# @param [Number] green
# @param [Number] blue
# @return [TintTo]
@tintTo: (duration, red, green, blue) ->
# Toggles the visibility of a node.
# @return [ToggleVisibility]
@toggleVisibility: ->
# Creates the action with a random seed, the grid size and the duration.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number|Null] seed
# @return [TurnOffTiles]
@turnOffTiles: (duration, gridSize, seed) ->
# creates the action with center position, number of twirls, amplitude, a grid size and duration
# @param [Number] duration
# @param [Size] gridSize
# @param [Point] position
# @param [Number] twirls
# @param [Number] amplitude
# @return [Twirl]
@twirl: (duration, gridSize, position, twirls, amplitude) ->
# Code copied & pasted from SpacePatrol game https://github.com/slembcke/SpacePatrol Renamed and added some changes for cocos2d
@v2fzero: ->
# Helper macro that creates an Vertex2F type composed of 2 floats: x, y
# @param [Number] x
# @param [Number] y
# @return [Vertex2F]
@vertex2: (x, y) ->
# Helper macro that creates an Vertex3F type composed of 3 floats: x, y, z
# @param [Number] x
# @param [Number] y
# @param [Number] z
# @return [Vertex3F]
@vertex3: (x, y, z) ->
# returns whether or not the line intersects
# @param [Number] Ax
# @param [Number] Ay
# @param [Number] Bx
# @param [Number] By
# @param [Number] Cx
# @param [Number] Cy
# @param [Number] Dx
# @param [Number] Dy
# @return [Object]
@vertexLineIntersect: (Ax, Ay, Bx, By, Cx, Cy, Dx, Dy) ->
# converts a line to a polygon
# @param [Float32Array] points
# @param [Number] stroke
# @param [Float32Array] vertices
# @param [Number] offset
# @param [Number] nuPoints
@vertexLineToPolygon: (points, stroke, vertices, offset, nuPoints) ->
# returns wheter or not polygon defined by vertex list is clockwise
# @param [Array] verts
# @return [Boolean]
@vertexListIsClockwise: (verts) ->
# initializes the action with amplitude, horizontal sin, vertical sin, a grid and duration
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] waves
# @param [Number] amplitude
# @param [Boolean] horizontal
# @param [Boolean] vertical
# @return [Waves]
@waves: (duration, gridSize, waves, amplitude, horizontal, vertical) ->
# Create a wave 3d action with duration, grid size, waves and amplitude.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] waves
# @param [Number] amplitude
@waves3D: (duration, gridSize, waves, amplitude) ->
# creates the action with a number of waves, the waves amplitude, the grid size and the duration.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] waves
# @param [Number] amplitude
# @return [WavesTiles3D]
@wavesTiles3D: (duration, gridSize, waves, amplitude) ->
# cc.Acceleration
# @param [Number] x
# @param [Number] y
# @param [Number] z
# @param [Number] timestamp
# @return [Acceleration]
@Acceleration: (x, y, z, timestamp) ->
# Base class for cc.Action objects.
# @return [Action]
@Action: ->
# Base class for Easing actions
# @param [ActionInterval] action
# @return [ActionEase]
@ActionEase: (action) ->
# Instant actions are immediate actions.
# @return [ActionInstant]
@ActionInstant: ->
# An interval action is an action that takes place within a certain period of time.
# @param [Number] d
# @return [ActionInterval]
@ActionInterval: (d) ->
# cc.ActionManager is a class that can manage actions.
# @return [ActionManager]
@ActionManager: ->
# cc.ActionTween cc.ActionTween is an action that lets you update any property of an object.
# @param [Number] duration
# @param [String] key
# @param [Number] from
# @param [Number] to
# @return [ActionTween]
@ActionTween: (duration, key, from, to) ->
# @return [ActionTweenDelegate]
@ActionTweenDelegate: ->
# cc.AffineTransform
# @param [Number] a
# @param [Number] b
# @param [Number] c
# @param [Number] d
# @param [Number] tx
# @param [Number] ty
# @return [AffineTransform]
@AffineTransform: (a, b, c, d, tx, ty) ->
# Animates a sprite given the name of an Animation
# @param [Animation] animation
# @return [Animate]
@Animate: (animation) ->
# A cc.Animation object is used to perform animations on the cc.Sprite objects.
# @param [Array] frames
# @param [Number] delay
# @param [Number] loops
# @return [Animation]
@Animation: (frames, delay, loops) ->
# cc.animationCache is a singleton object that manages the Animations.
# @return [animationCache]
@animationCache: ->
# cc.AnimationFrame A frame of the animation.
# @param spriteFrame
# @param delayUnits
# @param userInfo
# @return [AnimationFrame]
@AnimationFrame: (spriteFrame, delayUnits, userInfo) ->
# Array for object sorting utils
# @return [ArrayForObjectSorting]
@ArrayForObjectSorting: ->
# @return [async]
@async: ->
# Async Pool class, a helper of cc.async
# @param [Object|Array] srcObj
# @param [Number] limit
# @param [function] iterator
# @param [function] onEnd
# @param [object] target
# @return [AsyncPool]
@AsyncPool: (srcObj, limit, iterator, onEnd, target) ->
# cc.AtlasNode is a subclass of cc.Node, it knows how to render a TextureAtlas object.
# @param [String] tile
# @param [Number] tileWidth
# @param [Number] tileHeight
# @param [Number] itemsToRender
# @return [AtlasNode]
@AtlasNode: (tile, tileWidth, tileHeight, itemsToRender) ->
# cc.audioEngine is the singleton object, it provide simple audio APIs.
# @return [audioEngine]
@audioEngine: ->
# An action that moves the target with a cubic Bezier curve by a certain distance.
# @param [Number] t
# @param [Array] c
# @return [BezierBy]
@BezierBy: (t, c) ->
# An action that moves the target with a cubic Bezier curve to a destination point.
# @param [Number] t
# @param [Array] c
# @return [BezierTo]
@BezierTo: (t, c) ->
# Binary Stream Reader
# @param binaryData
# @return [BinaryStreamReader]
@BinaryStreamReader: (binaryData) ->
# Blinks a cc.Node object by modifying it's visible attribute
# @param [Number] duration
# @param [Number] blinks
# @return [Blink]
@Blink: (duration, blinks) ->
# Calls a 'callback'.
# @param [function] selector
# @param [object|null] selectorTarget
# @param [*|null] data
# @return [CallFunc]
@CallFunc: (selector, selectorTarget, data) ->
# Cardinal Spline path.
# @param [Number] duration
# @param [Array] points
# @param [Number] tension
# @return [CardinalSplineBy]
@CardinalSplineBy: (duration, points, tension) ->
# Cardinal Spline path.
# @param [Number] duration
# @param [Array] points
# @param [Number] tension
# @return [CardinalSplineTo]
@CardinalSplineTo: (duration, points, tension) ->
# An action that moves the target with a CatmullRom curve by a certain distance.
# @param [Number] dt
# @param [Array] points
# @return [CatmullRomBy]
@CatmullRomBy: (dt, points) ->
# An action that moves the target with a CatmullRom curve to a destination point.
# @param [Number] dt
# @param [Array] points
# @return [CatmullRomTo]
@CatmullRomTo: (dt, points) ->
# The base Class implementation (does nothing)
# @return [Class]
@Class: ->
# cc.ClippingNode is a subclass of cc.Node.
# @param [Node] stencil
# @return [ClippingNode]
@ClippingNode: (stencil) ->
# cc.Color
# @param [Number] r
# @param [Number] g
# @param [Number] b
# @param [Number] a
# @return [Color]
@Color: (r, g, b, a) ->
# The base class of component in CocoStudio
# @return [Component]
@Component: ->
# The component container for Cocostudio, it has some components.
# @return [ComponentContainer]
@ComponentContainer: ->
# cc.configuration is a singleton object which contains some openGL variables
# @return [configuration]
@configuration: ->
# cc.ContainerStrategy class is the root strategy class of container's scale strategy, it controls the behavior of how to scale the cc.container and cc._canvas object
# @return [ContainerStrategy]
@ContainerStrategy: ->
# cc.ContentStrategy class is the root strategy class of content's scale strategy, it controls the behavior of how to scale the scene and setup the viewport for the game
# @return [ContentStrategy]
@ContentStrategy: ->
# CCControl is inspired by the UIControl API class from the UIKit library of CocoaTouch.
# @return [Control]
@Control: ->
# CCControlButton: Button control for Cocos2D.
# @return [ControlButton]
@ControlButton: ->
# ControlColourPicker: color picker ui component.
# @return [ControlColourPicker]
@ControlColourPicker: ->
# ControlHuePicker: HUE picker ui component.
# @return [ControlHuePicker]
@ControlHuePicker: ->
# CCControlPotentiometer: Potentiometer control for Cocos2D.
# @return [ControlPotentiometer]
@ControlPotentiometer: ->
# ControlSaturationBrightnessPicker: Saturation brightness picker ui component.
# @return [ControlSaturationBrightnessPicker]
@ControlSaturationBrightnessPicker: ->
# ControlSlider: Slider ui component.
# @return [ControlSlider]
@ControlSlider: ->
# ControlStepper: Stepper ui component.
# @return [ControlStepper]
@ControlStepper: ->
# CCControlSwitch: Switch control ui component
# @return [ControlSwitch]
@ControlSwitch: ->
# ControlSwitchSprite: Sprite switch control ui component
# @return [ControlSwitchSprite]
@ControlSwitchSprite: ->
# Delays the action a certain amount of seconds
# @return [DelayTime]
@DelayTime: ->
# ATTENTION: USE cc.director INSTEAD OF cc.Director.
# @return [Director]
@Director: ->
# CCDrawNode Node that draws dots, segments and polygons.
# @return [DrawNode]
@DrawNode: ->
# cc.EaseBackIn action.
# @return [EaseBackIn]
@EaseBackIn: ->
# cc.EaseBackInOut action.
# @return [EaseBackInOut]
@EaseBackInOut: ->
# cc.EaseBackOut action.
# @return [EaseBackOut]
@EaseBackOut: ->
# cc.EaseBezierAction action.
# @param [Action] action
# @return [EaseBezierAction]
@EaseBezierAction: (action) ->
# cc.EaseBounce abstract class.
# @return [EaseBounce]
@EaseBounce: ->
# cc.EaseBounceIn action.
# @return [EaseBounceIn]
@EaseBounceIn: ->
# cc.EaseBounceInOut action.
# @return [EaseBounceInOut]
@EaseBounceInOut: ->
# cc.EaseBounceOut action.
# @return [EaseBounceOut]
@EaseBounceOut: ->
# cc.EaseCircleActionIn action.
# @return [EaseCircleActionIn]
@EaseCircleActionIn: ->
# cc.EaseCircleActionInOut action.
# @return [EaseCircleActionInOut]
@EaseCircleActionInOut: ->
# cc.EaseCircleActionOut action.
# @return [EaseCircleActionOut]
@EaseCircleActionOut: ->
# cc.EaseCubicActionIn action.
# @return [EaseCubicActionIn]
@EaseCubicActionIn: ->
# cc.EaseCubicActionInOut action.
# @return [EaseCubicActionInOut]
@EaseCubicActionInOut: ->
# cc.EaseCubicActionOut action.
# @return [EaseCubicActionOut]
@EaseCubicActionOut: ->
# Ease Elastic abstract class.
# @param [ActionInterval] action
# @param [Number] period
# @return [EaseElastic]
@EaseElastic: (action, period) ->
# Ease Elastic In action.
# @return [EaseElasticIn]
@EaseElasticIn: ->
# Ease Elastic InOut action.
# @return [EaseElasticInOut]
@EaseElasticInOut: ->
# Ease Elastic Out action.
# @return [EaseElasticOut]
@EaseElasticOut: ->
# cc.Ease Exponential In.
# @return [EaseExponentialIn]
@EaseExponentialIn: ->
# Ease Exponential InOut.
# @return [EaseExponentialInOut]
@EaseExponentialInOut: ->
# Ease Exponential Out.
# @return [EaseExponentialOut]
@EaseExponentialOut: ->
# cc.EaseIn action with a rate.
# @return [EaseIn]
@EaseIn: ->
# cc.EaseInOut action with a rate.
# @return [EaseInOut]
@EaseInOut: ->
# cc.EaseOut action with a rate.
# @return [EaseOut]
@EaseOut: ->
# cc.EaseQuadraticActionIn action.
# @return [EaseQuadraticActionIn]
@EaseQuadraticActionIn: ->
# cc.EaseQuadraticActionInOut action.
# @return [EaseQuadraticActionInOut]
@EaseQuadraticActionInOut: ->
# cc.EaseQuadraticActionIn action.
# @return [EaseQuadraticActionOut]
@EaseQuadraticActionOut: ->
# cc.EaseQuarticActionIn action.
# @return [EaseQuarticActionIn]
@EaseQuarticActionIn: ->
# cc.EaseQuarticActionInOut action.
# @return [EaseQuarticActionInOut]
@EaseQuarticActionInOut: ->
# cc.EaseQuarticActionOut action.
# @return [EaseQuarticActionOut]
@EaseQuarticActionOut: ->
# cc.EaseQuinticActionIn action.
# @return [EaseQuinticActionIn]
@EaseQuinticActionIn: ->
# cc.EaseQuinticActionInOut action.
# @return [EaseQuinticActionInOut]
@EaseQuinticActionInOut: ->
# cc.EaseQuinticActionOut action.
# @return [EaseQuinticActionOut]
@EaseQuinticActionOut: ->
# Base class for Easing actions with rate parameters
# @param [ActionInterval] action
# @param [Number] rate
# @return [EaseRateAction]
@EaseRateAction: (action, rate) ->
# Ease Sine In.
# @return [EaseSineIn]
@EaseSineIn: ->
# Ease Sine InOut.
# @return [EaseSineInOut]
@EaseSineInOut: ->
# Ease Sine Out.
# @return [EaseSineOut]
@EaseSineOut: ->
# cc.EditBox is a brief Class for edit box.
# @return [EditBox]
@EditBox: ->
# @return [EditBoxDelegate]
@EditBoxDelegate: ->
# Base class of all kinds of events.
# @return [Event]
@Event: ->
# The Custom event
# @return [EventCustom]
@EventCustom: ->
# The widget focus event.
# @return [EventFocus]
@EventFocus: ->
# The base class of event listener.
# @return [EventListener]
@EventListener: ->
# cc.eventManager is a singleton object which manages event listener subscriptions and event dispatching.
# @return [eventManager]
@eventManager: ->
# The mouse event
# @return [EventMouse]
@EventMouse: ->
# The touch event
# @return [EventTouch]
@EventTouch: ->
# Fades In an object that implements the cc.RGBAProtocol protocol.
# @param [Number] duration
# @return [FadeIn]
@FadeIn: (duration) ->
# Fades Out an object that implements the cc.RGBAProtocol protocol.
# @param [Number] duration
# @return [FadeOut]
@FadeOut: (duration) ->
# cc.FadeOutBLTiles action.
# @return [FadeOutBLTiles]
@FadeOutBLTiles: ->
# cc.FadeOutDownTiles action.
# @return [FadeOutDownTiles]
@FadeOutDownTiles: ->
# cc.FadeOutTRTiles action.
# @return [FadeOutTRTiles]
@FadeOutTRTiles: ->
# cc.FadeOutUpTiles action.
# @return [FadeOutUpTiles]
@FadeOutUpTiles: ->
# Fades an object that implements the cc.RGBAProtocol protocol.
# @param [Number] duration
# @param [Number] opacity
# @return [FadeTo]
@FadeTo: (duration, opacity) ->
# Base class actions that do have a finite time duration.
# @return [FiniteTimeAction]
@FiniteTimeAction: ->
# Flips the sprite horizontally.
# @param [Boolean] flip
# @return [FlipX]
@FlipX: (flip) ->
# cc.FlipX3D action.
# @param [Number] duration
# @return [FlipX3D]
@FlipX3D: (duration) ->
# Flips the sprite vertically
# @param [Boolean] flip
# @return [FlipY]
@FlipY: (flip) ->
# cc.FlipY3D action.
# @param [Number] duration
# @return [FlipY3D]
@FlipY3D: (duration) ->
# cc.Follow is an action that "follows" a node.
# @param [Node] followedNode
# @param [Rect] rect
# @return [Follow]
@Follow: (followedNode, rect) ->
# cc.FontDefinition
# @return [FontDefinition]
@FontDefinition: ->
# An object to boot the game.
# @return [game]
@game: ->
# Class that implements a WebGL program
# @return [GLProgram]
@GLProgram: ->
# FBO class that grabs the the contents of the screen
# @return [Grabber]
@Grabber: ->
# cc.Grid3D is a 3D grid implementation.
# @return [Grid3D]
@Grid3D: ->
# Base class for cc.Grid3D actions.
# @return [Grid3DAction]
@Grid3DAction: ->
# Base class for Grid actions
# @param [Number] duration
# @param [Size] gridSize
# @return [GridAction]
@GridAction: (duration, gridSize) ->
# Base class for cc.Grid
# @return [GridBase]
@GridBase: ->
# @return [HashElement]
@HashElement: ->
# Hide the node.
# @return [Hide]
@Hide: ->
# TGA format
# @param [Number] status
# @param [Number] type
# @param [Number] pixelDepth
# @param [Number] width
# @param [Number] height
# @param [Array] imageData
# @param [Number] flipped
# @return [ImageTGA]
@ImageTGA: (status, type, pixelDepth, width, height, imageData, flipped) ->
# Input method editor delegate.
# @return [IMEDelegate]
@IMEDelegate: ->
# cc.imeDispatcher is a singleton object which manage input message dispatching.
# @return [imeDispatcher]
@imeDispatcher: ->
# This class manages all events of input.
# @return [inputManager]
@inputManager: ->
# An Invocation class
# @return [Invocation]
@Invocation: ->
# Moves a cc.Node object simulating a parabolic jump movement by modifying it's position attribute.
# @param [Number] duration
# @param [Point|Number] position
# @param [Number] y
# @param [Number] height
# @param [Number] jumps
# @return [JumpBy]
@JumpBy: (duration, position, y, height, jumps) ->
# cc.JumpTiles3D action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] numberOfJumps
# @param [Number] amplitude
# @return [JumpTiles3D]
@JumpTiles3D: (duration, gridSize, numberOfJumps, amplitude) ->
# Moves a cc.Node object to a parabolic position simulating a jump movement by modifying it's position attribute.
# @param [Number] duration
# @param [Point|Number] position
# @param [Number] y
# @param [Number] height
# @param [Number] jumps
# @return [JumpTo]
@JumpTo: (duration, position, y, height, jumps) ->
# The Quaternion class
# @param [Number] x
# @param [Number] y
# @param [Number] z
# @param [Number] w
# @return [kmQuaternion]
@kmQuaternion: (x, y, z, w) ->
# using image file to print text label on the screen, might be a bit slower than cc.Label, similar to cc.LabelBMFont
# @param [String] strText
# @param [String] charMapFile
# @param [Number] itemWidth
# @param [Number] itemHeight
# @param [Number] startCharMap
# @return [LabelAtlas]
@LabelAtlas: (strText, charMapFile, itemWidth, itemHeight, startCharMap) ->
# cc.LabelBMFont is a subclass of cc.SpriteBatchNode.
# @param [String] str
# @param [String] fntFile
# @param [Number] width
# @param [Number] alignment
# @param [Point] imageOffset
# @return [LabelBMFont]
@LabelBMFont: (str, fntFile, width, alignment, imageOffset) ->
# cc.LabelTTF is a subclass of cc.TextureNode that knows how to render text labels with system font or a ttf font file All features from cc.Sprite are valid in cc.LabelTTF cc.LabelTTF objects are slow for js-binding on mobile devices.
# @param [String] text
# @param [String|cc.FontDefinition] fontName
# @param [Number] fontSize
# @param [Size] dimensions
# @param [Number] hAlignment
# @param [Number] vAlignment
# @return [LabelTTF]
@LabelTTF: (text, fontName, fontSize, dimensions, hAlignment, vAlignment) ->
# cc.Layer is a subclass of cc.Node that implements the TouchEventsDelegate protocol.
# @return [Layer]
@Layer: ->
# CCLayerColor is a subclass of CCLayer that implements the CCRGBAProtocol protocol.
# @param [Color] color
# @param [Number] width
# @param [Number] height
# @return [LayerColor]
@LayerColor: (color, width, height) ->
# CCLayerGradient is a subclass of cc.LayerColor that draws gradients across the background.
# @param [Color] start
# @param [Color] end
# @param [Point] v
# @return [LayerGradient]
@LayerGradient: (start, end, v) ->
# CCMultipleLayer is a CCLayer with the ability to multiplex it's children.
# @param [Array] layers
# @return [LayerMultiplex]
@LayerMultiplex: (layers) ->
# cc.Lens3D action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Point] position
# @param [Number] radius
# @return [Lens3D]
@Lens3D: (duration, gridSize, position, radius) ->
# cc.Liquid action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] waves
# @param [Number] amplitude
# @return [Liquid]
@Liquid: (duration, gridSize, waves, amplitude) ->
# Loader for resource loading process.
# @return [loader]
@loader: ->
# Features and Limitation: - You can add MenuItem objects in runtime using addChild: - But the only accepted children are MenuItem objects
# @param [...cc.MenuItem|null] menuItems}
# @return [Menu]
@Menu: (menuItems}) ->
# Subclass cc.MenuItem (or any subclass) to create your custom cc.MenuItem objects.
# @param [function|String] callback
# @param [Node] target
# @return [MenuItem]
@MenuItem: (callback, target) ->
# Helper class that creates a MenuItemLabel class with a LabelAtlas
# @param [String] value
# @param [String] charMapFile
# @param [Number] itemWidth
# @param [Number] itemHeight
# @param [String] startCharMap
# @param [function|String|Null] callback
# @param [Node|Null] target
# @return [MenuItemAtlasFont]
@MenuItemAtlasFont: (value, charMapFile, itemWidth, itemHeight, startCharMap, callback, target) ->
# Helper class that creates a CCMenuItemLabel class with a Label
# @param [String] value
# @param [function|String] callback
# @param [Node] target
# @return [MenuItemFont]
@MenuItemFont: (value, callback, target) ->
# cc.MenuItemImage accepts images as items.
# @param [string|null] normalImage
# @param [string|null] selectedImage
# @param [string|null] disabledImage
# @param [function|string|null] callback
# @param [Node|null] target
# @return [MenuItemImage]
@MenuItemImage: (normalImage, selectedImage, disabledImage, callback, target) ->
# Any cc.Node that supports the cc.LabelProtocol protocol can be added.
# @param [Node] label
# @param [function|String] selector
# @param [Node] target
# @return [MenuItemLabel]
@MenuItemLabel: (label, selector, target) ->
# CCMenuItemSprite accepts CCNode objects as items.
# @param [Image|Null] normalSprite
# @param [Image|Null] selectedSprite
# @param [Image|cc.Node|Null] three
# @param [String|function|cc.Node|Null] four
# @param [String|function|Null] five
# @return [MenuItemSprite]
@MenuItemSprite: (normalSprite, selectedSprite, three, four, five) ->
# A simple container class that "toggles" it's inner items The inner items can be any MenuItem
# @return [MenuItemToggle]
@MenuItemToggle: ->
# MenuPassive: The menu passive ui component
# @return [MenuPassive]
@MenuPassive: ->
# cc.MotionStreak manages a Ribbon based on it's motion in absolute space.
# @return [MotionStreak]
@MotionStreak: ->
# Moves a CCNode object x,y pixels by modifying it's position attribute.
# @param [Number] duration
# @param [Point|Number] deltaPos
# @param [Number] deltaY
# @return [MoveBy]
@MoveBy: (duration, deltaPos, deltaY) ->
# Moves a CCNode object to the position x,y.
# @param [Number] duration
# @param [Point|Number] position
# @param [Number] y
# @return [MoveTo]
@MoveTo: (duration, position, y) ->
# cc.Node is the root class of all node.
# @return [Node]
@Node: ->
# This action simulates a page turn from the bottom right hand corner of the screen.
# @return [PageTurn3D]
@PageTurn3D: ->
# cc.ParallaxNode: A node that simulates a parallax scroller The children will be moved faster / slower than the parent according the the parallax ratio.
# @return [ParallaxNode]
@ParallaxNode: ->
# Structure that contains the values of each particle
# @param [Point] pos
# @param [Point] startPos
# @param [Color] color
# @param [Color] deltaColor
# @param [Size] size
# @param [Size] deltaSize
# @param [Number] rotation
# @param [Number] deltaRotation
# @param [Number] timeToLive
# @param [Number] atlasIndex
# @param [Particle.ModeA] modeA
# @param [Particle.ModeA] modeB
# @return [Particle]
@Particle: (pos, startPos, color, deltaColor, size, deltaSize, rotation, deltaRotation, timeToLive, atlasIndex, modeA, modeB) ->
# cc.ParticleBatchNode is like a batch node: if it contains children, it will draw them in 1 single OpenGL call (often known as "batch draw").
# @param [String|cc.Texture2D] fileImage
# @param [Number] capacity
# @return [ParticleBatchNode]
@ParticleBatchNode: (fileImage, capacity) ->
# An explosion particle system
# @return [ParticleExplosion]
@ParticleExplosion: ->
# A fire particle system
# @return [ParticleFire]
@ParticleFire: ->
# A fireworks particle system
# @return [ParticleFireworks]
@ParticleFireworks: ->
# A flower particle system
# @return [ParticleFlower]
@ParticleFlower: ->
# A galaxy particle system
# @return [ParticleGalaxy]
@ParticleGalaxy: ->
# A meteor particle system
# @return [ParticleMeteor]
@ParticleMeteor: ->
# A rain particle system
# @return [ParticleRain]
@ParticleRain: ->
# A smoke particle system
# @return [ParticleSmoke]
@ParticleSmoke: ->
# A snow particle system
# @return [ParticleSnow]
@ParticleSnow: ->
# A spiral particle system
# @return [ParticleSpiral]
@ParticleSpiral: ->
# A sun particle system
# @return [ParticleSun]
@ParticleSun: ->
# Particle System base class.
# @return [ParticleSystem]
@ParticleSystem: ->
# @return [path]
@path: ->
# Places the node in a certain position
# @param [Point|Number] pos
# @param [Number] y
# @return [Place]
@Place: (pos, y) ->
# cc.plistParser is a singleton object for parsing plist files
# @return [plistParser]
@plistParser: ->
# cc.Point
# @param [Number] x
# @param [Number] y
# @return [Point]
@Point: (x, y) ->
# Parallax Object.
# @return [PointObject]
@PointObject: ->
# Progress from a percentage to another percentage
# @param [Number] duration
# @param [Number] fromPercentage
# @param [Number] toPercentage
# @return [ProgressFromTo]
@ProgressFromTo: (duration, fromPercentage, toPercentage) ->
# cc.Progresstimer is a subclass of cc.Node.
# @return [ProgressTimer]
@ProgressTimer: ->
# Progress to percentage
# @param [Number] duration
# @param [Number] percent
# @return [ProgressTo]
@ProgressTo: (duration, percent) ->
# A class inhert from cc.Node, use for saving some protected children in other list.
# @return [ProtectedNode]
@ProtectedNode: ->
# cc.Rect
# @param [Number] width
# @param [Number] height
# @param width
# @param height
# @return [Rect]
@Rect: (width, height, width, height) ->
# Delete self in the next frame.
# @param [Boolean] isNeedCleanUp
# @return [RemoveSelf]
@RemoveSelf: (isNeedCleanUp) ->
# cc.RenderTexture is a generic rendering target.
# @return [RenderTexture]
@RenderTexture: ->
# Repeats an action a number of times.
# @param [FiniteTimeAction] action
# @param [Number] times
# @return [Repeat]
@Repeat: (action, times) ->
# Repeats an action for ever.
# @param [FiniteTimeAction] action
# @return [RepeatForever]
@RepeatForever: (action) ->
# cc.ResolutionPolicy class is the root strategy class of scale strategy, its main task is to maintain the compatibility with Cocos2d-x
# @param [ContainerStrategy] containerStg
# @param [ContentStrategy] contentStg
# @return [ResolutionPolicy]
@ResolutionPolicy: (containerStg, contentStg) ->
# cc.ReuseGrid action
# @param [Number] times
# @return [ReuseGrid]
@ReuseGrid: (times) ->
# Executes an action in reverse order, from time=duration to time=0
# @param [FiniteTimeAction] action
# @return [ReverseTime]
@ReverseTime: (action) ->
# An RGBA color class, its value present as percent
# @param [Number] r
# @param [Number] g
# @param [Number] b
# @param [Number] a
# @return [RGBA]
@RGBA: (r, g, b, a) ->
# cc.Ripple3D action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Point] position
# @param [Number] radius
# @param [Number] waves
# @param [Number] amplitude
# @return [Ripple3D]
@Ripple3D: (duration, gridSize, position, radius, waves, amplitude) ->
# Rotates a cc.Node object clockwise a number of degrees by modifying it's rotation attribute.
# @param [Number] duration
# @param [Number] deltaAngleX
# @param [Number] deltaAngleY
# @return [RotateBy]
@RotateBy: (duration, deltaAngleX, deltaAngleY) ->
# Rotates a cc.Node object to a certain angle by modifying it's.
# @param [Number] duration
# @param [Number] deltaAngleX
# @param [Number] deltaAngleY
# @return [RotateTo]
@RotateTo: (duration, deltaAngleX, deltaAngleY) ->
# A SAX Parser
# @return [saxParser]
@saxParser: ->
# A 9-slice sprite for cocos2d.
# @return [Scale9Sprite]
@Scale9Sprite: ->
# Scales a cc.Node object a zoom factor by modifying it's scale attribute.
# @return [ScaleBy]
@ScaleBy: ->
# Scales a cc.Node object to a zoom factor by modifying it's scale attribute.
# @param [Number] duration
# @param [Number] sx
# @param [Number] sy
# @return [ScaleTo]
@ScaleTo: (duration, sx, sy) ->
# cc.Scene is a subclass of cc.Node that is used only as an abstract concept.
# @return [Scene]
@Scene: ->
# Scheduler is responsible of triggering the scheduled callbacks.
# @return [Scheduler]
@Scheduler: ->
# The fullscreen API provides an easy way for web content to be presented using the user's entire screen.
# @return [screen]
@screen: ->
# ScrollView support for cocos2d -x.
# @return [ScrollView]
@ScrollView: ->
# Runs actions sequentially, one after another.
# @param [Array|cc.FiniteTimeAction] tempArray
# @return [Sequence]
@Sequence: (tempArray) ->
# cc.shaderCache is a singleton object that stores manages GL shaders
# @return [shaderCache]
@shaderCache: ->
# cc.Shaky3D action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] range
# @param [Boolean] shakeZ
# @return [Shaky3D]
@Shaky3D: (duration, gridSize, range, shakeZ) ->
# cc.ShakyTiles3D action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] range
# @param [Boolean] shakeZ
# @return [ShakyTiles3D]
@ShakyTiles3D: (duration, gridSize, range, shakeZ) ->
# cc.ShatteredTiles3D action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] range
# @param [Boolean] shatterZ
# @return [ShatteredTiles3D]
@ShatteredTiles3D: (duration, gridSize, range, shatterZ) ->
# Show the node.
# @return [Show]
@Show: ->
# cc.ShuffleTiles action, Shuffle the tiles in random order.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] seed
# @return [ShuffleTiles]
@ShuffleTiles: (duration, gridSize, seed) ->
# cc.Size
# @param [Number] width
# @param [Number] height
# @return [Size]
@Size: (width, height) ->
# Skews a cc.Node object by skewX and skewY degrees.
# @param [Number] t
# @param [Number] sx
# @param [Number] sy
# @return [SkewBy]
@SkewBy: (t, sx, sy) ->
# Skews a cc.Node object to given angles by modifying it's skewX and skewY attributes
# @param [Number] t
# @param [Number] sx
# @param [Number] sy
# @return [SkewTo]
@SkewTo: (t, sx, sy) ->
# The sortable object interface
# @return [SortableObject]
@SortableObject: ->
# The SortedObject class
# @return [SortedObject]
@SortedObject: ->
# The Spacer class
# @return [Spacer]
@Spacer: ->
# Spawn a new action immediately
# @return [Spawn]
@Spawn: ->
# Changes the speed of an action, making it take longer (speed 1) or less (speed
# @param [ActionInterval] action
# @param [Number] speed
# @return [Speed]
@Speed: (action, speed) ->
# cc.SplitCols action.
# @param [Number] duration
# @param [Number] cols
# @return [SplitCols]
@SplitCols: (duration, cols) ->
# cc.SplitRows action.
# @param [Number] duration
# @param [Number] rows
# @return [SplitRows]
@SplitRows: (duration, rows) ->
# cc.Sprite is a 2d image ( http://en.wikipedia.org/wiki/Sprite_(computer_graphics) ) cc.Sprite can be created with an image, or with a sub-rectangle of an image.
# @param [String|cc.SpriteFrame|HTMLImageElement|cc.Texture2D] fileName
# @param [Rect] rect
# @param [Boolean] rotated
# @return [Sprite]
@Sprite: (fileName, rect, rotated) ->
# In Canvas render mode ,cc.SpriteBatchNodeCanvas is like a normal node: if it contains children.
# @param [String|cc.Texture2D] fileImage
# @param [Number] capacity
# @return [SpriteBatchNode]
@SpriteBatchNode: (fileImage, capacity) ->
# A cc.SpriteFrame has: - texture: A cc.Texture2D that will be used by the cc.Sprite - rectangle: A rectangle of the texture You can modify the frame of a cc.Sprite by doing:
# @param [String|cc.Texture2D] filename
# @param [Rect] rect
# @param [Boolean] rotated
# @param [Point] offset
# @param [Size] originalSize
# @return [SpriteFrame]
@SpriteFrame: (filename, rect, rotated, offset, originalSize) ->
# cc.spriteFrameCache is a singleton that handles the loading of the sprite frames.
# @return [spriteFrameCache]
@spriteFrameCache: ->
# cc.StopGrid action.
# @return [StopGrid]
@StopGrid: ->
# UITableView counterpart for cocos2d for iphone.
# @return [TableView]
@TableView: ->
# Abstract class for SWTableView cell node
# @return [TableViewCell]
@TableViewCell: ->
# Overrides the target of an action so that it always runs on the target specified at action creation rather than the one specified by runAction.
# @param [Node] target
# @param [FiniteTimeAction] action
# @return [TargetedAction]
@TargetedAction: (target, action) ->
# cc.Tex2F
# @param [Number] u1
# @param [Number] v1
# @return [Tex2F]
@Tex2F: (u1, v1) ->
# Text field delegate
# @return [TextFieldDelegate]
@TextFieldDelegate: ->
# A simple text input field with TTF font.
# @param [String] placeholder
# @param [Size] dimensions
# @param [Number] alignment
# @param [String] fontName
# @param [Number] fontSize
# @return [TextFieldTTF]
@TextFieldTTF: (placeholder, dimensions, alignment, fontName, fontSize) ->
# This class allows to easily create OpenGL or Canvas 2D textures from images, text or raw data.
# @return [Texture2D]
@Texture2D: ->
# A class that implements a Texture Atlas.
# @return [TextureAtlas]
@TextureAtlas: ->
# cc.textureCache is a singleton object, it's the global cache for cc.Texture2D
# @return [textureCache]
@textureCache: ->
# A Tile composed of position, startPosition and delta.
# @param [Point] position
# @param [Point] startPosition
# @param [Size] delta
# @return [Tile]
@Tile: (position, startPosition, delta) ->
# cc.TiledGrid3D is a 3D grid implementation.
# @return [TiledGrid3D]
@TiledGrid3D: ->
# Base class for cc.TiledGrid3D actions.
# @return [TiledGrid3DAction]
@TiledGrid3DAction: ->
# Light weight timer
# @return [Timer]
@Timer: ->
# Tints a cc.Node that implements the cc.NodeRGB protocol from current tint to a custom one.
# @param [Number] duration
# @param [Number] deltaRed
# @param [Number] deltaGreen
# @param [Number] deltaBlue
# @return [TintBy]
@TintBy: (duration, deltaRed, deltaGreen, deltaBlue) ->
# Tints a cc.Node that implements the cc.NodeRGB protocol from current tint to a custom one.
# @param [Number] duration
# @param [Number] red
# @param [Number] green
# @param [Number] blue
# @return [TintTo]
@TintTo: (duration, red, green, blue) ->
# cc.TMXLayer represents the TMX layer.
# @return [TMXLayer]
@TMXLayer: ->
# cc.TMXLayerInfo contains the information about the layers like: - Layer name - Layer size - Layer opacity at creation time (it can be modified at runtime) - Whether the layer is visible (if it's not visible, then the CocosNode won't be created) This information is obtained from the TMX file.
# @return [TMXLayerInfo]
@TMXLayerInfo: ->
# cc.TMXMapInfo contains the information about the map like: - Map orientation (hexagonal, isometric or orthogonal) - Tile size - Map size And it also contains: - Layers (an array of TMXLayerInfo objects) - Tilesets (an array of TMXTilesetInfo objects) - ObjectGroups (an array of TMXObjectGroupInfo objects) This information is obtained from the TMX file.
# @param [String] tmxFile
# @param [String] resourcePath
# @return [TMXMapInfo]
@TMXMapInfo: (tmxFile, resourcePath) ->
# cc.TMXObjectGroup represents the TMX object group.
# @return [TMXObjectGroup]
@TMXObjectGroup: ->
# cc.TMXTiledMap knows how to parse and render a TMX map.
# @param [String] tmxFile
# @param [String] resourcePath
# @return [TMXTiledMap]
@TMXTiledMap: (tmxFile, resourcePath) ->
# cc.TMXTilesetInfo contains the information about the tilesets like: - Tileset name - Tileset spacing - Tileset margin - size of the tiles - Image used for the tiles - Image size This information is obtained from the TMX file.
# @return [TMXTilesetInfo]
@TMXTilesetInfo: ->
# Toggles the visibility of a node.
# @return [ToggleVisibility]
@ToggleVisibility: ->
# The touch event class
# @param [Number] x
# @param [Number] y
# @param [Number] id
# @return [Touch]
@Touch: (x, y, id) ->
# Cross fades two scenes using the cc.RenderTexture object.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionCrossFade]
@TransitionCrossFade: (t, scene) ->
# Fade out the outgoing scene and then fade in the incoming scene.
# @param [Number] t
# @param [Scene] scene
# @param [TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER] o
# @return [TransitionFade]
@TransitionFade: (t, scene, o) ->
# Fade the tiles of the outgoing scene from the top-right corner to the bottom-left corner.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionFadeBL]
@TransitionFadeBL: (t, scene) ->
# Fade the tiles of the outgoing scene from the top to the bottom.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionFadeDown]
@TransitionFadeDown: (t, scene) ->
# Fade the tiles of the outgoing scene from the left-bottom corner the to top-right corner.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionFadeTR]
@TransitionFadeTR: (t, scene) ->
# Fade the tiles of the outgoing scene from the top-right corner to the bottom-left corner.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionFadeUp]
@TransitionFadeUp: (t, scene) ->
# Flips the screen half horizontally and half vertically.
# @param [Number] t
# @param [Scene] scene
# @param [TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER] o
# @return [TransitionFlipAngular]
@TransitionFlipAngular: (t, scene, o) ->
# Flips the screen horizontally.
# @param [Number] t
# @param [Scene] scene
# @param [TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER] o
# @return [TransitionFlipX]
@TransitionFlipX: (t, scene, o) ->
# Flips the screen vertically.
# @param [Number] t
# @param [Scene] scene
# @param [TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER] o
# @return [TransitionFlipY]
@TransitionFlipY: (t, scene, o) ->
# Zoom out and jump the outgoing scene, and then jump and zoom in the incoming
# @param [Number] t
# @param [Scene] scene
# @return [TransitionJumpZoom]
@TransitionJumpZoom: (t, scene) ->
# Move in from to the bottom the incoming scene.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionMoveInB]
@TransitionMoveInB: (t, scene) ->
# Move in from to the left the incoming scene.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionMoveInL]
@TransitionMoveInL: (t, scene) ->
# Move in from to the right the incoming scene.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionMoveInR]
@TransitionMoveInR: (t, scene) ->
# Move in from to the top the incoming scene.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionMoveInT]
@TransitionMoveInT: (t, scene) ->
# A transition which peels back the bottom right hand corner of a scene to transition to the scene beneath it simulating a page turn.
# @param [Number] t
# @param [Scene] scene
# @param [Boolean] backwards
# @return [TransitionPageTurn]
@TransitionPageTurn: (t, scene, backwards) ->
# cc.TransitionProgress transition.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionProgress]
@TransitionProgress: (t, scene) ->
# cc.TransitionProgressHorizontal transition.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionProgressHorizontal]
@TransitionProgressHorizontal: (t, scene) ->
# cc.TransitionProgressInOut transition.
# @return [TransitionProgressInOut]
@TransitionProgressInOut: ->
# cc.TransitionProgressOutIn transition.
# @return [TransitionProgressOutIn]
@TransitionProgressOutIn: ->
# cc.TransitionRadialCCW transition.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionProgressRadialCCW]
@TransitionProgressRadialCCW: (t, scene) ->
# cc.TransitionRadialCW transition.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionProgressRadialCW]
@TransitionProgressRadialCW: (t, scene) ->
# cc.TransitionProgressVertical transition.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionProgressVertical]
@TransitionProgressVertical: (t, scene) ->
# Rotate and zoom out the outgoing scene, and then rotate and zoom in the incoming
# @param [Number] t
# @param [Scene] scene
# @return [TransitionRotoZoom]
@TransitionRotoZoom: (t, scene) ->
# @param [Number] t
# @param [Scene] scene
# @return [TransitionScene]
@TransitionScene: (t, scene) ->
# A cc.Transition that supports orientation like.
# @param [Number] t
# @param [Scene] scene
# @param [TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER] orientation
# @return [TransitionSceneOriented]
@TransitionSceneOriented: (t, scene, orientation) ->
# Shrink the outgoing scene while grow the incoming scene
# @param [Number] t
# @param [Scene] scene
# @return [TransitionShrinkGrow]
@TransitionShrinkGrow: (t, scene) ->
# Slide in the incoming scene from the bottom border.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionSlideInB]
@TransitionSlideInB: (t, scene) ->
# a transition that a new scene is slided from left
# @param [Number] t
# @param [Scene] scene
# @return [TransitionSlideInL]
@TransitionSlideInL: (t, scene) ->
# Slide in the incoming scene from the right border.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionSlideInR]
@TransitionSlideInR: (t, scene) ->
# Slide in the incoming scene from the top border.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionSlideInT]
@TransitionSlideInT: (t, scene) ->
# The odd columns goes upwards while the even columns goes downwards.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionSplitCols]
@TransitionSplitCols: (t, scene) ->
# The odd rows goes to the left while the even rows goes to the right.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionSplitRows]
@TransitionSplitRows: (t, scene) ->
# Turn off the tiles of the outgoing scene in random order
# @param [Number] t
# @param [Scene] scene
# @return [TransitionTurnOffTiles]
@TransitionTurnOffTiles: (t, scene) ->
# Flips the screen half horizontally and half vertically doing a little zooming out/in.
# @param [Number] t
# @param [Scene] scene
# @param [TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER] o
# @return [TransitionZoomFlipAngular]
@TransitionZoomFlipAngular: (t, scene, o) ->
# Flips the screen horizontally doing a zoom out/in The front face is the outgoing scene and the back face is the incoming scene.
# @param [Number] t
# @param [Scene] scene
# @param [TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER] o
# @return [TransitionZoomFlipX]
@TransitionZoomFlipX: (t, scene, o) ->
# Flips the screen vertically doing a little zooming out/in The front face is the outgoing scene and the back face is the incoming scene.
# @param [Number] t
# @param [Scene] scene
# @param [TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER] o
# @return [TransitionZoomFlipY]
@TransitionZoomFlipY: (t, scene, o) ->
# cc.TurnOffTiles action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number|Null] seed
# @return [TurnOffTiles]
@TurnOffTiles: (duration, gridSize, seed) ->
# cc.Twirl action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Point] position
# @param [Number] twirls
# @param [Number] amplitude
# @return [Twirl]
@Twirl: (duration, gridSize, position, twirls, amplitude) ->
# cc.Vertex2F
# @param [Number] x1
# @param [Number] y1
# @return [Vertex2F]
@Vertex2F: (x1, y1) ->
# cc.Vertex3F
# @param [Number] x1
# @param [Number] y1
# @param [Number] z1
# @return [Vertex3F]
@Vertex3F: (x1, y1, z1) ->
# cc.view is the singleton object which represents the game window.
# @return [view]
@view: ->
# cc.visibleRect is a singleton object which defines the actual visible rect of the current view, it should represent the same rect as cc.view.getViewportRect()
# @return [visibleRect]
@visibleRect: ->
# cc.Waves action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] waves
# @param [Number] amplitude
# @param [Boolean] horizontal
# @param [Boolean] vertical
# @return [Waves]
@Waves: (duration, gridSize, waves, amplitude, horizontal, vertical) ->
# cc.Waves3D action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] waves
# @param [Number] amplitude
# @return [Waves3D]
@Waves3D: (duration, gridSize, waves, amplitude) ->
# cc.WavesTiles3D action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] waves
# @param [Number] amplitude
# @return [WavesTiles3D]
@WavesTiles3D: (duration, gridSize, waves, amplitude) ->
# A class of Web Audio.
# @param src
# @return [WebAudio]
@WebAudio: (src) ->
| true |
class cc
# Default Action tag
@ACTION_TAG_INVALID = {}
# The adjust factor is needed to prevent issue #442 One solution is to use DONT_RENDER_IN_SUBPIXELS images, but NO The other issue is that in some transitions (and I don't know why) the order should be reversed (In in top of Out or vice-versa).
# [Number]
@ADJUST_FACTOR = 1
# Horizontal center and vertical bottom.
# [Number]
@ALIGN_BOTTOM = 1
# Horizontal left and vertical bottom.
# [Number]
@ALIGN_BOTTOM_LEFT = 1
# Horizontal right and vertical bottom.
# [Number]
@ALIGN_BOTTOM_RIGHT = 1
# Horizontal center and vertical center.
# [Number]
@ALIGN_CENTER = 1
# Horizontal left and vertical center.
# [Number]
@ALIGN_LEFT = 1
# Horizontal right and vertical center.
# [Number]
@ALIGN_RIGHT = 1
# Horizontal center and vertical top.
# [Number]
@ALIGN_TOP = 1
# Horizontal left and vertical top.
# [Number]
@ALIGN_TOP_LEFT = 1
# Horizontal right and vertical top.
# [Number]
@ALIGN_TOP_RIGHT = 1
@ATTRIBUTE_NAME_COLOR = {}
@ATTRIBUTE_NAME_POSITION = {}
@ATTRIBUTE_NAME_TEX_COORD = {}
# default gl blend dst function.
# [Number]
@BLEND_DST = 1
# default gl blend src function.
# [Number]
@BLEND_SRC = 1
# A CCCamera is used in every CCNode.
@Camera = {}
# If enabled, the cc.Node objects (cc.Sprite, cc.Label,etc) will be able to render in subpixels.
@COCOSNODE_RENDER_SUBPIXEL = {}
# Number of kinds of control event.
@CONTROL_EVENT_TOTAL_NUMBER = {}
# Kinds of possible events for the control objects.
@CONTROL_EVENT_TOUCH_DOWN = {}
# The possible state for a control.
@CONTROL_STATE_NORMAL = {}
# returns a new clone of the controlPoints
# [Array]
@copyControlPoints = []
# default tag for current item
# [Number]
@CURRENT_ITEM = 1
# Default engine
@DEFAULT_ENGINE = {}
# [Number]
@DEFAULT_PADDING = 1
# [Number]
@DEFAULT_SPRITE_BATCH_CAPACITY = 1
# Default fps is 60
@defaultFPS = {}
# [Number]
@DEG = 1
# In browsers, we only support 2 orientations by change window size.
# [Number]
@DEVICE_MAX_ORIENTATIONS = 1
# Device oriented horizontally, home button on the right (UIDeviceOrientationLandscapeLeft)
# [Number]
@DEVICE_ORIENTATION_LANDSCAPE_LEFT = 1
# Device oriented horizontally, home button on the left (UIDeviceOrientationLandscapeRight)
# [Number]
@DEVICE_ORIENTATION_LANDSCAPE_RIGHT = 1
# Device oriented vertically, home button on the bottom (UIDeviceOrientationPortrait)
# [Number]
@DEVICE_ORIENTATION_PORTRAIT = 1
# Device oriented vertically, home button on the top (UIDeviceOrientationPortraitUpsideDown)
# [Number]
@DEVICE_ORIENTATION_PORTRAIT_UPSIDE_DOWN = 1
@director = {}
# Seconds between FPS updates.
@DIRECTOR_FPS_INTERVAL = {}
# Position of the FPS (Default: 0,0 (bottom-left corner)) To modify it, in Web engine please refer to CCConfig.js, in JSB please refer to CCConfig.h
@DIRECTOR_STATS_POSITION = {}
# default disabled tag
# [Number]
@DISABLE_TAG = 1
# ************************************************ implementation of DisplayLinkDirector ************************************************
@DisplayLinkDirector = {}
# [Number]
@DST_ALPHA = 1
# [Number]
@DST_COLOR = 1
# Capitalize all characters automatically.
# [Number]
@EDITBOX_INPUT_FLAG_INITIAL_CAPS_ALL_CHARACTERS = 1
# This flag is a hint to the implementation that during text editing, the initial letter of each sentence should be capitalized.
# [Number]
@EDITBOX_INPUT_FLAG_INITIAL_CAPS_SENTENCE = 1
# This flag is a hint to the implementation that during text editing, the initial letter of each word should be capitalized.
# [Number]
@EDITBOX_INPUT_FLAG_INITIAL_CAPS_WORD = 1
# Indicates that the text entered is confidential data that should be obscured whenever possible.
# [Number]
@EDITBOX_INPUT_FLAG_PASSWORD = 1
# Indicates that the text entered is sensitive data that the implementation must never store into a dictionary or table for use in predictive, auto-completing, or other accelerated input schemes.
# [Number]
@EDITBOX_INPUT_FLAG_SENSITIVE = 1
# The EditBoxInputMode defines the type of text that the user is allowed * to enter.
# [Number]
@EDITBOX_INPUT_MODE_ANY = 1
# The user is allowed to enter a real number value.
# [Number]
@EDITBOX_INPUT_MODE_DECIMAL = 1
# The user is allowed to enter an e-mail address.
# [Number]
@EDITBOX_INPUT_MODE_EMAILADDR = 1
# The user is allowed to enter an integer value.
# [Number]
@EDITBOX_INPUT_MODE_NUMERIC = 1
# The user is allowed to enter a phone number.
# [Number]
@EDITBOX_INPUT_MODE_PHONENUMBER = 1
# The user is allowed to enter any text, except for line breaks.
# [Number]
@EDITBOX_INPUT_MODE_SINGLELINE = 1
# The user is allowed to enter a URL.
# [Number]
@EDITBOX_INPUT_MODE_URL = 1
# If enabled, cocos2d will maintain an OpenGL state cache internally to avoid unnecessary switches.
@ENABLE_GL_STATE_CACHE = {}
# If enabled, actions that alter the position property (eg: CCMoveBy, CCJumpBy, CCBezierBy, etc.
@ENABLE_STACKABLE_ACTIONS = {}
# The current version of Cocos2d-JS being used.
@ENGINE_VERSION = {}
# If enabled, the texture coordinates will be calculated by using this formula: - texCoord.left = (rect.x*2+1) / (texture.wide*2); - texCoord.right = texCoord.left + (rect.width*2-2)/(texture.wide*2); The same for bottom and top.
@FIX_ARTIFACTS_BY_STRECHING_TEXEL = {}
# [Number]
@FLT_EPSILON = 1
# [Number]
@FLT_MAX = 1
# [Number]
@FLT_MIN = 1
# Image Format:JPG
@FMT_JPG = {}
# Image Format:PNG
@FMT_PNG = {}
# Image Format:RAWDATA
@FMT_RAWDATA = {}
# Image Format:TIFF
@FMT_TIFF = {}
# Image Format:UNKNOWN
@FMT_UNKNOWN = {}
# Image Format:WEBP
@FMT_WEBP = {}
# ************************************************************************* Copyright (c) 2008-2010 PI:NAME:<NAME>END_PI Copyright (c) 2011-2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc.
@g_NumberOfDraws = {}
# GL server side states
@GL_ALL = {}
# A update entry list
@HashUpdateEntry = {}
# enum for jpg
# [Number]
@IMAGE_FORMAT_JPEG = 1
# enum for png
# [Number]
@IMAGE_FORMAT_PNG = 1
# enum for raw
# [Number]
@IMAGE_FORMAT_RAWDATA = 1
# [Number]
@INVALID_INDEX = 1
# Whether or not support retina display
@IS_RETINA_DISPLAY_SUPPORTED = {}
# default size for font size
# [Number]
@ITEM_SIZE = 1
# Key map for keyboard event
@KEY = {}
# [Number]
@KEYBOARD_RETURNTYPE_DEFAULT = 1
# [Number]
@KEYBOARD_RETURNTYPE_DONE = 1
# [Number]
@KEYBOARD_RETURNTYPE_GO = 1
# [Number]
@KEYBOARD_RETURNTYPE_SEARCH = 1
# [Number]
@KEYBOARD_RETURNTYPE_SEND = 1
# [Number]
@LABEL_AUTOMATIC_WIDTH = 1
# If enabled, all subclasses of cc.LabelAtlas will draw a bounding box Useful for debugging purposes only.
@LABELATLAS_DEBUG_DRAW = {}
# If enabled, all subclasses of cc.LabelBMFont will draw a bounding box Useful for debugging purposes only.
@LABELBMFONT_DEBUG_DRAW = {}
# A list double-linked list used for "updates with priority"
@ListEntry = {}
# The min corner of the box
@max = {}
# [Number]
@MENU_HANDLER_PRIORITY = 1
# [Number]
@MENU_STATE_TRACKING_TOUCH = 1
# [Number]
@MENU_STATE_WAITING = 1
# The max corner of the box
@min = {}
# Default Node tag
# [Number]
@NODE_TAG_INVALID = 1
# NodeGrid class is a class serves as a decorator of cc.Node, Grid node can run grid actions over all its children
@NodeGrid = {}
# default tag for normal
# [Number]
@NORMAL_TAG = 1
# [Number]
@ONE = 1
# [Number]
@ONE_MINUS_CONSTANT_ALPHA = 1
# [Number]
@ONE_MINUS_CONSTANT_COLOR = 1
# [Number]
@ONE_MINUS_DST_ALPHA = 1
# [Number]
@ONE_MINUS_DST_COLOR = 1
# [Number]
@ONE_MINUS_SRC_ALPHA = 1
# [Number]
@ONE_MINUS_SRC_COLOR = 1
# If most of your images have pre-multiplied alpha, set it to 1 (if you are going to use .PNG/.JPG file images).
@OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA = {}
# Device oriented horizontally, home button on the right
@ORIENTATION_LANDSCAPE_LEFT = {}
# Device oriented horizontally, home button on the left
@ORIENTATION_LANDSCAPE_RIGHT = {}
# Device oriented vertically, home button on the bottom
@ORIENTATION_PORTRAIT = {}
# Device oriented vertically, home button on the top
@ORIENTATION_PORTRAIT_UPSIDE_DOWN = {}
# paticle default capacity
# [Number]
@PARTICLE_DEFAULT_CAPACITY = 1
# PI is the ratio of a circle's circumference to its diameter.
# [Number]
@PI = 1
@plistParser A Plist Parser A Plist Parser = {}
# smallest such that 1.0+FLT_EPSILON != 1.0
# [Number]
@POINT_EPSILON = 1
# Minimum priority level for user scheduling.
# [Number]
@PRIORITY_NON_SYSTEM = 1
# [Number]
@RAD = 1
# [Number]
@REPEAT_FOREVER = 1
# It's the suffix that will be appended to the files in order to load "retina display" images.
@RETINA_DISPLAY_FILENAME_SUFFIX = {}
# If enabled, cocos2d supports retina display.
@RETINA_DISPLAY_SUPPORT = {}
# XXX: Yes, nodes might have a sort problem once every 15 days if the game runs at 60 FPS and each frame sprites are reordered.
@s_globalOrderOfArrival = {}
# A tag constant for identifying fade scenes
# [Number]
@SCENE_FADE = 1
# tag for scene redial
# [Number]
@SCENE_RADIAL = 1
# default selected tag
# [Number]
@SELECTED_TAG = 1
@SHADER_POSITION_COLOR = {}
@SHADER_POSITION_COLOR_FRAG = {}
@SHADER_POSITION_COLOR_LENGTH_TEXTURE_FRAG = {}
@SHADER_POSITION_COLOR_LENGTH_TEXTURE_VERT = {}
@SHADER_POSITION_COLOR_VERT = {}
@SHADER_POSITION_LENGTHTEXTURECOLOR = {}
@SHADER_POSITION_TEXTURE = {}
@SHADER_POSITION_TEXTURE_A8COLOR_FRAG = {}
@SHADER_POSITION_TEXTURE_A8COLOR_VERT = {}
@SHADER_POSITION_TEXTURE_COLOR_ALPHATEST_FRAG = {}
@SHADER_POSITION_TEXTURE_COLOR_FRAG = {}
@SHADER_POSITION_TEXTURE_COLOR_VERT = {}
@SHADER_POSITION_TEXTURE_FRAG = {}
@SHADER_POSITION_TEXTURE_UCOLOR = {}
@SHADER_POSITION_TEXTURE_UCOLOR_FRAG = {}
@SHADER_POSITION_TEXTURE_UCOLOR_VERT = {}
@SHADER_POSITION_TEXTURE_VERT = {}
@SHADER_POSITION_TEXTUREA8COLOR = {}
@SHADER_POSITION_TEXTURECOLOR = {}
@SHADER_POSITION_TEXTURECOLORALPHATEST = {}
@SHADER_POSITION_UCOLOR = {}
@SHADER_POSITION_UCOLOR_FRAG = {}
@SHADER_POSITION_UCOLOR_VERT = {}
@SHADEREX_SWITCHMASK_FRAG = {}
# If enabled, all subclasses of cc.Sprite will draw a bounding box Useful for debugging purposes only.
@SPRITE_DEBUG_DRAW = {}
# If enabled, all subclasses of cc.Sprite that are rendered using an cc.SpriteBatchNode draw a bounding box.
@SPRITEBATCHNODE_DEBUG_DRAW = {}
# If enabled, the cc.Sprite objects rendered with cc.SpriteBatchNode will be able to render in subpixels.
@SPRITEBATCHNODE_RENDER_SUBPIXEL = {}
# [Number]
@SRC_ALPHA = 1
# [Number]
@SRC_ALPHA_SATURATE = 1
# [Number]
@SRC_COLOR = 1
# the value of stencil bits.
# [Number]
@stencilBits = 1
# The constant value of the fill style from bottom to top for cc.TableView
@TABLEVIEW_FILL_BOTTOMUP = {}
# The constant value of the fill style from top to bottom for cc.TableView
@TABLEVIEW_FILL_TOPDOWN = {}
# Data source that governs table backend data.
@TableViewDataSource = {}
# Sole purpose of this delegate is to single touch event in this version.
@TableViewDelegate = {}
# text alignment : center
# [Number]
@TEXT_ALIGNMENT_CENTER = 1
# text alignment : left
# [Number]
@TEXT_ALIGNMENT_LEFT = 1
# text alignment : right
# [Number]
@TEXT_ALIGNMENT_RIGHT = 1
# Use GL_TRIANGLE_STRIP instead of GL_TRIANGLES when rendering the texture atlas.
@TEXTURE_ATLAS_USE_TRIANGLE_STRIP = {}
# By default, cc.TextureAtlas (used by many cocos2d classes) will use VAO (Vertex Array Objects).
@TEXTURE_ATLAS_USE_VAO = {}
# If enabled, NPOT textures will be used where available.
@TEXTURE_NPOT_SUPPORT = {}
# [Number]
@TGA_ERROR_COMPRESSED_FILE = 1
# [Number]
@TGA_ERROR_FILE_OPEN = 1
# [Number]
@TGA_ERROR_INDEXED_COLOR = 1
# [Number]
@TGA_ERROR_MEMORY = 1
# [Number]
@TGA_ERROR_READING_FILE = 1
# [Number]
@TGA_OK = 1
# A png file reader
@tiffReader = {}
# Hexagonal orientation
# [Number]
@TMX_ORIENTATION_HEX = 1
# Isometric orientation
# [Number]
@TMX_ORIENTATION_ISO = 1
# Orthogonal orientation
# [Number]
@TMX_ORIENTATION_ORTHO = 1
# [Number]
@TMX_PROPERTY_LAYER = 1
# [Number]
@TMX_PROPERTY_MAP = 1
# [Number]
@TMX_PROPERTY_NONE = 1
# [Number]
@TMX_PROPERTY_OBJECT = 1
# [Number]
@TMX_PROPERTY_OBJECTGROUP = 1
# [Number]
@TMX_PROPERTY_TILE = 1
# [Number]
@TMX_TILE_DIAGONAL_FLAG = 1
# [Number]
@TMX_TILE_FLIPPED_ALL = 1
# [Number]
@TMX_TILE_FLIPPED_MASK = 1
# [Number]
@TMX_TILE_HORIZONTAL_FLAG = 1
# [Number]
@TMX_TILE_VERTICAL_FLAG = 1
# vertical orientation type where the Bottom is nearer
# [Number]
@TRANSITION_ORIENTATION_DOWN_OVER = 1
# horizontal orientation Type where the Left is nearer
# [Number]
@TRANSITION_ORIENTATION_LEFT_OVER = 1
# horizontal orientation type where the Right is nearer
# [Number]
@TRANSITION_ORIENTATION_RIGHT_OVER = 1
# vertical orientation type where the Up is nearer
# [Number]
@TRANSITION_ORIENTATION_UP_OVER = 1
@UIInterfaceOrientationLandscapeLeft = {}
@UIInterfaceOrientationLandscapeRight = {}
@UIInterfaceOrientationPortrait = {}
@UIInterfaceOrientationPortraitUpsideDown = {}
# maximum unsigned int value
# [Number]
@UINT_MAX = 1
@UNIFORM_ALPHA_TEST_VALUE_S = {}
@UNIFORM_COSTIME = {}
@UNIFORM_COSTIME_S = {}
@UNIFORM_MAX = {}
@UNIFORM_MVMATRIX = {}
@UNIFORM_MVMATRIX_S = {}
@UNIFORM_MVPMATRIX = {}
@UNIFORM_MVPMATRIX_S = {}
@UNIFORM_PMATRIX = {}
@UNIFORM_PMATRIX_S = {}
@UNIFORM_RANDOM01 = {}
@UNIFORM_RANDOM01_S = {}
@UNIFORM_SAMPLER = {}
@UNIFORM_SAMPLER_S = {}
@UNIFORM_SINTIME = {}
@UNIFORM_SINTIME_S = {}
@UNIFORM_TIME = {}
@UNIFORM_TIME_S = {}
# If enabled, it will use LA88 (Luminance Alpha 16-bit textures) for CCLabelTTF objects.
@USE_LA88_LABELS = {}
@VERTEX_ATTRIB_COLOR = {}
@VERTEX_ATTRIB_FLAG_COLOR = {}
@VERTEX_ATTRIB_FLAG_NONE = {}
@VERTEX_ATTRIB_FLAG_POS_COLOR_TEX = {}
@VERTEX_ATTRIB_FLAG_POSITION = {}
@VERTEX_ATTRIB_FLAG_TEX_COORDS = {}
@VERTEX_ATTRIB_MAX = {}
@VERTEX_ATTRIB_POSITION = {}
@VERTEX_ATTRIB_TEX_COORDS = {}
# text alignment : bottom
# [Number]
@VERTICAL_TEXT_ALIGNMENT_BOTTOM = 1
# text alignment : center
# [Number]
@VERTICAL_TEXT_ALIGNMENT_CENTER = 1
# text alignment : top
# [Number]
@VERTICAL_TEXT_ALIGNMENT_TOP = 1
# [Number]
@ZERO = 1
# default tag for zoom action tag
# [Number]
@ZOOM_ACTION_TAG = 1
# the dollar sign, classic like jquery, this selector add extra methods to HTMLElement without touching its prototype it is also chainable like jquery
# @param [HTMLElement|String] x
# @return [$]
@$: (x) ->
# Creates a new element, and adds cc.$ methods
# @param [String] x
# @return [$]
@$new: (x) ->
# Allocates and initializes the action.
# @return [Action]
@action: ->
# creates the action of ActionEase
# @param [ActionInterval] action
# @return [ActionEase]
@actionEase: (action) ->
# An interval action is an action that takes place within a certain period of time.
# @param [Number] d
# @return [ActionInterval]
@actionInterval: (d) ->
# Creates an initializes the action with the property name (key), and the from and to parameters.
# @param [Number] duration
# @param [String] key
# @param [Number] from
# @param [Number] to
# @return [ActionTween]
@actionTween: (duration, key, from, to) ->
# Concatenate a transform matrix to another and return the result: t' = t1 * t2
# @param [AffineTransform] t1
# @param [AffineTransform] t2
# @return [AffineTransform]
@affineTransformConcat: (t1, t2) ->
# Return true if an affine transform equals to another, false otherwise.
# @param [AffineTransform] t1
# @param [AffineTransform] t2
# @return [Boolean]
@affineTransformEqualToTransform: (t1, t2) ->
# Create a identity transformation matrix: [ 1, 0, 0, 0, 1, 0 ]
# @return [AffineTransform]
@affineTransformIdentity: ->
# Get the invert transform of an AffineTransform object
# @param [AffineTransform] t
# @return [AffineTransform]
@affineTransformInvert: (t) ->
# Create a cc.AffineTransform object with all contents in the matrix
# @param [Number] a
# @param [Number] b
# @param [Number] c
# @param [Number] d
# @param [Number] tx
# @param [Number] ty
# @return [AffineTransform]
@affineTransformMake: (a, b, c, d, tx, ty) ->
# Create a identity transformation matrix: [ 1, 0, 0, 0, 1, 0 ]
# @return [AffineTransform]
@affineTransformMakeIdentity: ->
# Create a new affine transformation with a base transformation matrix and a rotation based on it.
# @param [AffineTransform] aTransform
# @param [Number] anAngle
# @return [AffineTransform]
@affineTransformRotate: (aTransform, anAngle) ->
# Create a new affine transformation with a base transformation matrix and a scale based on it.
# @param [AffineTransform] t
# @param [Number] sx
# @param [Number] sy
# @return [AffineTransform]
@affineTransformScale: (t, sx, sy) ->
# Create a new affine transformation with a base transformation matrix and a translation based on it.
# @param [AffineTransform] t
# @param [Number] tx
# @param [Number] ty
# @return [AffineTransform]
@affineTransformTranslate: (t, tx, ty) ->
# create the animate with animation
# @param [Animation] animation
# @return [Animate]
@animate: (animation) ->
# Inserts some objects at index
# @param [Array] arr
# @param [Array] addObjs
# @param [Number] index
# @return [Array]
@arrayAppendObjectsToIndex: (arr, addObjs, index) ->
# Removes from arr all values in minusArr.
# @param [Array] arr
# @param [Array] minusArr
@arrayRemoveArray: (arr, minusArr) ->
# Searches for the first occurance of object and removes it.
# @param [Array] arr
# @param [*] delObj
@arrayRemoveObject: (arr, delObj) ->
# Verify Array's Type
# @param [Array] arr
# @param [function] type
# @return [Boolean]
@arrayVerifyType: (arr, type) ->
# Function added for JS bindings compatibility.
# @param [object] jsObj
# @param [object] superclass
@associateWithNative: (jsObj, superclass) ->
# @param me
# @param opt_methodName
# @param var_args
@base: (me, opt_methodName, var_args) ->
# @param [Number] a
# @param [Number] b
# @param [Number] c
# @param [Number] d
# @param [Number] t
# @return [Number]
@bezierAt: (a, b, c, d, t) ->
# An action that moves the target with a cubic Bezier curve by a certain distance.
# @param [Number] t
# @param [Array] c
# @return [BezierBy]
@bezierBy: (t, c) ->
# An action that moves the target with a cubic Bezier curve to a destination point.
# @param [Number] t
# @param [Array] c
# @return [BezierTo]
@bezierTo: (t, c) ->
# Blend Function used for textures
# @param [Number] src1
# @param [Number] dst1
@BlendFunc: (src1, dst1) ->
# @return [BlendFunc]
@blendFuncDisable: ->
# Blinks a cc.Node object by modifying it's visible attribute.
# @param [Number] duration
# @param blinks
# @return [Blink]
@blink: (duration, blinks) ->
# Creates the action with the callback
# @param [function] selector
# @param [object|null] selectorTarget
# @param [*|null] data
# @return [CallFunc]
@callFunc: (selector, selectorTarget, data) ->
# Returns the Cardinal Spline position for a given set of control points, tension and time.
# @param [Point] p0
# @param [Point] p1
# @param [Point] p2
# @param [Point] p3
# @param [Number] tension
# @param [Number] t
# @return [Point]
@cardinalSplineAt: (p0, p1, p2, p3, tension, t) ->
# creates an action with a Cardinal Spline array of points and tension.
# @param [Number] duration
# @param [Array] points
# @param [Number] tension
# @return [CardinalSplineBy]
@cardinalSplineBy: (duration, points, tension) ->
# creates an action with a Cardinal Spline array of points and tension.
# @param [Number] duration
# @param [Array] points
# @param [Number] tension
# @return [CardinalSplineTo]
@cardinalSplineTo: (duration, points, tension) ->
# Creates an action with a Cardinal Spline array of points and tension
# @param [Number] dt
# @param [Array] points
# @return [CatmullRomBy]
@catmullRomBy: (dt, points) ->
# creates an action with a Cardinal Spline array of points and tension.
# @param [Number] dt
# @param [Array] points
# @return [CatmullRomTo]
@catmullRomTo: (dt, points) ->
# convert an affine transform object to a kmMat4 object
# @param [AffineTransform] trans
# @param [kmMat4] mat
@CGAffineToGL: (trans, mat) ->
# Check webgl error.Error will be shown in console if exists.
@checkGLErrorDebug: ->
# Clamp a value between from and to.
# @param [Number] value
# @param [Number] min_inclusive
# @param [Number] max_inclusive
# @return [Number]
@clampf: (value, min_inclusive, max_inclusive) ->
# Create a new object and copy all properties in an exist object to the new object
# @param [object|Array] obj
# @return [Array|object]
@clone: (obj) ->
# returns a new clone of the controlPoints
# @param controlPoints
# @return [Array]
@cloneControlPoints: (controlPoints) ->
# Generate a color object based on multiple forms of parameters
# @param [Number|String|cc.Color] r
# @param [Number] g
# @param [Number] b
# @param [Number] a
# @return [Color]
@color: (r, g, b, a) ->
# returns true if both ccColor3B are equal.
# @param [Color] color1
# @param [Color] color2
# @return [Boolean]
@colorEqual: (color1, color2) ->
# convert Color to a string of color for style.
# @param [Color] color
# @return [String]
@colorToHex: (color) ->
# On Mac it returns 1; On iPhone it returns 2 if RetinaDisplay is On.
# @return [Number]
@contentScaleFactor: ->
# Copy an array's item to a new array (its performance is better than Array.slice)
# @param [Array] arr
# @return [Array]
@copyArray: (arr) ->
# create a webgl context
# @param [HTMLCanvasElement] canvas
# @param [Object] opt_attribs
# @return [WebGLRenderingContext]
@create3DContext: (canvas, opt_attribs) ->
# Common getter setter configuration function
# @param [Object] proto
# @param [String] prop
# @param [function] getter
# @param [function] setter
# @param [String] getterName
# @param [String] setterName
@defineGetterSetter: (proto, prop, getter, setter, getterName, setterName) ->
# converts degrees to radians
# @param [Number] angle
# @return [Number]
@degreesToRadians: (angle) ->
# Delays the action a certain amount of seconds
# @param [Number] d
# @return [DelayTime]
@delayTime: (d) ->
# Disable default GL states: - GL_TEXTURE_2D - GL_TEXTURE_COORD_ARRAY - GL_COLOR_ARRAY
@disableDefaultGLStates: ->
# Iterate over an object or an array, executing a function for each matched element.
# @param [object|array] obj
# @param [function] iterator
# @param [object] context
@each: (obj, iterator, context) ->
# Creates the action easing object.
# @return [Object]
@easeBackIn: ->
# Creates the action easing object.
# @return [Object]
@easeBackInOut: ->
# Creates the action easing object.
# @return [Object]
@easeBackOut: ->
# Creates the action easing object.
# @param [Number] p0
# @param [Number] p1
# @param [Number] p2
# @param [Number] p3
# @return [Object]
@easeBezierAction: (p0, p1, p2, p3) ->
# Creates the action easing object.
# @return [Object]
@easeBounceIn: ->
# Creates the action easing object.
# @return [Object]
@easeBounceInOut: ->
# Creates the action easing object.
# @return [Object]
@easeBounceOut: ->
# Creates the action easing object.
# @return [Object]
@easeCircleActionIn: ->
# Creates the action easing object.
# @return [Object]
@easeCircleActionInOut: ->
# Creates the action easing object.
# @return [Object]
@easeCircleActionOut: ->
# Creates the action easing object.
# @return [Object]
@easeCubicActionIn: ->
# Creates the action easing object.
# @return [Object]
@easeCubicActionInOut: ->
# Creates the action easing object.
# @return [Object]
@easeCubicActionOut: ->
# Creates the action easing obejct with the period in radians (default is 0.3).
# @param [Number] period
# @return [Object]
@easeElasticIn: (period) ->
# Creates the action easing object with the period in radians (default is 0.3).
# @param [Number] period
# @return [Object]
@easeElasticInOut: (period) ->
# Creates the action easing object with the period in radians (default is 0.3).
# @param [Number] period
# @return [Object]
@easeElasticOut: (period) ->
# Creates the action easing object with the rate parameter.
# @return [Object]
@easeExponentialIn: ->
# creates an EaseExponentialInOut action easing object.
# @return [Object]
@easeExponentialInOut: ->
# creates the action easing object.
# @return [Object]
@easeExponentialOut: ->
# Creates the action easing object with the rate parameter.
# @param [Number] rate
# @return [Object]
@easeIn: (rate) ->
# Creates the action easing object with the rate parameter.
# @param [Number] rate
# @return [Object]
@easeInOut: (rate) ->
# Creates the action easing object with the rate parameter.
# @param [Number] rate
# @return [Object]
@easeOut: (rate) ->
# Creates the action easing object.
# @return [Object]
@easeQuadraticActionIn: ->
# Creates the action easing object.
# @return [Object]
@easeQuadraticActionInOut: ->
# Creates the action easing object.
# @return [Object]
@easeQuadraticActionOut: ->
# Creates the action easing object.
# @return [Object]
@easeQuarticActionIn: ->
# Creates the action easing object.
# @return [Object]
@easeQuarticActionInOut: ->
# Creates the action easing object.
# @return [Object]
@easeQuarticActionOut: ->
# Creates the action easing object.
# @return [Object]
@easeQuinticActionIn: ->
# Creates the action easing object.
# @return [Object]
@easeQuinticActionInOut: ->
# Creates the action easing object.
# @return [Object]
@easeQuinticActionOut: ->
# Creates the action with the inner action and the rate parameter.
# @param [ActionInterval] action
# @param [Number] rate
# @return [EaseRateAction]
@easeRateAction: (action, rate) ->
# creates an EaseSineIn action.
# @return [Object]
@easeSineIn: ->
# creates the action easing object.
# @return [Object]
@easeSineInOut: ->
# Creates an EaseSineOut action easing object.
# @return [Object]
@easeSineOut: ->
# GL states that are enabled: - GL_TEXTURE_2D - GL_VERTEX_ARRAY - GL_TEXTURE_COORD_ARRAY - GL_COLOR_ARRAY
@enableDefaultGLStates: ->
# Copy all of the properties in source objects to target object and return the target object.
# @param [object] target
# @param [object] *sources
# @return [object]
@extend: (target, *sources) ->
# Fades In an object that implements the cc.RGBAProtocol protocol.
# @param [Number] duration
# @return [FadeIn]
@fadeIn: (duration) ->
# Fades Out an object that implements the cc.RGBAProtocol protocol.
# @param [Number] d
# @return [FadeOut]
@fadeOut: (d) ->
# Creates the action with the grid size and the duration.
# @param duration
# @param gridSize
# @return [FadeOutBLTiles]
@fadeOutBLTiles: (duration, gridSize) ->
# Creates the action with the grid size and the duration.
# @param [Number] duration
# @param [Size] gridSize
# @return [FadeOutDownTiles]
@fadeOutDownTiles: (duration, gridSize) ->
# Creates the action with the grid size and the duration.
# @param duration
# @param gridSize
# @return [FadeOutTRTiles]
@fadeOutTRTiles: (duration, gridSize) ->
# Creates the action with the grid size and the duration.
# @param [Number] duration
# @param [Size] gridSize
# @return [FadeOutUpTiles]
@fadeOutUpTiles: (duration, gridSize) ->
# Fades an object that implements the cc.RGBAProtocol protocol.
# @param [Number] duration
# @param [Number] opacity
# @return [FadeTo]
@fadeTo: (duration, opacity) ->
# Create a FlipX action to flip or unflip the target.
# @param [Boolean] flip
# @return [FlipX]
@flipX: (flip) ->
# Create a Flip X 3D action with duration.
# @param [Number] duration
# @return [FlipX3D]
@flipX3D: (duration) ->
# Create a FlipY action to flip or unflip the target.
# @param [Boolean] flip
# @return [FlipY]
@flipY: (flip) ->
# Create a flip Y 3d action with duration.
# @param [Number] duration
# @return [FlipY3D]
@flipY3D: (duration) ->
# creates the action with a set boundary.
# @param [Node] followedNode
# @param [Rect] rect
# @return [Follow|Null]
@follow: (followedNode, rect) ->
# A string tool to construct a string with format string.
# @return [String]
@formatStr: ->
# Generates texture's cache for texture tint
# @param [HTMLImageElement] texture
# @return [Array]
@generateTextureCacheForColor: (texture) ->
# Generate tinted texture with lighter.
# @param [HTMLImageElement] texture
# @param [Array] tintedImgCache
# @param [Color] color
# @param [Rect] rect
# @param [HTMLCanvasElement] renderCanvas
# @return [HTMLCanvasElement]
@generateTintImage: (texture, tintedImgCache, color, rect, renderCanvas) ->
# Tint a texture using the "multiply" operation
# @param [HTMLImageElement] image
# @param [Color] color
# @param [Rect] rect
# @param [HTMLCanvasElement] renderCanvas
# @return [HTMLCanvasElement]
@generateTintImageWithMultiply: (image, color, rect, renderCanvas) ->
# returns a point from the array
# @param [Array] controlPoints
# @param [Number] pos
# @return [Array]
@getControlPointAt: (controlPoints, pos) ->
# get image format by image data
# @param [Array] imgData
# @return [Number]
@getImageFormatByData: (imgData) ->
# If the texture is not already bound, it binds it.
# @param [Texture2D] textureId
@glBindTexture2D: (textureId) ->
# If the texture is not already bound to a given unit, it binds it.
# @param [Number] textureUnit
# @param [Texture2D] textureId
@glBindTexture2DN: (textureUnit, textureId) ->
# If the vertex array is not already bound, it binds it.
# @param [Number] vaoId
@glBindVAO: (vaoId) ->
# Uses a blending function in case it not already used.
# @param [Number] sfactor
# @param [Number] dfactor
@glBlendFunc: (sfactor, dfactor) ->
# @param [Number] sfactor
# @param [Number] dfactor
@glBlendFuncForParticle: (sfactor, dfactor) ->
# Resets the blending mode back to the cached state in case you used glBlendFuncSeparate() or glBlendEquation().
@glBlendResetToCache: ->
# Deletes the GL program.
# @param [WebGLProgram] program
@glDeleteProgram: (program) ->
# It will delete a given texture.
# @param [WebGLTexture] textureId
@glDeleteTexture: (textureId) ->
# It will delete a given texture.
# @param [Number] textureUnit
# @param [WebGLTexture] textureId
@glDeleteTextureN: (textureUnit, textureId) ->
# It will enable / disable the server side GL states.
# @param [Number] flags
@glEnable: (flags) ->
# Will enable the vertex attribs that are passed as flags.
# @param [VERTEX_ATTRIB_FLAG_POSITION | cc.VERTEX_ATTRIB_FLAG_COLOR | cc.VERTEX_ATTRIB_FLAG_TEX_OORDS] flags
@glEnableVertexAttribs: (flags) ->
# Invalidates the GL state cache.
@glInvalidateStateCache: ->
# Convert a kmMat4 object to an affine transform object
# @param [kmMat4] mat
# @param [AffineTransform] trans
@GLToCGAffine: (mat, trans) ->
# Uses the GL program in case program is different than the current one.
# @param [WebGLProgram] program
@glUseProgram: (program) ->
# creates the action with size and duration
# @param [Number] duration
# @param [Size] gridSize
# @return [Grid3DAction]
@grid3DAction: (duration, gridSize) ->
# creates the action with size and duration
# @param [Number] duration
# @param [Size] gridSize
# @return [GridAction]
@gridAction: (duration, gridSize) ->
# Hash Element used for "selectors with interval"
# @param [Array] timers
# @param [Class] target
# @param [Number] timerIndex
# @param [Timer] currentTimer
# @param [Boolean] currentTimerSalvaged
# @param [Boolean] paused
# @param [Array] hh
@HashTimerEntry: (timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused, hh) ->
# ************************************************************************* Copyright (c) 2008-2010 PI:NAME:<NAME>END_PI Copyright (c) 2011-2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc.
# @param value
# @param location
# @param hh
@HashUniformEntry: (value, location, hh) ->
# convert a string of color for style to Color.
# @param [String] hex
# @return [Color]
@hexToColor: (hex) ->
# Hide the node.
# @return [Hide]
@hide: ->
# IME Keyboard Notification Info structure
# @param [Rect] begin
# @param [Rect] end
# @param [Number] duration
@IMEKeyboardNotificationInfo: (begin, end, duration) ->
# Increments the GL Draws counts by one.
# @param [Number] addNumber
@incrementGLDraws: (addNumber) ->
# Another way to subclass: Using Google Closure.
# @param [Function] childCtor
# @param [Function] parentCtor
@inherits: (childCtor, parentCtor) ->
# Check the obj whether is array or not
# @param [*] obj
# @return [boolean]
@isArray: (obj) ->
# Check the url whether cross origin
# @param [String] url
# @return [boolean]
@isCrossOrigin: (url) ->
# Check the obj whether is function or not
# @param [*] obj
# @return [boolean]
@isFunction: (obj) ->
# Check the obj whether is number or not
# @param [*] obj
# @return [boolean]
@isNumber: (obj) ->
# Check the obj whether is object or not
# @param [*] obj
# @return [boolean]
@isObject: (obj) ->
# Check the obj whether is string or not
# @param [*] obj
# @return [boolean]
@isString: (obj) ->
# Check the obj whether is undefined or not
# @param [*] obj
# @return [boolean]
@isUndefined: (obj) ->
# Moves a cc.Node object simulating a parabolic jump movement by modifying it's position attribute.
# @param [Number] duration
# @param [Point|Number] position
# @param [Number] y
# @param [Number] height
# @param [Number] jumps
# @return [JumpBy]
@jumpBy: (duration, position, y, height, jumps) ->
# creates the action with the number of jumps, the sin amplitude, the grid size and the duration.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] numberOfJumps
# @param [Number] amplitude
# @return [JumpTiles3D]
@jumpTiles3D: (duration, gridSize, numberOfJumps, amplitude) ->
# Moves a cc.Node object to a parabolic position simulating a jump movement by modifying it's position attribute.
# @param [Number] duration
# @param [Point|Number] position
# @param [Number] y
# @param [Number] height
# @param [Number] jumps
# @return [JumpTo]
@jumpTo: (duration, position, y, height, jumps) ->
# A struture that represents an axis-aligned bounding box.
# @param min
# @param max
@kmAABB: (min, max) ->
# Assigns pIn to pOut, returns pOut.
# @param pOut
# @param pIn
@kmAABBAssign: (pOut, pIn) ->
# Returns KM_TRUE if point is in the specified AABB, returns KM_FALSE otherwise.
# @param pPoint
# @param pBox
@kmAABBContainsPoint: (pPoint, pBox) ->
# Scales pIn by s, stores the resulting AABB in pOut.
# @param pOut
# @param pIn
# @param s
@kmAABBScale: (pOut, pIn, s) ->
# A 4x4 matrix mat = | 0 4 8 12 | | 1 5 9 13 | | 2 6 10 14 | | 3 7 11 15 |
@kmMat4: ->
# Returns KM_TRUE if the 2 matrices are equal (approximately)
# @param pMat1
# @param pMat2
@kmMat4AreEqual: (pMat1, pMat2) ->
# Assigns the value of pIn to pOut
# @param pOut
# @param pIn
@kmMat4Assign: (pOut, pIn) ->
# Extract a 3x3 rotation matrix from the input 4x4 transformation.
# @param pOut
# @param pIn
@kmMat4ExtractRotation: (pOut, pIn) ->
# Fills a kmMat4 structure with the values from a 16 element array of floats
# @param pOut
# @param pMat
@kmMat4Fill: (pOut, pMat) ->
# Extract the forward vector from a 4x4 matrix.
# @param pOut
# @param pIn
@kmMat4GetForwardVec3: (pOut, pIn) ->
# Extract the right vector from a 4x4 matrix.
# @param pOut
# @param pIn
@kmMat4GetRightVec3: (pOut, pIn) ->
# Get the up vector from a matrix.
# @param pOut
# @param pIn
@kmMat4GetUpVec3: (pOut, pIn) ->
# Sets pOut to an identity matrix returns pOut
# @param pOut
@kmMat4Identity: (pOut) ->
# Calculates the inverse of pM and stores the result in pOut.
# @param pOut
# @param pM
@kmMat4Inverse: (pOut, pM) ->
# Returns KM_TRUE if pIn is an identity matrix KM_FALSE otherwise
# @param pIn
@kmMat4IsIdentity: (pIn) ->
# Builds a translation matrix in the same way as gluLookAt() the resulting matrix is stored in pOut.
# @param pOut
# @param pEye
# @param pCenter
# @param pUp
@kmMat4LookAt: (pOut, pEye, pCenter, pUp) ->
# Multiplies pM1 with pM2, stores the result in pOut, returns pOut
# @param pOut
# @param pM1
# @param pM2
@kmMat4Multiply: (pOut, pM1, pM2) ->
# Creates an orthographic projection matrix like glOrtho
# @param pOut
# @param left
# @param right
# @param bottom
# @param top
# @param nearVal
# @param farVal
@kmMat4OrthographicProjection: (pOut, left, right, bottom, top, nearVal, farVal) ->
# Creates a perspective projection matrix in the same way as gluPerspective
# @param pOut
# @param fovY
# @param aspect
# @param zNear
# @param zFar
@kmMat4PerspectiveProjection: (pOut, fovY, aspect, zNear, zFar) ->
# Build a rotation matrix from an axis and an angle.
# @param pOut
# @param axis
# @param radians
@kmMat4RotationAxisAngle: (pOut, axis, radians) ->
# Builds a rotation matrix from pitch, yaw and roll.
# @param pOut
# @param pitch
# @param yaw
# @param roll
@kmMat4RotationPitchYawRoll: (pOut, pitch, yaw, roll) ->
# Converts a quaternion to a rotation matrix, the result is stored in pOut, returns pOut
# @param pOut
# @param pQ
@kmMat4RotationQuaternion: (pOut, pQ) ->
# Take the rotation from a 4x4 transformation matrix, and return it as an axis and an angle (in radians) returns the output axis.
# @param pAxis
# @param radians
# @param pIn
@kmMat4RotationToAxisAngle: (pAxis, radians, pIn) ->
# Build a 4x4 OpenGL transformation matrix using a 3x3 rotation matrix, and a 3d vector representing a translation.
# @param pOut
# @param rotation
# @param translation
@kmMat4RotationTranslation: (pOut, rotation, translation) ->
# Builds an X-axis rotation matrix and stores it in pOut, returns pOut
# @param pOut
# @param radians
@kmMat4RotationX: (pOut, radians) ->
# Builds a rotation matrix using the rotation around the Y-axis The result is stored in pOut, pOut is returned.
# @param pOut
# @param radians
@kmMat4RotationY: (pOut, radians) ->
# Builds a rotation matrix around the Z-axis.
# @param pOut
# @param radians
@kmMat4RotationZ: (pOut, radians) ->
# Builds a scaling matrix
# @param pOut
# @param x
# @param y
# @param z
@kmMat4Scaling: (pOut, x, y, z) ->
# Builds a translation matrix.
# @param pOut
# @param x
# @param y
# @param z
@kmMat4Translation: (pOut, x, y, z) ->
# Sets pOut to the transpose of pIn, returns pOut
# @param pOut
# @param pIn
@kmMat4Transpose: (pOut, pIn) ->
# Returns POINT_INFRONT_OF_PLANE if pP is infront of pIn.
# @param pIn
# @param pP
@kmPlaneClassifyPoint: (pIn, pP) ->
# Creates a plane from 3 points.
# @param pOut
# @param p1
# @param p2
# @param p3
@kmPlaneFromPoints: (pOut, p1, p2, p3) ->
# Adapted from the OGRE engine! Gets the shortest arc quaternion to rotate this vector to the destination vector.
# @param pOut
# @param vec1
# @param vec2
# @param fallback
@kmQuaternionRotationBetweenVec3: (pOut, vec1, vec2, fallback) ->
# Returns the square of s (e.g.
# @param [Number] s
@kmSQR: (s) ->
# creates a lens 3d action with center position, radius
# @param [Number] duration
# @param [Size] gridSize
# @param [Point] position
# @param [Number] radius
# @return [Lens3D]
@lens3D: (duration, gridSize, position, radius) ->
# Linear interpolation between 2 numbers, the ratio sets how much it is biased to each end
# @param [Number] a
# @param [Number] b
# @param [Number] r
@lerp: (a, b, r) ->
# creates the action with amplitude, a grid and duration
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] waves
# @param [Number] amplitude
# @return [Liquid]
@liquid: (duration, gridSize, waves, amplitude) ->
# Create the action.
# @param [Number] duration
# @param [Point|Number] deltaPos
# @param [Number] deltaY
# @return [MoveBy]
@moveBy: (duration, deltaPos, deltaY) ->
# Create new action.
# @param [Number] duration
# @param [Point] position
# @param [Number] y
# @return [MoveBy]
@moveTo: (duration, position, y) ->
# @param [Number] x
# @return [Number]
@NextPOT: (x) ->
# Helpful macro that setups the GL server state, the correct GL program and sets the Model View Projection matrix
# @param [Node] node
@nodeDrawSetup: (node) ->
# Helper function that creates a cc.Point.
# @param [Number|cc.Point] x
# @param [Number] y
# @return [Point]
@p: (x, y) ->
# Calculates sum of two points.
# @param [Point] v1
# @param [Point] v2
# @return [Point]
@pAdd: (v1, v2) ->
# adds one point to another (inplace)
# @param [Point] v1
# @param [point] v2
@pAddIn: (v1, v2) ->
# create PageTurn3D action
# @param [Number] duration
# @param [Size] gridSize
# @return [PageTurn3D]
@pageTurn3D: (duration, gridSize) ->
# @param [Point] a
# @param [Point] b
# @return [Number]
@pAngle: (a, b) ->
# @param [Point] a
# @param [Point] b
# @return [Number]
@pAngleSigned: (a, b) ->
# Clamp a point between from and to.
# @param [Point] p
# @param [Number] min_inclusive
# @param [Number] max_inclusive
# @return [Point]
@pClamp: (p, min_inclusive, max_inclusive) ->
# Multiplies a nd b components, a.x*b.x, a.y*b.y
# @param [Point] a
# @param [Point] b
# @return [Point]
@pCompMult: (a, b) ->
# Run a math operation function on each point component Math.abs, Math.fllor, Math.ceil, Math.round.
# @param [Point] p
# @param [Function] opFunc
# @return [Point]
@pCompOp: (p, opFunc) ->
# Calculates cross product of two points.
# @param [Point] v1
# @param [Point] v2
# @return [Number]
@pCross: (v1, v2) ->
# Calculates the distance between two points
# @param [Point] v1
# @param [Point] v2
# @return [Number]
@pDistance: (v1, v2) ->
# Calculates the square distance between two points (not calling sqrt() )
# @param [Point] point1
# @param [Point] point2
# @return [Number]
@pDistanceSQ: (point1, point2) ->
# Calculates dot product of two points.
# @param [Point] v1
# @param [Point] v2
# @return [Number]
@pDot: (v1, v2) ->
# Converts radians to a normalized vector.
# @param [Number] a
# @return [Point]
@pForAngle: (a) ->
# Quickly convert cc.Size to a cc.Point
# @param [Size] s
# @return [Point]
@pFromSize: (s) ->
# @param [Point] a
# @param [Point] b
# @param [Number] variance
# @return [Boolean]
@pFuzzyEqual: (a, b, variance) ->
# copies the position of one point to another
# @param [Point] v1
# @param [Point] v2
@pIn: (v1, v2) ->
# ccpIntersectPoint return the intersection point of line A-B, C-D
# @param [Point] A
# @param [Point] B
# @param [Point] C
# @param [Point] D
# @return [Point]
@pIntersectPoint: (A, B, C, D) ->
# Creates a Place action with a position.
# @param [Point|Number] pos
# @param [Number] y
# @return [Place]
@place: (pos, y) ->
# Calculates distance between point an origin
# @param [Point] v
# @return [Number]
@pLength: (v) ->
# Calculates the square length of a cc.Point (not calling sqrt() )
# @param [Point] v
# @return [Number]
@pLengthSQ: (v) ->
# Linear Interpolation between two points a and b alpha == 0 ? a alpha == 1 ? b otherwise a value between a.
# @param [Point] a
# @param [Point] b
# @param [Number] alpha
# @return [pAdd]
@pLerp: (a, b, alpha) ->
# A general line-line intersection test indicating successful intersection of a line note that to truly test intersection for segments we have to make sure that s & t lie within [0.
# @param [Point] A
# @param [Point] B
# @param [Point] C
# @param [Point] D
# @param [Point] retP
# @return [Boolean]
@pLineIntersect: (A, B, C, D, retP) ->
# Calculates midpoint between two points.
# @param [Point] v1
# @param [Point] v2
# @return [pMult]
@pMidpoint: (v1, v2) ->
# Returns point multiplied by given factor.
# @param [Point] point
# @param [Number] floatVar
# @return [Point]
@pMult: (point, floatVar) ->
# multiplies the point with the given factor (inplace)
# @param [Point] point
# @param [Number] floatVar
@pMultIn: (point, floatVar) ->
# Returns opposite of point.
# @param [Point] point
# @return [Point]
@pNeg: (point) ->
# Returns point multiplied to a length of 1.
# @param [Point] v
# @return [Point]
@pNormalize: (v) ->
# normalizes the point (inplace)
# @param
@pNormalizeIn: ->
# Apply the affine transformation on a point.
# @param [Point] point
# @param [AffineTransform] t
# @return [Point]
@pointApplyAffineTransform: (point, t) ->
# Check whether a point's value equals to another
# @param [Point] point1
# @param [Point] point2
# @return [Boolean]
@pointEqualToPoint: (point1, point2) ->
# Converts a Point in pixels to points
# @param [Rect] pixels
# @return [Point]
@pointPixelsToPoints: (pixels) ->
# Converts a Point in points to pixels
# @param [Point] points
# @return [Point]
@pointPointsToPixels: (points) ->
# Calculates perpendicular of v, rotated 90 degrees counter-clockwise -- cross(v, perp(v)) = 0
# @param [Point] point
# @return [Point]
@pPerp: (point) ->
# Calculates the projection of v1 over v2.
# @param [Point] v1
# @param [Point] v2
# @return [pMult]
@pProject: (v1, v2) ->
# Creates and initializes the action with a duration, a "from" percentage and a "to" percentage
# @param [Number] duration
# @param [Number] fromPercentage
# @param [Number] toPercentage
# @return [ProgressFromTo]
@progressFromTo: (duration, fromPercentage, toPercentage) ->
# Creates and initializes with a duration and a percent
# @param [Number] duration
# @param [Number] percent
# @return [ProgressTo]
@progressTo: (duration, percent) ->
# Rotates two points.
# @param [Point] v1
# @param [Point] v2
# @return [Point]
@pRotate: (v1, v2) ->
# Rotates a point counter clockwise by the angle around a pivot
# @param [Point] v
# @param [Point] pivot
# @param [Number] angle
# @return [Point]
@pRotateByAngle: (v, pivot, angle) ->
# Calculates perpendicular of v, rotated 90 degrees clockwise -- cross(v, rperp(v))
# @param [Point] point
# @return [Point]
@pRPerp: (point) ->
# check to see if both points are equal
# @param [Point] A
# @param [Point] B
# @return [Boolean]
@pSameAs: (A, B) ->
# ccpSegmentIntersect return YES if Segment A-B intersects with segment C-D.
# @param [Point] A
# @param [Point] B
# @param [Point] C
# @param [Point] D
# @return [Boolean]
@pSegmentIntersect: (A, B, C, D) ->
# Calculates difference of two points.
# @param [Point] v1
# @param [Point] v2
# @return [Point]
@pSub: (v1, v2) ->
# subtracts one point from another (inplace)
# @param [Point] v1
# @param
@pSubIn: (v1, ) ->
# Converts a vector to radians.
# @param [Point] v
# @return [Number]
@pToAngle: (v) ->
# Unrotates two points.
# @param [Point] v1
# @param [Point] v2
# @return [Point]
@pUnrotate: (v1, v2) ->
# sets the position of the point to 0
# @param [Point] v
@pZeroIn: (v) ->
# converts radians to degrees
# @param [Number] angle
# @return [Number]
@radiansToDegrees: (angle) ->
# converts radians to degrees
# @param [Number] angle
# @return [Number]
@radiansToDegress: (angle) ->
# get a random number from 0 to 0xffffff
# @return [number]
@rand: ->
# returns a random float between 0 and 1
# @return [Number]
@random0To1: ->
# returns a random float between -1 and 1
# @return [Number]
@randomMinus1To1: ->
# Helper function that creates a cc.Rect.
# @param [Number|cc.Rect] x
# @param [Number] y
# @param [Number] w
# @param [Number] h
# @return [Rect]
@rect: (x, y, w, h) ->
# Apply the affine transformation on a rect.
# @param [Rect] rect
# @param [AffineTransform] anAffineTransform
# @return [Rect]
@rectApplyAffineTransform: (rect, anAffineTransform) ->
# Check whether a rect contains a point
# @param [Rect] rect
# @param [Point] point
# @return [Boolean]
@rectContainsPoint: (rect, point) ->
# Check whether the rect1 contains rect2
# @param [Rect] rect1
# @param [Rect] rect2
# @return [Boolean]
@rectContainsRect: (rect1, rect2) ->
# Check whether a rect's value equals to another
# @param [Rect] rect1
# @param [Rect] rect2
# @return [Boolean]
@rectEqualToRect: (rect1, rect2) ->
# Returns the rightmost x-value of a rect
# @param [Rect] rect
# @return [Number]
@rectGetMaxX: (rect) ->
# Return the topmost y-value of a rect
# @param [Rect] rect
# @return [Number]
@rectGetMaxY: (rect) ->
# Return the midpoint x-value of a rect
# @param [Rect] rect
# @return [Number]
@rectGetMidX: (rect) ->
# Return the midpoint y-value of `rect'
# @param [Rect] rect
# @return [Number]
@rectGetMidY: (rect) ->
# Returns the leftmost x-value of a rect
# @param [Rect] rect
# @return [Number]
@rectGetMinX: (rect) ->
# Return the bottommost y-value of a rect
# @param [Rect] rect
# @return [Number]
@rectGetMinY: (rect) ->
# Returns the overlapping portion of 2 rectangles
# @param [Rect] rectA
# @param [Rect] rectB
# @return [Rect]
@rectIntersection: (rectA, rectB) ->
# Check whether a rect intersect with another
# @param [Rect] rectA
# @param [Rect] rectB
# @return [Boolean]
@rectIntersectsRect: (rectA, rectB) ->
# Check whether a rect overlaps another
# @param [Rect] rectA
# @param [Rect] rectB
# @return [Boolean]
@rectOverlapsRect: (rectA, rectB) ->
# Converts a rect in pixels to points
# @param [Rect] pixel
# @return [Rect]
@rectPixelsToPoints: (pixel) ->
# Converts a rect in points to pixels
# @param [Rect] point
# @return [Rect]
@rectPointsToPixels: (point) ->
# Returns the smallest rectangle that contains the two source rectangles.
# @param [Rect] rectA
# @param [Rect] rectB
# @return [Rect]
@rectUnion: (rectA, rectB) ->
# Create a RemoveSelf object with a flag indicate whether the target should be cleaned up while removing.
# @param [Boolean] isNeedCleanUp
# @return [RemoveSelf]
@removeSelf: (isNeedCleanUp) ->
# Creates a Repeat action.
# @param [FiniteTimeAction] action
# @param [Number] times
# @return [Repeat]
@repeat: (action, times) ->
# Create a acton which repeat forever
# @param [FiniteTimeAction] action
# @return [RepeatForever]
@repeatForever: (action) ->
# creates an action with the number of times that the current grid will be reused
# @param [Number] times
# @return [ReuseGrid]
@reuseGrid: (times) ->
# returns a new copy of the array reversed.
# @param controlPoints
# @return [Array]
@reverseControlPoints: (controlPoints) ->
# reverse the current control point array inline, without generating a new one
# @param controlPoints
@reverseControlPointsInline: (controlPoints) ->
# Executes an action in reverse order, from time=duration to time=0.
# @param [FiniteTimeAction] action
# @return [ReverseTime]
@reverseTime: (action) ->
# creates a ripple 3d action with radius, number of waves, amplitude
# @param [Number] duration
# @param [Size] gridSize
# @param [Point] position
# @param [Number] radius
# @param [Number] waves
# @param [Number] amplitude
# @return [Ripple3D]
@ripple3D: (duration, gridSize, position, radius, waves, amplitude) ->
# Rotates a cc.Node object clockwise a number of degrees by modifying it's rotation attribute.
# @param [Number] duration
# @param [Number] deltaAngleX
# @param [Number] deltaAngleY
# @return [RotateBy]
@rotateBy: (duration, deltaAngleX, deltaAngleY) ->
# Creates a RotateTo action with separate rotation angles.
# @param [Number] duration
# @param [Number] deltaAngleX
# @param [Number] deltaAngleY
# @return [RotateTo]
@rotateTo: (duration, deltaAngleX, deltaAngleY) ->
# Scales a cc.Node object a zoom factor by modifying it's scale attribute.
# @param [Number] duration
# @param [Number] sx
# @param [Number|Null] sy
# @return [ScaleBy]
@scaleBy: (duration, sx, sy) ->
# Scales a cc.Node object to a zoom factor by modifying it's scale attribute.
# @param [Number] duration
# @param [Number] sx
# @param [Number] sy
# @return [ScaleTo]
@scaleTo: (duration, sx, sy) ->
# helper constructor to create an array of sequenceable actions
# @param [Array|cc.FiniteTimeAction] tempArray
# @return [Sequence]
@sequence: (tempArray) ->
# @param [Number] sfactor
# @param [Number] dfactor
@setBlending: (sfactor, dfactor) ->
# Sets the shader program for this node Since v2.0, each rendering node must set its shader program.
# @param [Node] node
# @param [GLProgram] program
@setProgram: (node, program) ->
# sets the projection matrix as dirty
@setProjectionMatrixDirty: ->
# creates the action with a range, shake Z vertices, a grid and duration
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] range
# @param [Boolean] shakeZ
# @return [Shaky3D]
@shaky3D: (duration, gridSize, range, shakeZ) ->
# Creates the action with a range, whether or not to shake Z vertices, a grid size, and duration.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] range
# @param [Boolean] shakeZ
# @return [ShakyTiles3D]
@shakyTiles3D: (duration, gridSize, range, shakeZ) ->
# Creates the action with a range, whether of not to shatter Z vertices, a grid size and duration.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] range
# @param [Boolean] shatterZ
# @return [ShatteredTiles3D]
@shatteredTiles3D: (duration, gridSize, range, shatterZ) ->
# Show the Node.
# @return [Show]
@show: ->
# Creates the action with a random seed, the grid size and the duration.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] seed
# @return [ShuffleTiles]
@shuffleTiles: (duration, gridSize, seed) ->
# Helper function that creates a cc.Size.
# @param [Number|cc.Size] w
# @param [Number] h
# @return [Size]
@size: (w, h) ->
# Apply the affine transformation on a size.
# @param [Size] size
# @param [AffineTransform] t
# @return [Size]
@sizeApplyAffineTransform: (size, t) ->
# Check whether a point's value equals to another
# @param [Size] size1
# @param [Size] size2
# @return [Boolean]
@sizeEqualToSize: (size1, size2) ->
# Converts a size in pixels to points
# @param [Size] sizeInPixels
# @return [Size]
@sizePixelsToPoints: (sizeInPixels) ->
# Converts a Size in points to pixels
# @param [Size] sizeInPoints
# @return [Size]
@sizePointsToPixels: (sizeInPoints) ->
# Skews a cc.Node object by skewX and skewY degrees.
# @param [Number] t
# @param [Number] sx
# @param [Number] sy
# @return [SkewBy]
@skewBy: (t, sx, sy) ->
# Create new action.
# @param [Number] t
# @param [Number] sx
# @param [Number] sy
# @return [SkewTo]
@skewTo: (t, sx, sy) ->
# Create a spawn action which runs several actions in parallel.
# @param [Array|cc.FiniteTimeAction] tempArray
# @return [FiniteTimeAction]
@spawn: (tempArray) ->
# creates the speed action.
# @param [ActionInterval] action
# @param [Number] speed
# @return [Speed]
@speed: (action, speed) ->
# creates the action with the number of columns to split and the duration.
# @param [Number] duration
# @param [Number] cols
# @return [SplitCols]
@splitCols: (duration, cols) ->
# creates the action with the number of rows to split and the duration.
# @param [Number] duration
# @param [Number] rows
# @return [SplitRows]
@splitRows: (duration, rows) ->
# Allocates and initializes the action
# @return [StopGrid]
@stopGrid: ->
# simple macro that swaps 2 variables modified from c++ macro, you need to pass in the x and y variables names in string, and then a reference to the whole object as third variable
# @param [String] x
# @param [String] y
# @param [Object] ref
@swap: (x, y, ref) ->
# Create an action with the specified action and forced target
# @param [Node] target
# @param [FiniteTimeAction] action
# @return [TargetedAction]
@targetedAction: (target, action) ->
# Helper macro that creates an Tex2F type: A texcoord composed of 2 floats: u, y
# @param [Number] u
# @param [Number] v
# @return [Tex2F]
@tex2: (u, v) ->
# releases the memory used for the image
# @param [ImageTGA] psInfo
@tgaDestroy: (psInfo) ->
# ImageTGA Flip
# @param [ImageTGA] psInfo
@tgaFlipImage: (psInfo) ->
# load the image header field from stream.
# @param [Array] buffer
# @param [Number] bufSize
# @param [ImageTGA] psInfo
# @return [Boolean]
@tgaLoadHeader: (buffer, bufSize, psInfo) ->
# loads the image pixels.
# @param [Array] buffer
# @param [Number] bufSize
# @param [ImageTGA] psInfo
# @return [Boolean]
@tgaLoadImageData: (buffer, bufSize, psInfo) ->
# Load RLE image data
# @param buffer
# @param bufSize
# @param psInfo
# @return [boolean]
@tgaLoadRLEImageData: (buffer, bufSize, psInfo) ->
# converts RGB to grayscale
# @param [ImageTGA] psInfo
@tgaRGBtogreyscale: (psInfo) ->
# Creates the action with duration and grid size
# @param [Number] duration
# @param [Size] gridSize
# @return [TiledGrid3DAction]
@tiledGrid3DAction: (duration, gridSize) ->
# Tints a cc.Node that implements the cc.NodeRGB protocol from current tint to a custom one.
# @param [Number] duration
# @param [Number] deltaRed
# @param [Number] deltaGreen
# @param [Number] deltaBlue
# @return [TintBy]
@tintBy: (duration, deltaRed, deltaGreen, deltaBlue) ->
# Tints a cc.Node that implements the cc.NodeRGB protocol from current tint to a custom one.
# @param [Number] duration
# @param [Number] red
# @param [Number] green
# @param [Number] blue
# @return [TintTo]
@tintTo: (duration, red, green, blue) ->
# Toggles the visibility of a node.
# @return [ToggleVisibility]
@toggleVisibility: ->
# Creates the action with a random seed, the grid size and the duration.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number|Null] seed
# @return [TurnOffTiles]
@turnOffTiles: (duration, gridSize, seed) ->
# creates the action with center position, number of twirls, amplitude, a grid size and duration
# @param [Number] duration
# @param [Size] gridSize
# @param [Point] position
# @param [Number] twirls
# @param [Number] amplitude
# @return [Twirl]
@twirl: (duration, gridSize, position, twirls, amplitude) ->
# Code copied & pasted from SpacePatrol game https://github.com/slembcke/SpacePatrol Renamed and added some changes for cocos2d
@v2fzero: ->
# Helper macro that creates an Vertex2F type composed of 2 floats: x, y
# @param [Number] x
# @param [Number] y
# @return [Vertex2F]
@vertex2: (x, y) ->
# Helper macro that creates an Vertex3F type composed of 3 floats: x, y, z
# @param [Number] x
# @param [Number] y
# @param [Number] z
# @return [Vertex3F]
@vertex3: (x, y, z) ->
# returns whether or not the line intersects
# @param [Number] Ax
# @param [Number] Ay
# @param [Number] Bx
# @param [Number] By
# @param [Number] Cx
# @param [Number] Cy
# @param [Number] Dx
# @param [Number] Dy
# @return [Object]
@vertexLineIntersect: (Ax, Ay, Bx, By, Cx, Cy, Dx, Dy) ->
# converts a line to a polygon
# @param [Float32Array] points
# @param [Number] stroke
# @param [Float32Array] vertices
# @param [Number] offset
# @param [Number] nuPoints
@vertexLineToPolygon: (points, stroke, vertices, offset, nuPoints) ->
# returns wheter or not polygon defined by vertex list is clockwise
# @param [Array] verts
# @return [Boolean]
@vertexListIsClockwise: (verts) ->
# initializes the action with amplitude, horizontal sin, vertical sin, a grid and duration
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] waves
# @param [Number] amplitude
# @param [Boolean] horizontal
# @param [Boolean] vertical
# @return [Waves]
@waves: (duration, gridSize, waves, amplitude, horizontal, vertical) ->
# Create a wave 3d action with duration, grid size, waves and amplitude.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] waves
# @param [Number] amplitude
@waves3D: (duration, gridSize, waves, amplitude) ->
# creates the action with a number of waves, the waves amplitude, the grid size and the duration.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] waves
# @param [Number] amplitude
# @return [WavesTiles3D]
@wavesTiles3D: (duration, gridSize, waves, amplitude) ->
# cc.Acceleration
# @param [Number] x
# @param [Number] y
# @param [Number] z
# @param [Number] timestamp
# @return [Acceleration]
@Acceleration: (x, y, z, timestamp) ->
# Base class for cc.Action objects.
# @return [Action]
@Action: ->
# Base class for Easing actions
# @param [ActionInterval] action
# @return [ActionEase]
@ActionEase: (action) ->
# Instant actions are immediate actions.
# @return [ActionInstant]
@ActionInstant: ->
# An interval action is an action that takes place within a certain period of time.
# @param [Number] d
# @return [ActionInterval]
@ActionInterval: (d) ->
# cc.ActionManager is a class that can manage actions.
# @return [ActionManager]
@ActionManager: ->
# cc.ActionTween cc.ActionTween is an action that lets you update any property of an object.
# @param [Number] duration
# @param [String] key
# @param [Number] from
# @param [Number] to
# @return [ActionTween]
@ActionTween: (duration, key, from, to) ->
# @return [ActionTweenDelegate]
@ActionTweenDelegate: ->
# cc.AffineTransform
# @param [Number] a
# @param [Number] b
# @param [Number] c
# @param [Number] d
# @param [Number] tx
# @param [Number] ty
# @return [AffineTransform]
@AffineTransform: (a, b, c, d, tx, ty) ->
# Animates a sprite given the name of an Animation
# @param [Animation] animation
# @return [Animate]
@Animate: (animation) ->
# A cc.Animation object is used to perform animations on the cc.Sprite objects.
# @param [Array] frames
# @param [Number] delay
# @param [Number] loops
# @return [Animation]
@Animation: (frames, delay, loops) ->
# cc.animationCache is a singleton object that manages the Animations.
# @return [animationCache]
@animationCache: ->
# cc.AnimationFrame A frame of the animation.
# @param spriteFrame
# @param delayUnits
# @param userInfo
# @return [AnimationFrame]
@AnimationFrame: (spriteFrame, delayUnits, userInfo) ->
# Array for object sorting utils
# @return [ArrayForObjectSorting]
@ArrayForObjectSorting: ->
# @return [async]
@async: ->
# Async Pool class, a helper of cc.async
# @param [Object|Array] srcObj
# @param [Number] limit
# @param [function] iterator
# @param [function] onEnd
# @param [object] target
# @return [AsyncPool]
@AsyncPool: (srcObj, limit, iterator, onEnd, target) ->
# cc.AtlasNode is a subclass of cc.Node, it knows how to render a TextureAtlas object.
# @param [String] tile
# @param [Number] tileWidth
# @param [Number] tileHeight
# @param [Number] itemsToRender
# @return [AtlasNode]
@AtlasNode: (tile, tileWidth, tileHeight, itemsToRender) ->
# cc.audioEngine is the singleton object, it provide simple audio APIs.
# @return [audioEngine]
@audioEngine: ->
# An action that moves the target with a cubic Bezier curve by a certain distance.
# @param [Number] t
# @param [Array] c
# @return [BezierBy]
@BezierBy: (t, c) ->
# An action that moves the target with a cubic Bezier curve to a destination point.
# @param [Number] t
# @param [Array] c
# @return [BezierTo]
@BezierTo: (t, c) ->
# Binary Stream Reader
# @param binaryData
# @return [BinaryStreamReader]
@BinaryStreamReader: (binaryData) ->
# Blinks a cc.Node object by modifying it's visible attribute
# @param [Number] duration
# @param [Number] blinks
# @return [Blink]
@Blink: (duration, blinks) ->
# Calls a 'callback'.
# @param [function] selector
# @param [object|null] selectorTarget
# @param [*|null] data
# @return [CallFunc]
@CallFunc: (selector, selectorTarget, data) ->
# Cardinal Spline path.
# @param [Number] duration
# @param [Array] points
# @param [Number] tension
# @return [CardinalSplineBy]
@CardinalSplineBy: (duration, points, tension) ->
# Cardinal Spline path.
# @param [Number] duration
# @param [Array] points
# @param [Number] tension
# @return [CardinalSplineTo]
@CardinalSplineTo: (duration, points, tension) ->
# An action that moves the target with a CatmullRom curve by a certain distance.
# @param [Number] dt
# @param [Array] points
# @return [CatmullRomBy]
@CatmullRomBy: (dt, points) ->
# An action that moves the target with a CatmullRom curve to a destination point.
# @param [Number] dt
# @param [Array] points
# @return [CatmullRomTo]
@CatmullRomTo: (dt, points) ->
# The base Class implementation (does nothing)
# @return [Class]
@Class: ->
# cc.ClippingNode is a subclass of cc.Node.
# @param [Node] stencil
# @return [ClippingNode]
@ClippingNode: (stencil) ->
# cc.Color
# @param [Number] r
# @param [Number] g
# @param [Number] b
# @param [Number] a
# @return [Color]
@Color: (r, g, b, a) ->
# The base class of component in CocoStudio
# @return [Component]
@Component: ->
# The component container for Cocostudio, it has some components.
# @return [ComponentContainer]
@ComponentContainer: ->
# cc.configuration is a singleton object which contains some openGL variables
# @return [configuration]
@configuration: ->
# cc.ContainerStrategy class is the root strategy class of container's scale strategy, it controls the behavior of how to scale the cc.container and cc._canvas object
# @return [ContainerStrategy]
@ContainerStrategy: ->
# cc.ContentStrategy class is the root strategy class of content's scale strategy, it controls the behavior of how to scale the scene and setup the viewport for the game
# @return [ContentStrategy]
@ContentStrategy: ->
# CCControl is inspired by the UIControl API class from the UIKit library of CocoaTouch.
# @return [Control]
@Control: ->
# CCControlButton: Button control for Cocos2D.
# @return [ControlButton]
@ControlButton: ->
# ControlColourPicker: color picker ui component.
# @return [ControlColourPicker]
@ControlColourPicker: ->
# ControlHuePicker: HUE picker ui component.
# @return [ControlHuePicker]
@ControlHuePicker: ->
# CCControlPotentiometer: Potentiometer control for Cocos2D.
# @return [ControlPotentiometer]
@ControlPotentiometer: ->
# ControlSaturationBrightnessPicker: Saturation brightness picker ui component.
# @return [ControlSaturationBrightnessPicker]
@ControlSaturationBrightnessPicker: ->
# ControlSlider: Slider ui component.
# @return [ControlSlider]
@ControlSlider: ->
# ControlStepper: Stepper ui component.
# @return [ControlStepper]
@ControlStepper: ->
# CCControlSwitch: Switch control ui component
# @return [ControlSwitch]
@ControlSwitch: ->
# ControlSwitchSprite: Sprite switch control ui component
# @return [ControlSwitchSprite]
@ControlSwitchSprite: ->
# Delays the action a certain amount of seconds
# @return [DelayTime]
@DelayTime: ->
# ATTENTION: USE cc.director INSTEAD OF cc.Director.
# @return [Director]
@Director: ->
# CCDrawNode Node that draws dots, segments and polygons.
# @return [DrawNode]
@DrawNode: ->
# cc.EaseBackIn action.
# @return [EaseBackIn]
@EaseBackIn: ->
# cc.EaseBackInOut action.
# @return [EaseBackInOut]
@EaseBackInOut: ->
# cc.EaseBackOut action.
# @return [EaseBackOut]
@EaseBackOut: ->
# cc.EaseBezierAction action.
# @param [Action] action
# @return [EaseBezierAction]
@EaseBezierAction: (action) ->
# cc.EaseBounce abstract class.
# @return [EaseBounce]
@EaseBounce: ->
# cc.EaseBounceIn action.
# @return [EaseBounceIn]
@EaseBounceIn: ->
# cc.EaseBounceInOut action.
# @return [EaseBounceInOut]
@EaseBounceInOut: ->
# cc.EaseBounceOut action.
# @return [EaseBounceOut]
@EaseBounceOut: ->
# cc.EaseCircleActionIn action.
# @return [EaseCircleActionIn]
@EaseCircleActionIn: ->
# cc.EaseCircleActionInOut action.
# @return [EaseCircleActionInOut]
@EaseCircleActionInOut: ->
# cc.EaseCircleActionOut action.
# @return [EaseCircleActionOut]
@EaseCircleActionOut: ->
# cc.EaseCubicActionIn action.
# @return [EaseCubicActionIn]
@EaseCubicActionIn: ->
# cc.EaseCubicActionInOut action.
# @return [EaseCubicActionInOut]
@EaseCubicActionInOut: ->
# cc.EaseCubicActionOut action.
# @return [EaseCubicActionOut]
@EaseCubicActionOut: ->
# Ease Elastic abstract class.
# @param [ActionInterval] action
# @param [Number] period
# @return [EaseElastic]
@EaseElastic: (action, period) ->
# Ease Elastic In action.
# @return [EaseElasticIn]
@EaseElasticIn: ->
# Ease Elastic InOut action.
# @return [EaseElasticInOut]
@EaseElasticInOut: ->
# Ease Elastic Out action.
# @return [EaseElasticOut]
@EaseElasticOut: ->
# cc.Ease Exponential In.
# @return [EaseExponentialIn]
@EaseExponentialIn: ->
# Ease Exponential InOut.
# @return [EaseExponentialInOut]
@EaseExponentialInOut: ->
# Ease Exponential Out.
# @return [EaseExponentialOut]
@EaseExponentialOut: ->
# cc.EaseIn action with a rate.
# @return [EaseIn]
@EaseIn: ->
# cc.EaseInOut action with a rate.
# @return [EaseInOut]
@EaseInOut: ->
# cc.EaseOut action with a rate.
# @return [EaseOut]
@EaseOut: ->
# cc.EaseQuadraticActionIn action.
# @return [EaseQuadraticActionIn]
@EaseQuadraticActionIn: ->
# cc.EaseQuadraticActionInOut action.
# @return [EaseQuadraticActionInOut]
@EaseQuadraticActionInOut: ->
# cc.EaseQuadraticActionIn action.
# @return [EaseQuadraticActionOut]
@EaseQuadraticActionOut: ->
# cc.EaseQuarticActionIn action.
# @return [EaseQuarticActionIn]
@EaseQuarticActionIn: ->
# cc.EaseQuarticActionInOut action.
# @return [EaseQuarticActionInOut]
@EaseQuarticActionInOut: ->
# cc.EaseQuarticActionOut action.
# @return [EaseQuarticActionOut]
@EaseQuarticActionOut: ->
# cc.EaseQuinticActionIn action.
# @return [EaseQuinticActionIn]
@EaseQuinticActionIn: ->
# cc.EaseQuinticActionInOut action.
# @return [EaseQuinticActionInOut]
@EaseQuinticActionInOut: ->
# cc.EaseQuinticActionOut action.
# @return [EaseQuinticActionOut]
@EaseQuinticActionOut: ->
# Base class for Easing actions with rate parameters
# @param [ActionInterval] action
# @param [Number] rate
# @return [EaseRateAction]
@EaseRateAction: (action, rate) ->
# Ease Sine In.
# @return [EaseSineIn]
@EaseSineIn: ->
# Ease Sine InOut.
# @return [EaseSineInOut]
@EaseSineInOut: ->
# Ease Sine Out.
# @return [EaseSineOut]
@EaseSineOut: ->
# cc.EditBox is a brief Class for edit box.
# @return [EditBox]
@EditBox: ->
# @return [EditBoxDelegate]
@EditBoxDelegate: ->
# Base class of all kinds of events.
# @return [Event]
@Event: ->
# The Custom event
# @return [EventCustom]
@EventCustom: ->
# The widget focus event.
# @return [EventFocus]
@EventFocus: ->
# The base class of event listener.
# @return [EventListener]
@EventListener: ->
# cc.eventManager is a singleton object which manages event listener subscriptions and event dispatching.
# @return [eventManager]
@eventManager: ->
# The mouse event
# @return [EventMouse]
@EventMouse: ->
# The touch event
# @return [EventTouch]
@EventTouch: ->
# Fades In an object that implements the cc.RGBAProtocol protocol.
# @param [Number] duration
# @return [FadeIn]
@FadeIn: (duration) ->
# Fades Out an object that implements the cc.RGBAProtocol protocol.
# @param [Number] duration
# @return [FadeOut]
@FadeOut: (duration) ->
# cc.FadeOutBLTiles action.
# @return [FadeOutBLTiles]
@FadeOutBLTiles: ->
# cc.FadeOutDownTiles action.
# @return [FadeOutDownTiles]
@FadeOutDownTiles: ->
# cc.FadeOutTRTiles action.
# @return [FadeOutTRTiles]
@FadeOutTRTiles: ->
# cc.FadeOutUpTiles action.
# @return [FadeOutUpTiles]
@FadeOutUpTiles: ->
# Fades an object that implements the cc.RGBAProtocol protocol.
# @param [Number] duration
# @param [Number] opacity
# @return [FadeTo]
@FadeTo: (duration, opacity) ->
# Base class actions that do have a finite time duration.
# @return [FiniteTimeAction]
@FiniteTimeAction: ->
# Flips the sprite horizontally.
# @param [Boolean] flip
# @return [FlipX]
@FlipX: (flip) ->
# cc.FlipX3D action.
# @param [Number] duration
# @return [FlipX3D]
@FlipX3D: (duration) ->
# Flips the sprite vertically
# @param [Boolean] flip
# @return [FlipY]
@FlipY: (flip) ->
# cc.FlipY3D action.
# @param [Number] duration
# @return [FlipY3D]
@FlipY3D: (duration) ->
# cc.Follow is an action that "follows" a node.
# @param [Node] followedNode
# @param [Rect] rect
# @return [Follow]
@Follow: (followedNode, rect) ->
# cc.FontDefinition
# @return [FontDefinition]
@FontDefinition: ->
# An object to boot the game.
# @return [game]
@game: ->
# Class that implements a WebGL program
# @return [GLProgram]
@GLProgram: ->
# FBO class that grabs the the contents of the screen
# @return [Grabber]
@Grabber: ->
# cc.Grid3D is a 3D grid implementation.
# @return [Grid3D]
@Grid3D: ->
# Base class for cc.Grid3D actions.
# @return [Grid3DAction]
@Grid3DAction: ->
# Base class for Grid actions
# @param [Number] duration
# @param [Size] gridSize
# @return [GridAction]
@GridAction: (duration, gridSize) ->
# Base class for cc.Grid
# @return [GridBase]
@GridBase: ->
# @return [HashElement]
@HashElement: ->
# Hide the node.
# @return [Hide]
@Hide: ->
# TGA format
# @param [Number] status
# @param [Number] type
# @param [Number] pixelDepth
# @param [Number] width
# @param [Number] height
# @param [Array] imageData
# @param [Number] flipped
# @return [ImageTGA]
@ImageTGA: (status, type, pixelDepth, width, height, imageData, flipped) ->
# Input method editor delegate.
# @return [IMEDelegate]
@IMEDelegate: ->
# cc.imeDispatcher is a singleton object which manage input message dispatching.
# @return [imeDispatcher]
@imeDispatcher: ->
# This class manages all events of input.
# @return [inputManager]
@inputManager: ->
# An Invocation class
# @return [Invocation]
@Invocation: ->
# Moves a cc.Node object simulating a parabolic jump movement by modifying it's position attribute.
# @param [Number] duration
# @param [Point|Number] position
# @param [Number] y
# @param [Number] height
# @param [Number] jumps
# @return [JumpBy]
@JumpBy: (duration, position, y, height, jumps) ->
# cc.JumpTiles3D action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] numberOfJumps
# @param [Number] amplitude
# @return [JumpTiles3D]
@JumpTiles3D: (duration, gridSize, numberOfJumps, amplitude) ->
# Moves a cc.Node object to a parabolic position simulating a jump movement by modifying it's position attribute.
# @param [Number] duration
# @param [Point|Number] position
# @param [Number] y
# @param [Number] height
# @param [Number] jumps
# @return [JumpTo]
@JumpTo: (duration, position, y, height, jumps) ->
# The Quaternion class
# @param [Number] x
# @param [Number] y
# @param [Number] z
# @param [Number] w
# @return [kmQuaternion]
@kmQuaternion: (x, y, z, w) ->
# using image file to print text label on the screen, might be a bit slower than cc.Label, similar to cc.LabelBMFont
# @param [String] strText
# @param [String] charMapFile
# @param [Number] itemWidth
# @param [Number] itemHeight
# @param [Number] startCharMap
# @return [LabelAtlas]
@LabelAtlas: (strText, charMapFile, itemWidth, itemHeight, startCharMap) ->
# cc.LabelBMFont is a subclass of cc.SpriteBatchNode.
# @param [String] str
# @param [String] fntFile
# @param [Number] width
# @param [Number] alignment
# @param [Point] imageOffset
# @return [LabelBMFont]
@LabelBMFont: (str, fntFile, width, alignment, imageOffset) ->
# cc.LabelTTF is a subclass of cc.TextureNode that knows how to render text labels with system font or a ttf font file All features from cc.Sprite are valid in cc.LabelTTF cc.LabelTTF objects are slow for js-binding on mobile devices.
# @param [String] text
# @param [String|cc.FontDefinition] fontName
# @param [Number] fontSize
# @param [Size] dimensions
# @param [Number] hAlignment
# @param [Number] vAlignment
# @return [LabelTTF]
@LabelTTF: (text, fontName, fontSize, dimensions, hAlignment, vAlignment) ->
# cc.Layer is a subclass of cc.Node that implements the TouchEventsDelegate protocol.
# @return [Layer]
@Layer: ->
# CCLayerColor is a subclass of CCLayer that implements the CCRGBAProtocol protocol.
# @param [Color] color
# @param [Number] width
# @param [Number] height
# @return [LayerColor]
@LayerColor: (color, width, height) ->
# CCLayerGradient is a subclass of cc.LayerColor that draws gradients across the background.
# @param [Color] start
# @param [Color] end
# @param [Point] v
# @return [LayerGradient]
@LayerGradient: (start, end, v) ->
# CCMultipleLayer is a CCLayer with the ability to multiplex it's children.
# @param [Array] layers
# @return [LayerMultiplex]
@LayerMultiplex: (layers) ->
# cc.Lens3D action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Point] position
# @param [Number] radius
# @return [Lens3D]
@Lens3D: (duration, gridSize, position, radius) ->
# cc.Liquid action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] waves
# @param [Number] amplitude
# @return [Liquid]
@Liquid: (duration, gridSize, waves, amplitude) ->
# Loader for resource loading process.
# @return [loader]
@loader: ->
# Features and Limitation: - You can add MenuItem objects in runtime using addChild: - But the only accepted children are MenuItem objects
# @param [...cc.MenuItem|null] menuItems}
# @return [Menu]
@Menu: (menuItems}) ->
# Subclass cc.MenuItem (or any subclass) to create your custom cc.MenuItem objects.
# @param [function|String] callback
# @param [Node] target
# @return [MenuItem]
@MenuItem: (callback, target) ->
# Helper class that creates a MenuItemLabel class with a LabelAtlas
# @param [String] value
# @param [String] charMapFile
# @param [Number] itemWidth
# @param [Number] itemHeight
# @param [String] startCharMap
# @param [function|String|Null] callback
# @param [Node|Null] target
# @return [MenuItemAtlasFont]
@MenuItemAtlasFont: (value, charMapFile, itemWidth, itemHeight, startCharMap, callback, target) ->
# Helper class that creates a CCMenuItemLabel class with a Label
# @param [String] value
# @param [function|String] callback
# @param [Node] target
# @return [MenuItemFont]
@MenuItemFont: (value, callback, target) ->
# cc.MenuItemImage accepts images as items.
# @param [string|null] normalImage
# @param [string|null] selectedImage
# @param [string|null] disabledImage
# @param [function|string|null] callback
# @param [Node|null] target
# @return [MenuItemImage]
@MenuItemImage: (normalImage, selectedImage, disabledImage, callback, target) ->
# Any cc.Node that supports the cc.LabelProtocol protocol can be added.
# @param [Node] label
# @param [function|String] selector
# @param [Node] target
# @return [MenuItemLabel]
@MenuItemLabel: (label, selector, target) ->
# CCMenuItemSprite accepts CCNode objects as items.
# @param [Image|Null] normalSprite
# @param [Image|Null] selectedSprite
# @param [Image|cc.Node|Null] three
# @param [String|function|cc.Node|Null] four
# @param [String|function|Null] five
# @return [MenuItemSprite]
@MenuItemSprite: (normalSprite, selectedSprite, three, four, five) ->
# A simple container class that "toggles" it's inner items The inner items can be any MenuItem
# @return [MenuItemToggle]
@MenuItemToggle: ->
# MenuPassive: The menu passive ui component
# @return [MenuPassive]
@MenuPassive: ->
# cc.MotionStreak manages a Ribbon based on it's motion in absolute space.
# @return [MotionStreak]
@MotionStreak: ->
# Moves a CCNode object x,y pixels by modifying it's position attribute.
# @param [Number] duration
# @param [Point|Number] deltaPos
# @param [Number] deltaY
# @return [MoveBy]
@MoveBy: (duration, deltaPos, deltaY) ->
# Moves a CCNode object to the position x,y.
# @param [Number] duration
# @param [Point|Number] position
# @param [Number] y
# @return [MoveTo]
@MoveTo: (duration, position, y) ->
# cc.Node is the root class of all node.
# @return [Node]
@Node: ->
# This action simulates a page turn from the bottom right hand corner of the screen.
# @return [PageTurn3D]
@PageTurn3D: ->
# cc.ParallaxNode: A node that simulates a parallax scroller The children will be moved faster / slower than the parent according the the parallax ratio.
# @return [ParallaxNode]
@ParallaxNode: ->
# Structure that contains the values of each particle
# @param [Point] pos
# @param [Point] startPos
# @param [Color] color
# @param [Color] deltaColor
# @param [Size] size
# @param [Size] deltaSize
# @param [Number] rotation
# @param [Number] deltaRotation
# @param [Number] timeToLive
# @param [Number] atlasIndex
# @param [Particle.ModeA] modeA
# @param [Particle.ModeA] modeB
# @return [Particle]
@Particle: (pos, startPos, color, deltaColor, size, deltaSize, rotation, deltaRotation, timeToLive, atlasIndex, modeA, modeB) ->
# cc.ParticleBatchNode is like a batch node: if it contains children, it will draw them in 1 single OpenGL call (often known as "batch draw").
# @param [String|cc.Texture2D] fileImage
# @param [Number] capacity
# @return [ParticleBatchNode]
@ParticleBatchNode: (fileImage, capacity) ->
# An explosion particle system
# @return [ParticleExplosion]
@ParticleExplosion: ->
# A fire particle system
# @return [ParticleFire]
@ParticleFire: ->
# A fireworks particle system
# @return [ParticleFireworks]
@ParticleFireworks: ->
# A flower particle system
# @return [ParticleFlower]
@ParticleFlower: ->
# A galaxy particle system
# @return [ParticleGalaxy]
@ParticleGalaxy: ->
# A meteor particle system
# @return [ParticleMeteor]
@ParticleMeteor: ->
# A rain particle system
# @return [ParticleRain]
@ParticleRain: ->
# A smoke particle system
# @return [ParticleSmoke]
@ParticleSmoke: ->
# A snow particle system
# @return [ParticleSnow]
@ParticleSnow: ->
# A spiral particle system
# @return [ParticleSpiral]
@ParticleSpiral: ->
# A sun particle system
# @return [ParticleSun]
@ParticleSun: ->
# Particle System base class.
# @return [ParticleSystem]
@ParticleSystem: ->
# @return [path]
@path: ->
# Places the node in a certain position
# @param [Point|Number] pos
# @param [Number] y
# @return [Place]
@Place: (pos, y) ->
# cc.plistParser is a singleton object for parsing plist files
# @return [plistParser]
@plistParser: ->
# cc.Point
# @param [Number] x
# @param [Number] y
# @return [Point]
@Point: (x, y) ->
# Parallax Object.
# @return [PointObject]
@PointObject: ->
# Progress from a percentage to another percentage
# @param [Number] duration
# @param [Number] fromPercentage
# @param [Number] toPercentage
# @return [ProgressFromTo]
@ProgressFromTo: (duration, fromPercentage, toPercentage) ->
# cc.Progresstimer is a subclass of cc.Node.
# @return [ProgressTimer]
@ProgressTimer: ->
# Progress to percentage
# @param [Number] duration
# @param [Number] percent
# @return [ProgressTo]
@ProgressTo: (duration, percent) ->
# A class inhert from cc.Node, use for saving some protected children in other list.
# @return [ProtectedNode]
@ProtectedNode: ->
# cc.Rect
# @param [Number] width
# @param [Number] height
# @param width
# @param height
# @return [Rect]
@Rect: (width, height, width, height) ->
# Delete self in the next frame.
# @param [Boolean] isNeedCleanUp
# @return [RemoveSelf]
@RemoveSelf: (isNeedCleanUp) ->
# cc.RenderTexture is a generic rendering target.
# @return [RenderTexture]
@RenderTexture: ->
# Repeats an action a number of times.
# @param [FiniteTimeAction] action
# @param [Number] times
# @return [Repeat]
@Repeat: (action, times) ->
# Repeats an action for ever.
# @param [FiniteTimeAction] action
# @return [RepeatForever]
@RepeatForever: (action) ->
# cc.ResolutionPolicy class is the root strategy class of scale strategy, its main task is to maintain the compatibility with Cocos2d-x
# @param [ContainerStrategy] containerStg
# @param [ContentStrategy] contentStg
# @return [ResolutionPolicy]
@ResolutionPolicy: (containerStg, contentStg) ->
# cc.ReuseGrid action
# @param [Number] times
# @return [ReuseGrid]
@ReuseGrid: (times) ->
# Executes an action in reverse order, from time=duration to time=0
# @param [FiniteTimeAction] action
# @return [ReverseTime]
@ReverseTime: (action) ->
# An RGBA color class, its value present as percent
# @param [Number] r
# @param [Number] g
# @param [Number] b
# @param [Number] a
# @return [RGBA]
@RGBA: (r, g, b, a) ->
# cc.Ripple3D action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Point] position
# @param [Number] radius
# @param [Number] waves
# @param [Number] amplitude
# @return [Ripple3D]
@Ripple3D: (duration, gridSize, position, radius, waves, amplitude) ->
# Rotates a cc.Node object clockwise a number of degrees by modifying it's rotation attribute.
# @param [Number] duration
# @param [Number] deltaAngleX
# @param [Number] deltaAngleY
# @return [RotateBy]
@RotateBy: (duration, deltaAngleX, deltaAngleY) ->
# Rotates a cc.Node object to a certain angle by modifying it's.
# @param [Number] duration
# @param [Number] deltaAngleX
# @param [Number] deltaAngleY
# @return [RotateTo]
@RotateTo: (duration, deltaAngleX, deltaAngleY) ->
# A SAX Parser
# @return [saxParser]
@saxParser: ->
# A 9-slice sprite for cocos2d.
# @return [Scale9Sprite]
@Scale9Sprite: ->
# Scales a cc.Node object a zoom factor by modifying it's scale attribute.
# @return [ScaleBy]
@ScaleBy: ->
# Scales a cc.Node object to a zoom factor by modifying it's scale attribute.
# @param [Number] duration
# @param [Number] sx
# @param [Number] sy
# @return [ScaleTo]
@ScaleTo: (duration, sx, sy) ->
# cc.Scene is a subclass of cc.Node that is used only as an abstract concept.
# @return [Scene]
@Scene: ->
# Scheduler is responsible of triggering the scheduled callbacks.
# @return [Scheduler]
@Scheduler: ->
# The fullscreen API provides an easy way for web content to be presented using the user's entire screen.
# @return [screen]
@screen: ->
# ScrollView support for cocos2d -x.
# @return [ScrollView]
@ScrollView: ->
# Runs actions sequentially, one after another.
# @param [Array|cc.FiniteTimeAction] tempArray
# @return [Sequence]
@Sequence: (tempArray) ->
# cc.shaderCache is a singleton object that stores manages GL shaders
# @return [shaderCache]
@shaderCache: ->
# cc.Shaky3D action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] range
# @param [Boolean] shakeZ
# @return [Shaky3D]
@Shaky3D: (duration, gridSize, range, shakeZ) ->
# cc.ShakyTiles3D action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] range
# @param [Boolean] shakeZ
# @return [ShakyTiles3D]
@ShakyTiles3D: (duration, gridSize, range, shakeZ) ->
# cc.ShatteredTiles3D action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] range
# @param [Boolean] shatterZ
# @return [ShatteredTiles3D]
@ShatteredTiles3D: (duration, gridSize, range, shatterZ) ->
# Show the node.
# @return [Show]
@Show: ->
# cc.ShuffleTiles action, Shuffle the tiles in random order.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] seed
# @return [ShuffleTiles]
@ShuffleTiles: (duration, gridSize, seed) ->
# cc.Size
# @param [Number] width
# @param [Number] height
# @return [Size]
@Size: (width, height) ->
# Skews a cc.Node object by skewX and skewY degrees.
# @param [Number] t
# @param [Number] sx
# @param [Number] sy
# @return [SkewBy]
@SkewBy: (t, sx, sy) ->
# Skews a cc.Node object to given angles by modifying it's skewX and skewY attributes
# @param [Number] t
# @param [Number] sx
# @param [Number] sy
# @return [SkewTo]
@SkewTo: (t, sx, sy) ->
# The sortable object interface
# @return [SortableObject]
@SortableObject: ->
# The SortedObject class
# @return [SortedObject]
@SortedObject: ->
# The Spacer class
# @return [Spacer]
@Spacer: ->
# Spawn a new action immediately
# @return [Spawn]
@Spawn: ->
# Changes the speed of an action, making it take longer (speed 1) or less (speed
# @param [ActionInterval] action
# @param [Number] speed
# @return [Speed]
@Speed: (action, speed) ->
# cc.SplitCols action.
# @param [Number] duration
# @param [Number] cols
# @return [SplitCols]
@SplitCols: (duration, cols) ->
# cc.SplitRows action.
# @param [Number] duration
# @param [Number] rows
# @return [SplitRows]
@SplitRows: (duration, rows) ->
# cc.Sprite is a 2d image ( http://en.wikipedia.org/wiki/Sprite_(computer_graphics) ) cc.Sprite can be created with an image, or with a sub-rectangle of an image.
# @param [String|cc.SpriteFrame|HTMLImageElement|cc.Texture2D] fileName
# @param [Rect] rect
# @param [Boolean] rotated
# @return [Sprite]
@Sprite: (fileName, rect, rotated) ->
# In Canvas render mode ,cc.SpriteBatchNodeCanvas is like a normal node: if it contains children.
# @param [String|cc.Texture2D] fileImage
# @param [Number] capacity
# @return [SpriteBatchNode]
@SpriteBatchNode: (fileImage, capacity) ->
# A cc.SpriteFrame has: - texture: A cc.Texture2D that will be used by the cc.Sprite - rectangle: A rectangle of the texture You can modify the frame of a cc.Sprite by doing:
# @param [String|cc.Texture2D] filename
# @param [Rect] rect
# @param [Boolean] rotated
# @param [Point] offset
# @param [Size] originalSize
# @return [SpriteFrame]
@SpriteFrame: (filename, rect, rotated, offset, originalSize) ->
# cc.spriteFrameCache is a singleton that handles the loading of the sprite frames.
# @return [spriteFrameCache]
@spriteFrameCache: ->
# cc.StopGrid action.
# @return [StopGrid]
@StopGrid: ->
# UITableView counterpart for cocos2d for iphone.
# @return [TableView]
@TableView: ->
# Abstract class for SWTableView cell node
# @return [TableViewCell]
@TableViewCell: ->
# Overrides the target of an action so that it always runs on the target specified at action creation rather than the one specified by runAction.
# @param [Node] target
# @param [FiniteTimeAction] action
# @return [TargetedAction]
@TargetedAction: (target, action) ->
# cc.Tex2F
# @param [Number] u1
# @param [Number] v1
# @return [Tex2F]
@Tex2F: (u1, v1) ->
# Text field delegate
# @return [TextFieldDelegate]
@TextFieldDelegate: ->
# A simple text input field with TTF font.
# @param [String] placeholder
# @param [Size] dimensions
# @param [Number] alignment
# @param [String] fontName
# @param [Number] fontSize
# @return [TextFieldTTF]
@TextFieldTTF: (placeholder, dimensions, alignment, fontName, fontSize) ->
# This class allows to easily create OpenGL or Canvas 2D textures from images, text or raw data.
# @return [Texture2D]
@Texture2D: ->
# A class that implements a Texture Atlas.
# @return [TextureAtlas]
@TextureAtlas: ->
# cc.textureCache is a singleton object, it's the global cache for cc.Texture2D
# @return [textureCache]
@textureCache: ->
# A Tile composed of position, startPosition and delta.
# @param [Point] position
# @param [Point] startPosition
# @param [Size] delta
# @return [Tile]
@Tile: (position, startPosition, delta) ->
# cc.TiledGrid3D is a 3D grid implementation.
# @return [TiledGrid3D]
@TiledGrid3D: ->
# Base class for cc.TiledGrid3D actions.
# @return [TiledGrid3DAction]
@TiledGrid3DAction: ->
# Light weight timer
# @return [Timer]
@Timer: ->
# Tints a cc.Node that implements the cc.NodeRGB protocol from current tint to a custom one.
# @param [Number] duration
# @param [Number] deltaRed
# @param [Number] deltaGreen
# @param [Number] deltaBlue
# @return [TintBy]
@TintBy: (duration, deltaRed, deltaGreen, deltaBlue) ->
# Tints a cc.Node that implements the cc.NodeRGB protocol from current tint to a custom one.
# @param [Number] duration
# @param [Number] red
# @param [Number] green
# @param [Number] blue
# @return [TintTo]
@TintTo: (duration, red, green, blue) ->
# cc.TMXLayer represents the TMX layer.
# @return [TMXLayer]
@TMXLayer: ->
# cc.TMXLayerInfo contains the information about the layers like: - Layer name - Layer size - Layer opacity at creation time (it can be modified at runtime) - Whether the layer is visible (if it's not visible, then the CocosNode won't be created) This information is obtained from the TMX file.
# @return [TMXLayerInfo]
@TMXLayerInfo: ->
# cc.TMXMapInfo contains the information about the map like: - Map orientation (hexagonal, isometric or orthogonal) - Tile size - Map size And it also contains: - Layers (an array of TMXLayerInfo objects) - Tilesets (an array of TMXTilesetInfo objects) - ObjectGroups (an array of TMXObjectGroupInfo objects) This information is obtained from the TMX file.
# @param [String] tmxFile
# @param [String] resourcePath
# @return [TMXMapInfo]
@TMXMapInfo: (tmxFile, resourcePath) ->
# cc.TMXObjectGroup represents the TMX object group.
# @return [TMXObjectGroup]
@TMXObjectGroup: ->
# cc.TMXTiledMap knows how to parse and render a TMX map.
# @param [String] tmxFile
# @param [String] resourcePath
# @return [TMXTiledMap]
@TMXTiledMap: (tmxFile, resourcePath) ->
# cc.TMXTilesetInfo contains the information about the tilesets like: - Tileset name - Tileset spacing - Tileset margin - size of the tiles - Image used for the tiles - Image size This information is obtained from the TMX file.
# @return [TMXTilesetInfo]
@TMXTilesetInfo: ->
# Toggles the visibility of a node.
# @return [ToggleVisibility]
@ToggleVisibility: ->
# The touch event class
# @param [Number] x
# @param [Number] y
# @param [Number] id
# @return [Touch]
@Touch: (x, y, id) ->
# Cross fades two scenes using the cc.RenderTexture object.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionCrossFade]
@TransitionCrossFade: (t, scene) ->
# Fade out the outgoing scene and then fade in the incoming scene.
# @param [Number] t
# @param [Scene] scene
# @param [TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER] o
# @return [TransitionFade]
@TransitionFade: (t, scene, o) ->
# Fade the tiles of the outgoing scene from the top-right corner to the bottom-left corner.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionFadeBL]
@TransitionFadeBL: (t, scene) ->
# Fade the tiles of the outgoing scene from the top to the bottom.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionFadeDown]
@TransitionFadeDown: (t, scene) ->
# Fade the tiles of the outgoing scene from the left-bottom corner the to top-right corner.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionFadeTR]
@TransitionFadeTR: (t, scene) ->
# Fade the tiles of the outgoing scene from the top-right corner to the bottom-left corner.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionFadeUp]
@TransitionFadeUp: (t, scene) ->
# Flips the screen half horizontally and half vertically.
# @param [Number] t
# @param [Scene] scene
# @param [TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER] o
# @return [TransitionFlipAngular]
@TransitionFlipAngular: (t, scene, o) ->
# Flips the screen horizontally.
# @param [Number] t
# @param [Scene] scene
# @param [TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER] o
# @return [TransitionFlipX]
@TransitionFlipX: (t, scene, o) ->
# Flips the screen vertically.
# @param [Number] t
# @param [Scene] scene
# @param [TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER] o
# @return [TransitionFlipY]
@TransitionFlipY: (t, scene, o) ->
# Zoom out and jump the outgoing scene, and then jump and zoom in the incoming
# @param [Number] t
# @param [Scene] scene
# @return [TransitionJumpZoom]
@TransitionJumpZoom: (t, scene) ->
# Move in from to the bottom the incoming scene.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionMoveInB]
@TransitionMoveInB: (t, scene) ->
# Move in from to the left the incoming scene.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionMoveInL]
@TransitionMoveInL: (t, scene) ->
# Move in from to the right the incoming scene.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionMoveInR]
@TransitionMoveInR: (t, scene) ->
# Move in from to the top the incoming scene.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionMoveInT]
@TransitionMoveInT: (t, scene) ->
# A transition which peels back the bottom right hand corner of a scene to transition to the scene beneath it simulating a page turn.
# @param [Number] t
# @param [Scene] scene
# @param [Boolean] backwards
# @return [TransitionPageTurn]
@TransitionPageTurn: (t, scene, backwards) ->
# cc.TransitionProgress transition.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionProgress]
@TransitionProgress: (t, scene) ->
# cc.TransitionProgressHorizontal transition.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionProgressHorizontal]
@TransitionProgressHorizontal: (t, scene) ->
# cc.TransitionProgressInOut transition.
# @return [TransitionProgressInOut]
@TransitionProgressInOut: ->
# cc.TransitionProgressOutIn transition.
# @return [TransitionProgressOutIn]
@TransitionProgressOutIn: ->
# cc.TransitionRadialCCW transition.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionProgressRadialCCW]
@TransitionProgressRadialCCW: (t, scene) ->
# cc.TransitionRadialCW transition.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionProgressRadialCW]
@TransitionProgressRadialCW: (t, scene) ->
# cc.TransitionProgressVertical transition.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionProgressVertical]
@TransitionProgressVertical: (t, scene) ->
# Rotate and zoom out the outgoing scene, and then rotate and zoom in the incoming
# @param [Number] t
# @param [Scene] scene
# @return [TransitionRotoZoom]
@TransitionRotoZoom: (t, scene) ->
# @param [Number] t
# @param [Scene] scene
# @return [TransitionScene]
@TransitionScene: (t, scene) ->
# A cc.Transition that supports orientation like.
# @param [Number] t
# @param [Scene] scene
# @param [TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER] orientation
# @return [TransitionSceneOriented]
@TransitionSceneOriented: (t, scene, orientation) ->
# Shrink the outgoing scene while grow the incoming scene
# @param [Number] t
# @param [Scene] scene
# @return [TransitionShrinkGrow]
@TransitionShrinkGrow: (t, scene) ->
# Slide in the incoming scene from the bottom border.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionSlideInB]
@TransitionSlideInB: (t, scene) ->
# a transition that a new scene is slided from left
# @param [Number] t
# @param [Scene] scene
# @return [TransitionSlideInL]
@TransitionSlideInL: (t, scene) ->
# Slide in the incoming scene from the right border.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionSlideInR]
@TransitionSlideInR: (t, scene) ->
# Slide in the incoming scene from the top border.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionSlideInT]
@TransitionSlideInT: (t, scene) ->
# The odd columns goes upwards while the even columns goes downwards.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionSplitCols]
@TransitionSplitCols: (t, scene) ->
# The odd rows goes to the left while the even rows goes to the right.
# @param [Number] t
# @param [Scene] scene
# @return [TransitionSplitRows]
@TransitionSplitRows: (t, scene) ->
# Turn off the tiles of the outgoing scene in random order
# @param [Number] t
# @param [Scene] scene
# @return [TransitionTurnOffTiles]
@TransitionTurnOffTiles: (t, scene) ->
# Flips the screen half horizontally and half vertically doing a little zooming out/in.
# @param [Number] t
# @param [Scene] scene
# @param [TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER] o
# @return [TransitionZoomFlipAngular]
@TransitionZoomFlipAngular: (t, scene, o) ->
# Flips the screen horizontally doing a zoom out/in The front face is the outgoing scene and the back face is the incoming scene.
# @param [Number] t
# @param [Scene] scene
# @param [TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER] o
# @return [TransitionZoomFlipX]
@TransitionZoomFlipX: (t, scene, o) ->
# Flips the screen vertically doing a little zooming out/in The front face is the outgoing scene and the back face is the incoming scene.
# @param [Number] t
# @param [Scene] scene
# @param [TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER] o
# @return [TransitionZoomFlipY]
@TransitionZoomFlipY: (t, scene, o) ->
# cc.TurnOffTiles action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number|Null] seed
# @return [TurnOffTiles]
@TurnOffTiles: (duration, gridSize, seed) ->
# cc.Twirl action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Point] position
# @param [Number] twirls
# @param [Number] amplitude
# @return [Twirl]
@Twirl: (duration, gridSize, position, twirls, amplitude) ->
# cc.Vertex2F
# @param [Number] x1
# @param [Number] y1
# @return [Vertex2F]
@Vertex2F: (x1, y1) ->
# cc.Vertex3F
# @param [Number] x1
# @param [Number] y1
# @param [Number] z1
# @return [Vertex3F]
@Vertex3F: (x1, y1, z1) ->
# cc.view is the singleton object which represents the game window.
# @return [view]
@view: ->
# cc.visibleRect is a singleton object which defines the actual visible rect of the current view, it should represent the same rect as cc.view.getViewportRect()
# @return [visibleRect]
@visibleRect: ->
# cc.Waves action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] waves
# @param [Number] amplitude
# @param [Boolean] horizontal
# @param [Boolean] vertical
# @return [Waves]
@Waves: (duration, gridSize, waves, amplitude, horizontal, vertical) ->
# cc.Waves3D action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] waves
# @param [Number] amplitude
# @return [Waves3D]
@Waves3D: (duration, gridSize, waves, amplitude) ->
# cc.WavesTiles3D action.
# @param [Number] duration
# @param [Size] gridSize
# @param [Number] waves
# @param [Number] amplitude
# @return [WavesTiles3D]
@WavesTiles3D: (duration, gridSize, waves, amplitude) ->
# A class of Web Audio.
# @param src
# @return [WebAudio]
@WebAudio: (src) ->
|
[
{
"context": "s\"\nPAGES: \"Pagina's\"\nPOSTS: \"Berichten\"\nAUTHORS: \"Auteurs\"\nSEARCH: \"Zoeken\"\nSOCIAL_NETWORKS: \"Sociale netwe",
"end": 405,
"score": 0.9794626235961914,
"start": 398,
"tag": "NAME",
"value": "Auteurs"
},
{
"context": "}}\"\n\"sharing\":\n \"shared\": \"G... | src/i18n/nl.cson | Intraktio/hybrid | 2 | PULL_TO_REFRESH: "Omlaag om te herladen!"
RETRY: "Opnieuw"
CANCEL: "Cancel"
SUBMIT: "Submit"
BACK: "Terug"
ERROR: "Er ging iets mis, probeer het opnieuw."
ATTEMPT_TO_CONNECT: "Poging {{attempt}} van {{attemptMax}}. Om te laden"
OK: "Ok"
YES: "Ja"
NO: "Nee"
EMPTY_LIST: "Er is niks hier!"
ENABLED: "Ingeschakeld"
MENU: "Menu"
HOME: "Home"
TAGS: "Tags"
PAGES: "Pagina's"
POSTS: "Berichten"
AUTHORS: "Auteurs"
SEARCH: "Zoeken"
SOCIAL_NETWORKS: "Sociale netwerken"
CATEGORIES: "Categorieën"
SETTINGS: "Instellingen"
CUSTOM_POSTS: "Aangepaste berichten"
CUSTOM_TAXO: "Aangepaste taxanomie"
CUSTOM_TAXO_TITLE: "{{term}}: {{name}}"
PUSH_NOTIFS: "Push berichten"
PUSH_NOTIF_TITLE: "Nieuwe inhoud!"
PUSH_NOTIF_TEXT: "Een nieuwe post/pagina: '{{postTitle}}' is nu op {{appTitle}}, wil je het bekijken?"
BOOKMARKS: "Bladwijzers"
BOOKMARKS_EMPTY: "Nog geen bladwijzers!"
BOOKMARK_ADDED: "Toegevoegd!"
BOOKMARK_REMOVED: "Bladwijzer verwijderd!"
ZOOM: "Zoom"
CACHE_CLEAR: "Clear cache"
CACHE_CLEARED: "Cache cleared"
"tags":
"title": "Tags"
"tag":
"title": "Tag: {{name}}"
"categories":
"title": "Categorieën"
"category":
"title": "Categorie: {{name}}"
"home":
"title": "Home"
"search":
"inputPlaceholder": "Zoeken"
"title": "Zoek"
"titleQuery": "Resultaten voor: {{query}}"
"sharing":
"shared": "Gedeeld!"
AUTHORS: "Auteurs"
AUTHOR: "Auteur"
AUTHOR_TITLE: "Auteur: {{name}}"
"pages":
"title": "Pagina's"
"posts":
"title": "Berichten"
"featured": "Uitgelicht"
"post":
"comments": "Reactie's"
"openInBrowser": "Open in browser"
"about":
"title": "Over"
"languages":
"en": "Engels"
"fr": "Frans"
"zh": "Chinees"
"es": "Spaans"
"pl": "Pools"
"de": "Duits"
"pt": "Portugees"
"it": "Italiaans"
"nl": "Nederlands"
"ru": "Russisch"
"tr": "Turks" | 168577 | PULL_TO_REFRESH: "Omlaag om te herladen!"
RETRY: "Opnieuw"
CANCEL: "Cancel"
SUBMIT: "Submit"
BACK: "Terug"
ERROR: "Er ging iets mis, probeer het opnieuw."
ATTEMPT_TO_CONNECT: "Poging {{attempt}} van {{attemptMax}}. Om te laden"
OK: "Ok"
YES: "Ja"
NO: "Nee"
EMPTY_LIST: "Er is niks hier!"
ENABLED: "Ingeschakeld"
MENU: "Menu"
HOME: "Home"
TAGS: "Tags"
PAGES: "Pagina's"
POSTS: "Berichten"
AUTHORS: "<NAME>"
SEARCH: "Zoeken"
SOCIAL_NETWORKS: "Sociale netwerken"
CATEGORIES: "Categorieën"
SETTINGS: "Instellingen"
CUSTOM_POSTS: "Aangepaste berichten"
CUSTOM_TAXO: "Aangepaste taxanomie"
CUSTOM_TAXO_TITLE: "{{term}}: {{name}}"
PUSH_NOTIFS: "Push berichten"
PUSH_NOTIF_TITLE: "Nieuwe inhoud!"
PUSH_NOTIF_TEXT: "Een nieuwe post/pagina: '{{postTitle}}' is nu op {{appTitle}}, wil je het bekijken?"
BOOKMARKS: "Bladwijzers"
BOOKMARKS_EMPTY: "Nog geen bladwijzers!"
BOOKMARK_ADDED: "Toegevoegd!"
BOOKMARK_REMOVED: "Bladwijzer verwijderd!"
ZOOM: "Zoom"
CACHE_CLEAR: "Clear cache"
CACHE_CLEARED: "Cache cleared"
"tags":
"title": "Tags"
"tag":
"title": "Tag: {{name}}"
"categories":
"title": "Categorieën"
"category":
"title": "Categorie: {{name}}"
"home":
"title": "Home"
"search":
"inputPlaceholder": "Zoeken"
"title": "Zoek"
"titleQuery": "Resultaten voor: {{query}}"
"sharing":
"shared": "Gedeeld!"
AUTHORS: "<NAME>"
AUTHOR: "<NAME>"
AUTHOR_TITLE: "Auteur: {{name}}"
"pages":
"title": "Pagina's"
"posts":
"title": "Berichten"
"featured": "Uitgelicht"
"post":
"comments": "Reactie's"
"openInBrowser": "Open in browser"
"about":
"title": "Over"
"languages":
"en": "Engels"
"fr": "Frans"
"zh": "Chinees"
"es": "Spaans"
"pl": "Pools"
"de": "Duits"
"pt": "Portugees"
"it": "Italiaans"
"nl": "Nederlands"
"ru": "Russisch"
"tr": "Turks" | true | PULL_TO_REFRESH: "Omlaag om te herladen!"
RETRY: "Opnieuw"
CANCEL: "Cancel"
SUBMIT: "Submit"
BACK: "Terug"
ERROR: "Er ging iets mis, probeer het opnieuw."
ATTEMPT_TO_CONNECT: "Poging {{attempt}} van {{attemptMax}}. Om te laden"
OK: "Ok"
YES: "Ja"
NO: "Nee"
EMPTY_LIST: "Er is niks hier!"
ENABLED: "Ingeschakeld"
MENU: "Menu"
HOME: "Home"
TAGS: "Tags"
PAGES: "Pagina's"
POSTS: "Berichten"
AUTHORS: "PI:NAME:<NAME>END_PI"
SEARCH: "Zoeken"
SOCIAL_NETWORKS: "Sociale netwerken"
CATEGORIES: "Categorieën"
SETTINGS: "Instellingen"
CUSTOM_POSTS: "Aangepaste berichten"
CUSTOM_TAXO: "Aangepaste taxanomie"
CUSTOM_TAXO_TITLE: "{{term}}: {{name}}"
PUSH_NOTIFS: "Push berichten"
PUSH_NOTIF_TITLE: "Nieuwe inhoud!"
PUSH_NOTIF_TEXT: "Een nieuwe post/pagina: '{{postTitle}}' is nu op {{appTitle}}, wil je het bekijken?"
BOOKMARKS: "Bladwijzers"
BOOKMARKS_EMPTY: "Nog geen bladwijzers!"
BOOKMARK_ADDED: "Toegevoegd!"
BOOKMARK_REMOVED: "Bladwijzer verwijderd!"
ZOOM: "Zoom"
CACHE_CLEAR: "Clear cache"
CACHE_CLEARED: "Cache cleared"
"tags":
"title": "Tags"
"tag":
"title": "Tag: {{name}}"
"categories":
"title": "Categorieën"
"category":
"title": "Categorie: {{name}}"
"home":
"title": "Home"
"search":
"inputPlaceholder": "Zoeken"
"title": "Zoek"
"titleQuery": "Resultaten voor: {{query}}"
"sharing":
"shared": "Gedeeld!"
AUTHORS: "PI:NAME:<NAME>END_PI"
AUTHOR: "PI:NAME:<NAME>END_PI"
AUTHOR_TITLE: "Auteur: {{name}}"
"pages":
"title": "Pagina's"
"posts":
"title": "Berichten"
"featured": "Uitgelicht"
"post":
"comments": "Reactie's"
"openInBrowser": "Open in browser"
"about":
"title": "Over"
"languages":
"en": "Engels"
"fr": "Frans"
"zh": "Chinees"
"es": "Spaans"
"pl": "Pools"
"de": "Duits"
"pt": "Portugees"
"it": "Italiaans"
"nl": "Nederlands"
"ru": "Russisch"
"tr": "Turks" |
[
{
"context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino ",
"end": 38,
"score": 0.9998892545700073,
"start": 25,
"tag": "NAME",
"value": "Andrey Antukh"
},
{
"context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright... | public/taiga-front/app/coffee/modules/base/navurls.coffee | mabotech/maboss | 0 | ###
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com>
# Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: modules/base/navurl.coffee
###
taiga = @.taiga
trim = @.taiga.trim
bindOnce = @.taiga.bindOnce
module = angular.module("taigaBase")
#############################################################################
## Navigation Urls Service
#############################################################################
class NavigationUrlsService extends taiga.Service
constructor: ->
@.urls = {}
update: (urls) ->
@.urls = _.merge({}, @.urls, urls or {})
formatUrl: (url, ctx={}) ->
replacer = (match) ->
match = trim(match, ":")
return ctx[match] or "undefined"
return url.replace(/(:\w+)/g, replacer)
resolve: (name, ctx) ->
url = @.urls[name]
return "" if not url
return @.formatUrl(url, ctx) if ctx
return url
module.service("$tgNavUrls", NavigationUrlsService)
#############################################################################
## Navigation Urls Directive
#############################################################################
NavigationUrlsDirective = ($navurls, $auth, $q, $location) ->
# Example:
# link(tg-nav="project-backlog:project='sss',")
# bindOnce version that uses $q for offer
# promise based api
bindOnceP = ($scope, attr) ->
defered = $q.defer()
bindOnce $scope, attr, (v) ->
defered.resolve(v)
return defered.promise
parseNav = (data, $scope) ->
[name, params] = _.map(data.split(":"), trim)
if params
params = _.map(params.split(","), trim)
else
params = []
values = _.map(params, (x) -> trim(x.split("=")[1]))
promises = _.map(values, (x) -> bindOnceP($scope, x))
return $q.all(promises).then ->
options = {}
for item in params
[key, value] = _.map(item.split("="), trim)
options[key] = $scope.$eval(value)
return [name, options]
link = ($scope, $el, $attrs) ->
if $el.is("a")
$el.attr("href", "#")
$el.on "mouseenter", (event) ->
target = $(event.currentTarget)
if !target.data("fullUrl")
parseNav($attrs.tgNav, $scope).then (result) ->
[name, options] = result
user = $auth.getUser()
options.user = user.username if user
url = $navurls.resolve(name)
fullUrl = $navurls.formatUrl(url, options)
target.data("fullUrl", fullUrl)
if target.is("a")
target.attr("href", fullUrl)
$el.on "click", (event) ->
event.preventDefault()
target = $(event.currentTarget)
if target.hasClass('noclick')
return
fullUrl = target.data("fullUrl")
switch event.which
when 1
$location.url(fullUrl)
$scope.$apply()
when 2
window.open fullUrl
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgNav", ["$tgNavUrls", "$tgAuth", "$q", "$tgLocation", NavigationUrlsDirective])
| 18655 | ###
# Copyright (C) 2014 <NAME> <<EMAIL>>
# Copyright (C) 2014 <NAME> <<EMAIL>>
# Copyright (C) 2014 <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: modules/base/navurl.coffee
###
taiga = @.taiga
trim = @.taiga.trim
bindOnce = @.taiga.bindOnce
module = angular.module("taigaBase")
#############################################################################
## Navigation Urls Service
#############################################################################
class NavigationUrlsService extends taiga.Service
constructor: ->
@.urls = {}
update: (urls) ->
@.urls = _.merge({}, @.urls, urls or {})
formatUrl: (url, ctx={}) ->
replacer = (match) ->
match = trim(match, ":")
return ctx[match] or "undefined"
return url.replace(/(:\w+)/g, replacer)
resolve: (name, ctx) ->
url = @.urls[name]
return "" if not url
return @.formatUrl(url, ctx) if ctx
return url
module.service("$tgNavUrls", NavigationUrlsService)
#############################################################################
## Navigation Urls Directive
#############################################################################
NavigationUrlsDirective = ($navurls, $auth, $q, $location) ->
# Example:
# link(tg-nav="project-backlog:project='sss',")
# bindOnce version that uses $q for offer
# promise based api
bindOnceP = ($scope, attr) ->
defered = $q.defer()
bindOnce $scope, attr, (v) ->
defered.resolve(v)
return defered.promise
parseNav = (data, $scope) ->
[name, params] = _.map(data.split(":"), trim)
if params
params = _.map(params.split(","), trim)
else
params = []
values = _.map(params, (x) -> trim(x.split("=")[1]))
promises = _.map(values, (x) -> bindOnceP($scope, x))
return $q.all(promises).then ->
options = {}
for item in params
[key, value] = _.map(item.split("="), trim)
options[key] = $scope.$eval(value)
return [name, options]
link = ($scope, $el, $attrs) ->
if $el.is("a")
$el.attr("href", "#")
$el.on "mouseenter", (event) ->
target = $(event.currentTarget)
if !target.data("fullUrl")
parseNav($attrs.tgNav, $scope).then (result) ->
[name, options] = result
user = $auth.getUser()
options.user = user.username if user
url = $navurls.resolve(name)
fullUrl = $navurls.formatUrl(url, options)
target.data("fullUrl", fullUrl)
if target.is("a")
target.attr("href", fullUrl)
$el.on "click", (event) ->
event.preventDefault()
target = $(event.currentTarget)
if target.hasClass('noclick')
return
fullUrl = target.data("fullUrl")
switch event.which
when 1
$location.url(fullUrl)
$scope.$apply()
when 2
window.open fullUrl
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgNav", ["$tgNavUrls", "$tgAuth", "$q", "$tgLocation", NavigationUrlsDirective])
| true | ###
# Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: modules/base/navurl.coffee
###
taiga = @.taiga
trim = @.taiga.trim
bindOnce = @.taiga.bindOnce
module = angular.module("taigaBase")
#############################################################################
## Navigation Urls Service
#############################################################################
class NavigationUrlsService extends taiga.Service
constructor: ->
@.urls = {}
update: (urls) ->
@.urls = _.merge({}, @.urls, urls or {})
formatUrl: (url, ctx={}) ->
replacer = (match) ->
match = trim(match, ":")
return ctx[match] or "undefined"
return url.replace(/(:\w+)/g, replacer)
resolve: (name, ctx) ->
url = @.urls[name]
return "" if not url
return @.formatUrl(url, ctx) if ctx
return url
module.service("$tgNavUrls", NavigationUrlsService)
#############################################################################
## Navigation Urls Directive
#############################################################################
NavigationUrlsDirective = ($navurls, $auth, $q, $location) ->
# Example:
# link(tg-nav="project-backlog:project='sss',")
# bindOnce version that uses $q for offer
# promise based api
bindOnceP = ($scope, attr) ->
defered = $q.defer()
bindOnce $scope, attr, (v) ->
defered.resolve(v)
return defered.promise
parseNav = (data, $scope) ->
[name, params] = _.map(data.split(":"), trim)
if params
params = _.map(params.split(","), trim)
else
params = []
values = _.map(params, (x) -> trim(x.split("=")[1]))
promises = _.map(values, (x) -> bindOnceP($scope, x))
return $q.all(promises).then ->
options = {}
for item in params
[key, value] = _.map(item.split("="), trim)
options[key] = $scope.$eval(value)
return [name, options]
link = ($scope, $el, $attrs) ->
if $el.is("a")
$el.attr("href", "#")
$el.on "mouseenter", (event) ->
target = $(event.currentTarget)
if !target.data("fullUrl")
parseNav($attrs.tgNav, $scope).then (result) ->
[name, options] = result
user = $auth.getUser()
options.user = user.username if user
url = $navurls.resolve(name)
fullUrl = $navurls.formatUrl(url, options)
target.data("fullUrl", fullUrl)
if target.is("a")
target.attr("href", fullUrl)
$el.on "click", (event) ->
event.preventDefault()
target = $(event.currentTarget)
if target.hasClass('noclick')
return
fullUrl = target.data("fullUrl")
switch event.which
when 1
$location.url(fullUrl)
$scope.$apply()
when 2
window.open fullUrl
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgNav", ["$tgNavUrls", "$tgAuth", "$q", "$tgLocation", NavigationUrlsDirective])
|
[
{
"context": "ssword, callback) ->\n if login is 'admin' and password is 'password'\n c",
"end": 1151,
"score": 0.9967373609542847,
"start": 1146,
"tag": "USERNAME",
"value": "admin"
},
{
"context": " if login is 'admin' and password is '... | examples/blog/docpad.coffee | TranscendOfSypherus/docpad-plugin-minicms | 1 | module.exports =
# The data generated by minicms is just like any other content
# So we can create custom collections or simply add template helpers
templateData:
getIndex: ->
@getCollection('html').findOne(url: '/')?.toJSON()
getArticles: ->
@getCollection('html').findAllLive(type: 'article').sortArray(date:-1)
getLinks: ->
@getCollection('html').findAllLive(type: 'link').sortArray(name:1)
plugins:
# This contains all the configuration of minicms, used for the admin panel of our blog
# It allows you to define lists, forms and how to generate the final content
minicms:
#prefix:
# url: 'cms' # Access the admin panel through '/cms' by default
# meta: 'cms' # Store form data of each content into a 'cms' field by default (inside metadata)
# Secret, required by signed cookie session
secret: 'keyboard cat blog'
# Implement the logic you want for authentication
auth: (login, password, callback) ->
if login is 'admin' and password is 'password'
callback null, true
else
callback "Invalid login or password.", false
# List all the content that is managed by the plugin
models: [
# Example of a content that is unique and only has 1 entry
name: ['Configuration', 'Configuration'] # First is singular name, second is plural. Here we use the same because we never have multiple "Configurations"
unique: true # Make this model "unique", that means there can only be 1 entry, not more, not less
form:
url: "/index" # Save configuration meta in index file
ext: 'html.md' # With a ".html.md" extension
# Set the metadata template of the file
# Each function that we put in the metadata will be called and the result will be used
# The context (this, @) contains the @docpad instance, a @slugify function and all the properties of the current model
meta:
title: -> @title
layout: 'home'
about: -> @about
# The content follows the metadata. For this file, it is in markdown (because we are making a html.md file)
content: -> @title
# For each model, we can create a form with several components that will allow the user to input data
components: [
# A 'title' field with a text input component (notice that we use this title field in the metadata template, above)
field: 'title'
label: 'Website Title' # The label is what will appear as field name in the form for the admin panel
type: 'text'
,
# Another text input component to type the Author of the website (this one is still stored in the cms: key of the meta, but we don't really use it for now. Maybe later?)
field: 'author'
label: 'Website Author'
type: 'text'
,
# An 'about' field using a plain textarea component
field: 'about'
label: 'About me'
type: 'textarea'
height: 100
,
# A color picker example
field: 'myColor'
label: 'My Favourite Color'
type: 'color'
,
# We can choose a 'category' with a choice component.
field: 'category'
label: 'Category'
type: 'choice'
expanded: true # The component will be "expanded" using html radio inputs
# The data: option returns an array of available categories.
# For this example, it is hardcoded but you can make your own logic using @docpad collections
data: -> ['Sport', 'News']
,
# We add a 'sub-category' field that depends on the 'category' field
field: 'subCategory'
deps: ['category'] # This field will update when the category field changes value
label: 'Sub-category'
type: 'choice'
# Here, we use the @category value to decide which sub-categories are available
# It will be called each time the field reloads
data: ->
if @category is 'Sport'
return ['Footbal', 'Tennis', 'Handball', 'Swimming']
else if @category is 'News'
return ['Technology', 'Finance', 'Gossip']
else # No category selected, then no sub-category available
return []
,
# Allow the user to change the blog logo by uploading an image
field: 'logo'
label: 'Website Logo'
type: 'file'
use: 'standard' # There can be multiple image profiles, here we define the one that will be displayed inside the form
optional: true # We can make a field optional
images: # Image profiles
# For this field, we only make 1 profile called 'standard' that will resize the image to fit in a 220x220 rectangle.
standard:
# You can hardcode an extension (png, jpg, gif), or use the @ext value to dynamically generate the right type.
# Also works with animated gifs (but a bit experimental)
url: -> "/logo.#{@ext}" # The url to create for the image
width: 220 # The maximum width of the image
height: 220 # The maximum height of the image
,
# An example of rich text field 'wysiwyg' component
# The resulting value will be valid html
field: 'wysiwygExample'
label: 'Wysiwyg example'
type: 'wysiwyg'
height: 450 # Optional, set the height of the field inside the form
,
# An example of 'markdown' component, so you can choose your philosophy: wysiwyg or markdown
field: 'markdownExample'
label: 'Markdown example'
type: 'markdown'
height: 450 # Optional, set the height of the field inside the form
]
,
# Example of a model that can have several entries.
# We are making a blog, so we need articles!
name: ['Article', 'Articles'] # First is singular form, second is plural form. Note that urls inside admin panel will be generated by slugifying those names.
list:
# Because this model can have several entries, we need a list page.
# Here is the configuration of it
# A list is showing several 'fields' of each entries inside a table layout
fields: [
name: 'Title' # Name of the 'field' in the table
value: -> @title # The function will be called and the value will be used for display. Inside the function, you have access to all the entry's meta
,
name: 'Image'
# If you want to display html that won't be escaped, use 'html' instead of 'value'
html: ->
if @image?
return '<div style="height:32px"><img src="'+@image.square.url+'" style="width:32px;height:32px" alt="image" /></div>'
else
return '<div style="height:32px"> - </div>'
,
name: 'Tags'
html: ->
if @tags instanceof Array
return @tags.join(', ')
else
return ''
]
# You can add filters to you list to make browsing easier
filters: [
name: 'Tag' # Filter by tag
# The data function returns all the available values to use on the filter
# Here, we are walking through the articles to find all tags
data: ->
tags = []
filter = type: 'article'
for item in @docpad.getCollection('html').findAll(filter).models
itemTags = item.get('tags')
if itemTags instanceof Array
for tag in itemTags
if not (tag in tags)
tags.push tag
return tags
,
# A custom filter to choose articles with image or articles without image only
name: 'Kind'
data: -> ['With Image', 'Textual']
]
# The list's data function is returning all the entries of the list.
# It is in charge to take in account the filters values
# When a filter changes, this function is called again to update the list
# The result of this function can be a Docpad Collection or a JSON-like array
data: ->
filter = type: 'article'
# Filter by kind (with image or not)
if @kind is 'with-image'
filter.image = $ne: null
else if @kind is 'textual'
filter.image = null
collection = @docpad.getCollection('html').findAll(filter)
if @tag?
# Filter by tags
finalModels = []
if collection.models instanceof Array
for model in collection.models
tags = model.get('tags')
for tag in tags
if @slugify(tag) is @tag
finalModels.push model.toJSON()
break
return finalModels
else
return collection
form:
# As with the configuration model, we need a form to add/edit articles
url: -> "/blog/#{@slugify @title}" # Each article's url. We slugify the title to generate the url
ext: 'html.md'
meta:
title: -> @title
type: 'article'
layout: 'article'
image: -> @image
tags: -> if @tags instanceof Array then @tags else []
date: -> new Date(@date)
content: -> @content
components: [
field: 'title'
type: 'text'
,
# A 'date' field with a datetime picker
field: 'date'
type: 'date'
# You can remove the hours by adding time: false
#time: false
,
# Choose the tags of your article
field: 'tags'
type: 'tags'
data: ->
# The data is used for autocompletion
tags = []
for item in @docpad.getCollection('html').findAll().models
itemTags = item.get('tags')
if itemTags instanceof Array
for tag in itemTags
if not (tag in tags)
tags.push tag
return tags
,
field: 'content'
type: 'markdown'
# You can add your custom validator on any field
# Well, this is actually useless here because the default validator is doing the same check,
# but feel free to check more things for your own needs.
validate: (val) -> typeof(val) is 'string' and val.length > 0
# You can also add your custom sanitizer that will be called before saving the content
sanitize: (val) -> return val?.trim()
,
field: 'image'
type: 'file'
use: 'thumbnail'
optional: true
images:
# This time we have 3 image profiles
# Each of them will be generated from the original picture
# Notice they all have a different url
standard:
url: -> "/blog/#{@slugify @title}.#{@ext}"
width: 498
height: 9999999
thumbnail:
url: -> "/blog/#{@slugify @title}.tn.#{@ext}"
width: 9999999
height: 128
square:
url: -> "/blog/#{@slugify @title}.sq.#{@ext}"
width: 32
height: 32
crop: true # With this option, the image will be cropped in order to have the exact 32x32 size
]
,
# Another model to add links on the sidebar of the blog
# Nothing more than the articles model
name: ['Link', 'Links']
list:
fields: [
name: 'Name'
value: -> @title
,
name: 'URL'
html: -> @href
]
data: ->
filter = type: 'link'
return @docpad.getCollection('html').findAll(filter)
form:
url: -> "/link/#{@slugify @name}"
ext: 'html.md'
meta:
title: -> @name
type: 'link'
layout: 'link'
href: -> @url
content: -> @url
components: [
field: 'name'
type: 'text'
,
field: 'url'
label: 'URL'
type: 'text'
]
]
| 85633 | module.exports =
# The data generated by minicms is just like any other content
# So we can create custom collections or simply add template helpers
templateData:
getIndex: ->
@getCollection('html').findOne(url: '/')?.toJSON()
getArticles: ->
@getCollection('html').findAllLive(type: 'article').sortArray(date:-1)
getLinks: ->
@getCollection('html').findAllLive(type: 'link').sortArray(name:1)
plugins:
# This contains all the configuration of minicms, used for the admin panel of our blog
# It allows you to define lists, forms and how to generate the final content
minicms:
#prefix:
# url: 'cms' # Access the admin panel through '/cms' by default
# meta: 'cms' # Store form data of each content into a 'cms' field by default (inside metadata)
# Secret, required by signed cookie session
secret: 'keyboard cat blog'
# Implement the logic you want for authentication
auth: (login, password, callback) ->
if login is 'admin' and password is '<PASSWORD>'
callback null, true
else
callback "Invalid login or password.", false
# List all the content that is managed by the plugin
models: [
# Example of a content that is unique and only has 1 entry
name: ['Configuration', 'Configuration'] # First is singular name, second is plural. Here we use the same because we never have multiple "Configurations"
unique: true # Make this model "unique", that means there can only be 1 entry, not more, not less
form:
url: "/index" # Save configuration meta in index file
ext: 'html.md' # With a ".html.md" extension
# Set the metadata template of the file
# Each function that we put in the metadata will be called and the result will be used
# The context (this, @) contains the @docpad instance, a @slugify function and all the properties of the current model
meta:
title: -> @title
layout: 'home'
about: -> @about
# The content follows the metadata. For this file, it is in markdown (because we are making a html.md file)
content: -> @title
# For each model, we can create a form with several components that will allow the user to input data
components: [
# A 'title' field with a text input component (notice that we use this title field in the metadata template, above)
field: 'title'
label: 'Website Title' # The label is what will appear as field name in the form for the admin panel
type: 'text'
,
# Another text input component to type the Author of the website (this one is still stored in the cms: key of the meta, but we don't really use it for now. Maybe later?)
field: 'author'
label: 'Website Author'
type: 'text'
,
# An 'about' field using a plain textarea component
field: 'about'
label: 'About me'
type: 'textarea'
height: 100
,
# A color picker example
field: 'myColor'
label: 'My Favourite Color'
type: 'color'
,
# We can choose a 'category' with a choice component.
field: 'category'
label: 'Category'
type: 'choice'
expanded: true # The component will be "expanded" using html radio inputs
# The data: option returns an array of available categories.
# For this example, it is hardcoded but you can make your own logic using @docpad collections
data: -> ['Sport', 'News']
,
# We add a 'sub-category' field that depends on the 'category' field
field: 'subCategory'
deps: ['category'] # This field will update when the category field changes value
label: 'Sub-category'
type: 'choice'
# Here, we use the @category value to decide which sub-categories are available
# It will be called each time the field reloads
data: ->
if @category is 'Sport'
return ['Footbal', 'Tennis', 'Handball', 'Swimming']
else if @category is 'News'
return ['Technology', 'Finance', 'Gossip']
else # No category selected, then no sub-category available
return []
,
# Allow the user to change the blog logo by uploading an image
field: 'logo'
label: 'Website Logo'
type: 'file'
use: 'standard' # There can be multiple image profiles, here we define the one that will be displayed inside the form
optional: true # We can make a field optional
images: # Image profiles
# For this field, we only make 1 profile called 'standard' that will resize the image to fit in a 220x220 rectangle.
standard:
# You can hardcode an extension (png, jpg, gif), or use the @ext value to dynamically generate the right type.
# Also works with animated gifs (but a bit experimental)
url: -> "/logo.#{@ext}" # The url to create for the image
width: 220 # The maximum width of the image
height: 220 # The maximum height of the image
,
# An example of rich text field 'wysiwyg' component
# The resulting value will be valid html
field: 'wysiwygExample'
label: 'Wysiwyg example'
type: 'wysiwyg'
height: 450 # Optional, set the height of the field inside the form
,
# An example of 'markdown' component, so you can choose your philosophy: wysiwyg or markdown
field: 'markdownExample'
label: 'Markdown example'
type: 'markdown'
height: 450 # Optional, set the height of the field inside the form
]
,
# Example of a model that can have several entries.
# We are making a blog, so we need articles!
name: ['Article', 'Articles'] # First is singular form, second is plural form. Note that urls inside admin panel will be generated by slugifying those names.
list:
# Because this model can have several entries, we need a list page.
# Here is the configuration of it
# A list is showing several 'fields' of each entries inside a table layout
fields: [
name: 'Title' # Name of the 'field' in the table
value: -> @title # The function will be called and the value will be used for display. Inside the function, you have access to all the entry's meta
,
name: 'Image'
# If you want to display html that won't be escaped, use 'html' instead of 'value'
html: ->
if @image?
return '<div style="height:32px"><img src="'+@image.square.url+'" style="width:32px;height:32px" alt="image" /></div>'
else
return '<div style="height:32px"> - </div>'
,
name: 'Tags'
html: ->
if @tags instanceof Array
return @tags.join(', ')
else
return ''
]
# You can add filters to you list to make browsing easier
filters: [
name: 'Tag' # Filter by tag
# The data function returns all the available values to use on the filter
# Here, we are walking through the articles to find all tags
data: ->
tags = []
filter = type: 'article'
for item in @docpad.getCollection('html').findAll(filter).models
itemTags = item.get('tags')
if itemTags instanceof Array
for tag in itemTags
if not (tag in tags)
tags.push tag
return tags
,
# A custom filter to choose articles with image or articles without image only
name: 'Kind'
data: -> ['With Image', 'Textual']
]
# The list's data function is returning all the entries of the list.
# It is in charge to take in account the filters values
# When a filter changes, this function is called again to update the list
# The result of this function can be a Docpad Collection or a JSON-like array
data: ->
filter = type: 'article'
# Filter by kind (with image or not)
if @kind is 'with-image'
filter.image = $ne: null
else if @kind is 'textual'
filter.image = null
collection = @docpad.getCollection('html').findAll(filter)
if @tag?
# Filter by tags
finalModels = []
if collection.models instanceof Array
for model in collection.models
tags = model.get('tags')
for tag in tags
if @slugify(tag) is @tag
finalModels.push model.toJSON()
break
return finalModels
else
return collection
form:
# As with the configuration model, we need a form to add/edit articles
url: -> "/blog/#{@slugify @title}" # Each article's url. We slugify the title to generate the url
ext: 'html.md'
meta:
title: -> @title
type: 'article'
layout: 'article'
image: -> @image
tags: -> if @tags instanceof Array then @tags else []
date: -> new Date(@date)
content: -> @content
components: [
field: 'title'
type: 'text'
,
# A 'date' field with a datetime picker
field: 'date'
type: 'date'
# You can remove the hours by adding time: false
#time: false
,
# Choose the tags of your article
field: 'tags'
type: 'tags'
data: ->
# The data is used for autocompletion
tags = []
for item in @docpad.getCollection('html').findAll().models
itemTags = item.get('tags')
if itemTags instanceof Array
for tag in itemTags
if not (tag in tags)
tags.push tag
return tags
,
field: 'content'
type: 'markdown'
# You can add your custom validator on any field
# Well, this is actually useless here because the default validator is doing the same check,
# but feel free to check more things for your own needs.
validate: (val) -> typeof(val) is 'string' and val.length > 0
# You can also add your custom sanitizer that will be called before saving the content
sanitize: (val) -> return val?.trim()
,
field: 'image'
type: 'file'
use: 'thumbnail'
optional: true
images:
# This time we have 3 image profiles
# Each of them will be generated from the original picture
# Notice they all have a different url
standard:
url: -> "/blog/#{@slugify @title}.#{@ext}"
width: 498
height: 9999999
thumbnail:
url: -> "/blog/#{@slugify @title}.tn.#{@ext}"
width: 9999999
height: 128
square:
url: -> "/blog/#{@slugify @title}.sq.#{@ext}"
width: 32
height: 32
crop: true # With this option, the image will be cropped in order to have the exact 32x32 size
]
,
# Another model to add links on the sidebar of the blog
# Nothing more than the articles model
name: ['Link', 'Links']
list:
fields: [
name: 'Name'
value: -> @title
,
name: 'URL'
html: -> @href
]
data: ->
filter = type: 'link'
return @docpad.getCollection('html').findAll(filter)
form:
url: -> "/link/#{@slugify @name}"
ext: 'html.md'
meta:
title: -><NAME> @name
type: 'link'
layout: 'link'
href: -> @url
content: -> @url
components: [
field: 'name'
type: 'text'
,
field: 'url'
label: 'URL'
type: 'text'
]
]
| true | module.exports =
# The data generated by minicms is just like any other content
# So we can create custom collections or simply add template helpers
templateData:
getIndex: ->
@getCollection('html').findOne(url: '/')?.toJSON()
getArticles: ->
@getCollection('html').findAllLive(type: 'article').sortArray(date:-1)
getLinks: ->
@getCollection('html').findAllLive(type: 'link').sortArray(name:1)
plugins:
# This contains all the configuration of minicms, used for the admin panel of our blog
# It allows you to define lists, forms and how to generate the final content
minicms:
#prefix:
# url: 'cms' # Access the admin panel through '/cms' by default
# meta: 'cms' # Store form data of each content into a 'cms' field by default (inside metadata)
# Secret, required by signed cookie session
secret: 'keyboard cat blog'
# Implement the logic you want for authentication
auth: (login, password, callback) ->
if login is 'admin' and password is 'PI:PASSWORD:<PASSWORD>END_PI'
callback null, true
else
callback "Invalid login or password.", false
# List all the content that is managed by the plugin
models: [
# Example of a content that is unique and only has 1 entry
name: ['Configuration', 'Configuration'] # First is singular name, second is plural. Here we use the same because we never have multiple "Configurations"
unique: true # Make this model "unique", that means there can only be 1 entry, not more, not less
form:
url: "/index" # Save configuration meta in index file
ext: 'html.md' # With a ".html.md" extension
# Set the metadata template of the file
# Each function that we put in the metadata will be called and the result will be used
# The context (this, @) contains the @docpad instance, a @slugify function and all the properties of the current model
meta:
title: -> @title
layout: 'home'
about: -> @about
# The content follows the metadata. For this file, it is in markdown (because we are making a html.md file)
content: -> @title
# For each model, we can create a form with several components that will allow the user to input data
components: [
# A 'title' field with a text input component (notice that we use this title field in the metadata template, above)
field: 'title'
label: 'Website Title' # The label is what will appear as field name in the form for the admin panel
type: 'text'
,
# Another text input component to type the Author of the website (this one is still stored in the cms: key of the meta, but we don't really use it for now. Maybe later?)
field: 'author'
label: 'Website Author'
type: 'text'
,
# An 'about' field using a plain textarea component
field: 'about'
label: 'About me'
type: 'textarea'
height: 100
,
# A color picker example
field: 'myColor'
label: 'My Favourite Color'
type: 'color'
,
# We can choose a 'category' with a choice component.
field: 'category'
label: 'Category'
type: 'choice'
expanded: true # The component will be "expanded" using html radio inputs
# The data: option returns an array of available categories.
# For this example, it is hardcoded but you can make your own logic using @docpad collections
data: -> ['Sport', 'News']
,
# We add a 'sub-category' field that depends on the 'category' field
field: 'subCategory'
deps: ['category'] # This field will update when the category field changes value
label: 'Sub-category'
type: 'choice'
# Here, we use the @category value to decide which sub-categories are available
# It will be called each time the field reloads
data: ->
if @category is 'Sport'
return ['Footbal', 'Tennis', 'Handball', 'Swimming']
else if @category is 'News'
return ['Technology', 'Finance', 'Gossip']
else # No category selected, then no sub-category available
return []
,
# Allow the user to change the blog logo by uploading an image
field: 'logo'
label: 'Website Logo'
type: 'file'
use: 'standard' # There can be multiple image profiles, here we define the one that will be displayed inside the form
optional: true # We can make a field optional
images: # Image profiles
# For this field, we only make 1 profile called 'standard' that will resize the image to fit in a 220x220 rectangle.
standard:
# You can hardcode an extension (png, jpg, gif), or use the @ext value to dynamically generate the right type.
# Also works with animated gifs (but a bit experimental)
url: -> "/logo.#{@ext}" # The url to create for the image
width: 220 # The maximum width of the image
height: 220 # The maximum height of the image
,
# An example of rich text field 'wysiwyg' component
# The resulting value will be valid html
field: 'wysiwygExample'
label: 'Wysiwyg example'
type: 'wysiwyg'
height: 450 # Optional, set the height of the field inside the form
,
# An example of 'markdown' component, so you can choose your philosophy: wysiwyg or markdown
field: 'markdownExample'
label: 'Markdown example'
type: 'markdown'
height: 450 # Optional, set the height of the field inside the form
]
,
# Example of a model that can have several entries.
# We are making a blog, so we need articles!
name: ['Article', 'Articles'] # First is singular form, second is plural form. Note that urls inside admin panel will be generated by slugifying those names.
list:
# Because this model can have several entries, we need a list page.
# Here is the configuration of it
# A list is showing several 'fields' of each entries inside a table layout
fields: [
name: 'Title' # Name of the 'field' in the table
value: -> @title # The function will be called and the value will be used for display. Inside the function, you have access to all the entry's meta
,
name: 'Image'
# If you want to display html that won't be escaped, use 'html' instead of 'value'
html: ->
if @image?
return '<div style="height:32px"><img src="'+@image.square.url+'" style="width:32px;height:32px" alt="image" /></div>'
else
return '<div style="height:32px"> - </div>'
,
name: 'Tags'
html: ->
if @tags instanceof Array
return @tags.join(', ')
else
return ''
]
# You can add filters to you list to make browsing easier
filters: [
name: 'Tag' # Filter by tag
# The data function returns all the available values to use on the filter
# Here, we are walking through the articles to find all tags
data: ->
tags = []
filter = type: 'article'
for item in @docpad.getCollection('html').findAll(filter).models
itemTags = item.get('tags')
if itemTags instanceof Array
for tag in itemTags
if not (tag in tags)
tags.push tag
return tags
,
# A custom filter to choose articles with image or articles without image only
name: 'Kind'
data: -> ['With Image', 'Textual']
]
# The list's data function is returning all the entries of the list.
# It is in charge to take in account the filters values
# When a filter changes, this function is called again to update the list
# The result of this function can be a Docpad Collection or a JSON-like array
data: ->
filter = type: 'article'
# Filter by kind (with image or not)
if @kind is 'with-image'
filter.image = $ne: null
else if @kind is 'textual'
filter.image = null
collection = @docpad.getCollection('html').findAll(filter)
if @tag?
# Filter by tags
finalModels = []
if collection.models instanceof Array
for model in collection.models
tags = model.get('tags')
for tag in tags
if @slugify(tag) is @tag
finalModels.push model.toJSON()
break
return finalModels
else
return collection
form:
# As with the configuration model, we need a form to add/edit articles
url: -> "/blog/#{@slugify @title}" # Each article's url. We slugify the title to generate the url
ext: 'html.md'
meta:
title: -> @title
type: 'article'
layout: 'article'
image: -> @image
tags: -> if @tags instanceof Array then @tags else []
date: -> new Date(@date)
content: -> @content
components: [
field: 'title'
type: 'text'
,
# A 'date' field with a datetime picker
field: 'date'
type: 'date'
# You can remove the hours by adding time: false
#time: false
,
# Choose the tags of your article
field: 'tags'
type: 'tags'
data: ->
# The data is used for autocompletion
tags = []
for item in @docpad.getCollection('html').findAll().models
itemTags = item.get('tags')
if itemTags instanceof Array
for tag in itemTags
if not (tag in tags)
tags.push tag
return tags
,
field: 'content'
type: 'markdown'
# You can add your custom validator on any field
# Well, this is actually useless here because the default validator is doing the same check,
# but feel free to check more things for your own needs.
validate: (val) -> typeof(val) is 'string' and val.length > 0
# You can also add your custom sanitizer that will be called before saving the content
sanitize: (val) -> return val?.trim()
,
field: 'image'
type: 'file'
use: 'thumbnail'
optional: true
images:
# This time we have 3 image profiles
# Each of them will be generated from the original picture
# Notice they all have a different url
standard:
url: -> "/blog/#{@slugify @title}.#{@ext}"
width: 498
height: 9999999
thumbnail:
url: -> "/blog/#{@slugify @title}.tn.#{@ext}"
width: 9999999
height: 128
square:
url: -> "/blog/#{@slugify @title}.sq.#{@ext}"
width: 32
height: 32
crop: true # With this option, the image will be cropped in order to have the exact 32x32 size
]
,
# Another model to add links on the sidebar of the blog
# Nothing more than the articles model
name: ['Link', 'Links']
list:
fields: [
name: 'Name'
value: -> @title
,
name: 'URL'
html: -> @href
]
data: ->
filter = type: 'link'
return @docpad.getCollection('html').findAll(filter)
form:
url: -> "/link/#{@slugify @name}"
ext: 'html.md'
meta:
title: ->PI:NAME:<NAME>END_PI @name
type: 'link'
layout: 'link'
href: -> @url
content: -> @url
components: [
field: 'name'
type: 'text'
,
field: 'url'
label: 'URL'
type: 'text'
]
]
|
[
{
"context": "Autocomplete.ContainerConfiguration\n token: 'asdfdsf'\n el: $('[data-id=test]')\n url: @sandbo",
"end": 670,
"score": 0.9838557243347168,
"start": 663,
"tag": "PASSWORD",
"value": "asdfdsf"
},
{
"context": "(@server, [{\n 'id': '1',\n 'task_nam... | spec/dash-autocomplete/integration/render_search_results.coffee | samaritanministries/dash-autocomplete.js | 0 | describe 'Rendering search results', ->
class CollectionView extends Backbone.View
render: ->
@$el.html('Collection View Template')
@
showNoResults: ->
showError: ->
showResults: (data) ->
@render()
collection = new Backbone.Collection(data)
collection.each((model) => @$el.append(model.get('task_name')))
searchCriteriaCleared: ->
beforeEach ->
jasmine.clock().install()
setFixtures('<div data-id="test"></div>')
@sandboxUrl = 'https://sandbox.smchcn.net/smi/api/TaskItems/search'
@server = sinon.fakeServer.create()
configs = new DashAutocomplete.ContainerConfiguration
token: 'asdfdsf'
el: $('[data-id=test]')
url: @sandboxUrl
resultsView: new CollectionView()
.configuration()
@containerView = new DashAutocomplete.ContainerView(configs).render()
stubSearchResults = (server, response) ->
server.respondWith(
'POST',
'https://sandbox.smchcn.net/smi/api/TaskItems/search',
[200, { 'Content-Type': 'application/json' }, JSON.stringify(response)]
)
waitForSearchToFinish = ->
jasmine.clock().tick(111111000000) #this is ridiculous, but I can't get the debounce to time properly
afterEach ->
jasmine.clock().uninstall()
it 'renders the container view', ->
expect(@containerView.$el).toContainText('Collection View Template')
it 'renders search results', ->
stubSearchResults(@server, [{
'id': '1',
'task_name': 'First Task'
}, {
'id': '2',
'task_name': 'Second Task'
}])
$('[data-id=text-input]').val('test').keyup()
waitForSearchToFinish()
@server.respond()
expect(@containerView.$el).toContainText('First Task')
expect(@containerView.$el).toContainText('Second Task')
it 'renders search results, and toggles spinner before request completes', ->
stubSearchResults(@server, [])
$('[data-id=text-input]').val('test').keyup()
waitForSearchToFinish()
spinnerContainer = @containerView.$('[data-id=spinner-container]')
expect(spinnerContainer).toHaveClass("dash-spinner")
@server.respond()
expect(spinnerContainer).not.toHaveClass("dash-spinner")
| 213196 | describe 'Rendering search results', ->
class CollectionView extends Backbone.View
render: ->
@$el.html('Collection View Template')
@
showNoResults: ->
showError: ->
showResults: (data) ->
@render()
collection = new Backbone.Collection(data)
collection.each((model) => @$el.append(model.get('task_name')))
searchCriteriaCleared: ->
beforeEach ->
jasmine.clock().install()
setFixtures('<div data-id="test"></div>')
@sandboxUrl = 'https://sandbox.smchcn.net/smi/api/TaskItems/search'
@server = sinon.fakeServer.create()
configs = new DashAutocomplete.ContainerConfiguration
token: '<PASSWORD>'
el: $('[data-id=test]')
url: @sandboxUrl
resultsView: new CollectionView()
.configuration()
@containerView = new DashAutocomplete.ContainerView(configs).render()
stubSearchResults = (server, response) ->
server.respondWith(
'POST',
'https://sandbox.smchcn.net/smi/api/TaskItems/search',
[200, { 'Content-Type': 'application/json' }, JSON.stringify(response)]
)
waitForSearchToFinish = ->
jasmine.clock().tick(111111000000) #this is ridiculous, but I can't get the debounce to time properly
afterEach ->
jasmine.clock().uninstall()
it 'renders the container view', ->
expect(@containerView.$el).toContainText('Collection View Template')
it 'renders search results', ->
stubSearchResults(@server, [{
'id': '1',
'task_name': '<NAME> Task'
}, {
'id': '2',
'task_name': '<NAME>'
}])
$('[data-id=text-input]').val('test').keyup()
waitForSearchToFinish()
@server.respond()
expect(@containerView.$el).toContainText('First Task')
expect(@containerView.$el).toContainText('Second Task')
it 'renders search results, and toggles spinner before request completes', ->
stubSearchResults(@server, [])
$('[data-id=text-input]').val('test').keyup()
waitForSearchToFinish()
spinnerContainer = @containerView.$('[data-id=spinner-container]')
expect(spinnerContainer).toHaveClass("dash-spinner")
@server.respond()
expect(spinnerContainer).not.toHaveClass("dash-spinner")
| true | describe 'Rendering search results', ->
class CollectionView extends Backbone.View
render: ->
@$el.html('Collection View Template')
@
showNoResults: ->
showError: ->
showResults: (data) ->
@render()
collection = new Backbone.Collection(data)
collection.each((model) => @$el.append(model.get('task_name')))
searchCriteriaCleared: ->
beforeEach ->
jasmine.clock().install()
setFixtures('<div data-id="test"></div>')
@sandboxUrl = 'https://sandbox.smchcn.net/smi/api/TaskItems/search'
@server = sinon.fakeServer.create()
configs = new DashAutocomplete.ContainerConfiguration
token: 'PI:PASSWORD:<PASSWORD>END_PI'
el: $('[data-id=test]')
url: @sandboxUrl
resultsView: new CollectionView()
.configuration()
@containerView = new DashAutocomplete.ContainerView(configs).render()
stubSearchResults = (server, response) ->
server.respondWith(
'POST',
'https://sandbox.smchcn.net/smi/api/TaskItems/search',
[200, { 'Content-Type': 'application/json' }, JSON.stringify(response)]
)
waitForSearchToFinish = ->
jasmine.clock().tick(111111000000) #this is ridiculous, but I can't get the debounce to time properly
afterEach ->
jasmine.clock().uninstall()
it 'renders the container view', ->
expect(@containerView.$el).toContainText('Collection View Template')
it 'renders search results', ->
stubSearchResults(@server, [{
'id': '1',
'task_name': 'PI:NAME:<NAME>END_PI Task'
}, {
'id': '2',
'task_name': 'PI:NAME:<NAME>END_PI'
}])
$('[data-id=text-input]').val('test').keyup()
waitForSearchToFinish()
@server.respond()
expect(@containerView.$el).toContainText('First Task')
expect(@containerView.$el).toContainText('Second Task')
it 'renders search results, and toggles spinner before request completes', ->
stubSearchResults(@server, [])
$('[data-id=text-input]').val('test').keyup()
waitForSearchToFinish()
spinnerContainer = @containerView.$('[data-id=spinner-container]')
expect(spinnerContainer).toHaveClass("dash-spinner")
@server.respond()
expect(spinnerContainer).not.toHaveClass("dash-spinner")
|
[
{
"context": "###*\n * CrowdSync version 0.6.5\n * (c) 2011 Central Christian Church - www.centralaz.com\n * CrowdSync may be freely di",
"end": 68,
"score": 0.9965288639068604,
"start": 44,
"tag": "NAME",
"value": "Central Christian Church"
}
] | coffeescripts/public/crowdsync.coffee | CentralAZ/CrowdSync | 1 | ###*
* CrowdSync version 0.6.5
* (c) 2011 Central Christian Church - www.centralaz.com
* CrowdSync may be freely distributed under the MIT license.
* For all details and documentation head to https://github.com/centralaz/crowdsync
###
class window.CrowdSync
constructor: (options = {}) ->
if options then @settings = options
@initSettings(options)
if @settings.useCanvas is false then @loadNotesFromDom() else @initCanvas()
@initDocument()
# Initializes settings to their defaults when app is initialized
initSettings: (options) ->
@deltaOffset = Number.MAX_VALUE
@playHeadIndex = 0
@settings.cycleLength = options.cycleLength or 10
@settings.campus = options.campus or 1
@settings.displayLogo = options.displayLogo or false
@settings.displaySplash = options.displaySplash or false
@settings.serverCheckCount = 1
@settings.displayCountDown = options.displayCountDown or true
@settings.countDownLength = options.countDownLength or 30000
@settings.debugging = options.debugging or false
@settings.notes = options.notes or ['a','b','c','d']
@settings.randomizeColor = if options.randomizeColor? then options.randomizeColor else true
@clientNotes = []
@settings.useCanvas = options.useCanvas or false
@settings.shouldPlayAudio = options.shouldPlayAudio or false
@settings.audioStartOffset = options.audioStartOffset or 0
@settings.audioFileName = options.audioFileName or ''
if @settings.shouldPlayAudio is true
@audio = new Audio(@settings.audioFileName)
@playingAudio = false
@testAudio()
# Kicks the tires on audio playback.
testAudio: ->
if typeof webkitAudioContext is 'undefined' then return
@audioContext = new webkitAudioContext()
@source = @audioContext.createBufferSource();
@processor = @audioContext.createJavaScriptNode(2048);
# When audio metadata becomes available, log end date to determine any possible delay in playback
audioAvailable = (event) => @processor.onaudioprocess = null
@source.connect(@processor)
@processor.connect(@audioContext.destination)
request = new XMLHttpRequest()
request.open('GET', @settings.audioFileName, true)
request.responseType = 'arraybuffer'
# Attempts to load file via ArrayBuffer from an AJAX request and autoplay.
request.onload = () =>
@source.buffer = @audioContext.createBuffer(request.response, false)
@source.looping = true
@processor.onaudioprocess = audioAvailable
@source.noteOn(0)
request.send()
# Prepares DOM based on default/client settings
initDocument: ->
if @settings.displayCountDown is true then $('<div class="count-down"/>').appendTo('body')
if @settings.debugging is true then $('<div id="debug"/>').appendTo('body')
if @settings.displayLogo is true
for note in @clientNotes
$(".#{note}").addClass("logo-#{note}")
# Based on user settings will gather the "notes" the client is responsible for playing
loadNotesFromDom: ->
addNote = (note, array) ->
if $.inArray(note, array) is -1 then array.push(note)
# If we've already got the DOM configured with colors, don't do anything...
if @settings.randomizeColor is false
# Find the notes that are defined in the markup to store in settings
for note in @settings.notes
if $('.main-screen').hasClass(note)
addNote(note, @clientNotes)
if @settings.debugging is false then $('.main-screen').text('')
else
# Add new note to the dom and store them in settings
that = @
$('.main-screen').removeClass(@settings.notes.join(' ')).each ->
i = Math.floor(Math.random() * that.settings.notes.length)
theNote = that.settings.notes[i]
$(this).addClass(theNote)
addNote(theNote, that.clientNotes)
if that.settings.debugging is true then $(this).text(theNote)
# Wrapper for console.log to guard against errors in browsers that don't support it
log: (message) ->
if typeof console isnt 'undefined' and console.log then console.log(message)
# After getting the current notes to watch, and the track from the server,
# filter out any ticks in the current track that the client doesn't need
# to care about.
filterNotes: ->
@currentTrack.ticks = $.grep @currentTrack.ticks, (element, index) =>
hasNotes = $.grep element.notes, (note, i) =>
result = $.inArray(note, @clientNotes)
result > -1
hasNotes.length > 0
if @settings.debugging is true
@log('Filtering out mismatched notes...')
@log(@currentTrack)
# Once notes have been filtered, set each tick's play time based on adjusted start time
convertToClientTime: ->
if @settings.debugging is true then @log("Current start time: #{@currentTrack.startTime}")
@currentTrack.startTime = @currentTrack.startTime + @deltaOffset
# Countdown starts 30 sec prior to start time
@currentTrack.countDownStartTime = @currentTrack.startTime - @settings.countDownLength
$.each @currentTrack.ticks, (index, value) =>
value.time += @currentTrack.startTime
if @settings.debugging is true
@log 'Converting relative timecodes to client time...'
@log(@currentTrack)
# Formats seconds passed in to a more human readable format: e.g. - 3:16
formatCountDownTime: (seconds) ->
minutes = Math.floor(seconds / 60) % 60
seconds = seconds % 60
if minutes > 0
if seconds.toString().length is 1 then seconds = "0#{seconds}"
return "#{minutes}:#{seconds}"
else return seconds
# Writes debugging timer info to the DOM
writeTimerInfo: (delta) ->
$ul = $('<ul/>')
$ul.append "<li>Client Time: #{@clientTime.getTime()}</li>"
$ul.append "<li>Server Time: #{@serverTime}</li>"
$ul.append "<li>Delta: #{delta}</li>"
$ul.append "<li>Min Delta: #{@deltaOffset}</li>"
$ul.prependTo '#debug'
# Initiate polling the server to get the difference between client and server time
start: (count) ->
if @debugging is true then $('<div id="debug"/>').appendTo 'body'
@deltaCount = count
@deltaTimer = setInterval(=>
@getDelta()
, 500)
# Pings the server to check the current time
getDelta: ->
$.ajax
url: '/CrowdSync.asmx/GetTime'
type: 'GET'
data: ''
contentType: 'application/json; charset=utf-8'
dataType: 'json'
success: (result) =>
@serverTime = result.d
@clientTime = new Date()
delta = @clientTime.getTime() - @serverTime
@deltaOffset = delta if delta < @deltaOffset
if @settings.debugging is true then @writeTimerInfo(delta)
# When we're done computing the time delta, load the next track...
if @settings.serverCheckCount++ >= @deltaCount
clearTimeout(@deltaTimer)
@loadNextTrack()
false
error: (result, status, error) =>
clearTimeout(@deltaTimer)
if @settings.debugging is true then @log(result.responseText)
false
# Loads the next track to play
loadNextTrack: ->
if @settings.debugging is true then @log('Loading next track...')
$.ajax
url: "/CrowdSync.asmx/GetNextStartByCampusID?campusID=#{@settings.campus}"
type: 'GET'
data: ''
contentType: 'application/json; charset=utf-8'
dataType: 'json'
success: (result) =>
startTime = result.d.startTime
endTime = startTime + @currentTrack.ticks[@currentTrack.ticks.length - 1].time + @deltaOffset
@currentTrack.startTime = startTime
@currentTrack.endTime = endTime
if @settings.debugging is true
serverTime = new Date(@currentTrack.startTime)
$('#debug').prepend "<h3>Server Start Time: #{serverTime.toTimeString()}.#{serverTime.getMilliseconds()}</h3>"
@filterNotes()
@convertToClientTime()
if @settings.debugging is true
adjustedTime = new Date(@currentTrack.startTime)
$('#debug').prepend "<h3>Adjusted Start Time: #{adjustedTime.toTimeString()}.#{adjustedTime.getMilliseconds()}</h3>"
$('#debug').prepend "Current Notes: #{@clientNotes.join(', ')}"
@countDownTimer = setInterval(=>
@countDown()
, @settings.cycleLength)
false
error: (result, status, error) =>
if @settings.debugging is true then @log(result.responseText)
false
# Determines if/when to show the countdown on the DOM and plays audio
countDown: ->
theTime = new Date()
# Has the count down started yet?
if @currentTrack.countDownStartTime <= theTime # and theTime < @currentTrack.startTime
# Counting Down...
remainingMilliseconds = @currentTrack.startTime - theTime.getTime()
# Is it time to play the audio track?
audioPlayTime = @currentTrack.startTime + @settings.audioStartOffset + @settings.cycleLength # - @audioDelay
if @settings.shouldPlayAudio is true and audioPlayTime <= theTime and @playingAudio is false
if @settings.debugging then @log 'Playing audio...'
@audio.play()
@playingAudio = true
if @settings.debugging then $('.main-screen').text(remainingMilliseconds)
if remainingMilliseconds <= 0
if @settings.displayLogo is true then $('.main-screen').removeClass("logo-#{@settings.notes.join(' logo-')}")
if @settings.displaySplash is true then $('.splash').removeClass('splash')
clearTimeout(@countDownTimer)
@play()
if @settings.displayCountDown is true
remainingSeconds = Math.ceil(remainingMilliseconds / 1000)
$('.count-down').text(@formatCountDownTime(remainingSeconds))
if remainingMilliseconds <= 0
$('.count-down').fadeOut 'slow', -> $(this).remove()
# Initiates visual element, whether displayed via DOM manipulation or Canvas
play: ->
if @settings.debugging is true then @log "Starting tick..."
func = if @settings.useCanvas is false then @paintDom else @paintCanvas
@cycleTimer = setInterval(=>
@tick(func)
, @settings.cycleLength)
# Determines the current position within the song and will start or stop visualization
tick: (callback) ->
theTime = new Date()
currentTick = @currentTrack.ticks[@playHeadIndex]
if currentTick? and theTime >= currentTick.time
callback.call(@, theTime, currentTick)
@playHeadIndex += 1
# Stop playing, the current song has ended...
else if theTime > @currentTrack.endTime
clearTimeout(@cycleTimer)
if @settings.useCanvas is true then @clearCanvas()
if @settings.debugging is true then @log('Song has ended...')
if @settings.shouldPlayAudio is true
if @settings.debugging is true then 'Stopping audio track...'
setTimeout(=>
@audio.pause()
@playingAudio = false
, 1000)
# Presentation has finished, fade out...
setTimeout(->
$('.overlay').fadeIn('slow')
, 3000)
# Load next track once the current one has completed...
#@loadNextTrack()
# Displays song data to the DOM via adding classes to '.main-screen' elements
paintDom: (theTime, theTick) ->
selector = ".#{theTick.notes.join(', .')}"
$(selector).removeClass('off')
setTimeout(->
$(selector).addClass('off')
, theTick.duration)
# Prepares canvas for visualization to be drawn
initCanvas: ->
@clientNotes = @settings.notes
if @settings.debugging then @log 'Initializing canvas...'
@canvasWidth = 1240 # 1280 document.width
@canvasHeight = 728 # 768 document.height
@canvas = document.getElementById('main-screen')
@canvas.width = @canvasWidth
@canvas.height = @canvasHeight
@context = @canvas.getContext('2d')
@lights = []
@plotTree()
# Plots points of light on Canvas x,y and assigns colors in Christmas tree visualization
plotTree: ->
# Plot Christmas Tree lights here...
if @settings.debugging then @log 'Plotting points...'
colSpacing = 17
rowSpacing = colSpacing
xOffset = Math.ceil(@canvasWidth / 2)
yOffset = Math.ceil(@canvasHeight * .05)
for i in [0..38]
if i is 38 then cols = 4
else if i is 37 then cols = 7
else if i > 0 then cols = Math.ceil(i / 4 + 2)
else cols = 1
yPos = (i * rowSpacing) + yOffset
colSpacing += .05
widthFactor = Math.sin((i+5) / 18) * 50
for j in [0..cols]
xPos = xOffset - (cols * widthFactor / 2) + (j * widthFactor)
index = Math.floor(Math.random() * @settings.notes.length)
noteName = @settings.notes[index]
xPos = @nudge(xPos)
yPos = @nudge(yPos)
@lights.push(
x: xPos
innerX: xPos
y: yPos
innerY: yPos
color: @canvasColors[noteName]
note: @settings.notes[index]
)
if @settings.debugging is true then @log @lights
# Paint lights ~100 frames per second
@canvasTimer = setInterval(=>
@paintLights()
, @settings.cycleLength)
# Clears canvas and kills timer that controls rendering tree to free up resources
clearCanvas: ->
clearTimeout(@canvasTimer)
@context.clearRect(0, 0, @canvasWidth, @canvasHeight)
# Randomizes light position based on it's initial position to make the tree appaer more organic
nudge: (n) ->
d = Math.floor(Math.random() * 10)
n + if Math.random() > .5 then -d else d
# Creates variance in position of blur effect on each 'light'
nudgeBlur: (n, center, radius) ->
d = if Math.random() * 100 > 30 then 1 else 0
d = if Math.random() > .5 then -d else d
n = n + d
if n >= center + radius - 3 then n = n - 1
else if n <= center - radius + 3 then n = n + 1
n
# Assigns alpha values of each 'light' on the canvas and sets up a timeout to fade out the lights
paintCanvas: (theTime, theTick) ->
for note in theTick.notes
if @settings.debugging is true then @log note
@canvasColors[note].a = 0.81
setTimeout(=>
@lightsOut(theTick)
, theTick.duration)
# Actually paints each light on the Canvas
paintLights: ->
# Draw lights onto canvas here...
@context.clearRect(0, 0, @canvasWidth, @canvasHeight)
radians = Math.PI * 2
radius = 13
for light in @lights
color = @canvasColors[light.note]
#@context.fillStyle = "rgba(#{color.r}, #{color.g}, #{color.b}, #{color.a})"
light.innerX = @nudgeBlur(light.innerX, light.x, radius)
light.innerY = @nudgeBlur(light.innerY, light.y, radius)
gradient = @context.createRadialGradient(light.innerX, light.innerY, 0, light.x, light.y, radius)
gradient.addColorStop(0.6, "rgba(#{color.r}, #{color.g}, #{color.b}, #{color.a})")
gradient.addColorStop(1, "rgba(#{color.r}, #{color.g}, #{color.b}, 0)")
@context.fillStyle = gradient
@context.beginPath()
@context.arc(light.x, light.y, radius, 0, radians, true)
@context.closePath()
@context.fill()
# Stores a reference to timer ID and initializes callback to 'dim' lights
lightsOut: (theTick) ->
if @settings.debugging is true then "Turning off '#{theTick.notes.join(', ')}'"
fadeTimer = setInterval(=>
@fadeLights(theTick)
, @settings.cycleLength)
theTick.fadeTimer = fadeTimer
# Fades out lights by decrementing the alpha value. Sets to 0 and kills fade timer when less than 5% opacity
fadeLights: (theTick) ->
for note in theTick.notes
@canvasColors[note].a -= .5
if @canvasColors[note].a <= 0.05
@canvasColors[note].a = 0
clearTimeout(theTick.fadeTimer)
# Object to represent color values for Christmas tree light visualization
canvasColors:
a: { r: 255, g: 4, b: 38, a: 0 }, # a - Red
b: { r: 0, g: 201, b: 235, a: 0 }, # b - Blue
c: { r: 46, g: 248, b: 25, a: 0 }, # c - Green
d: { r: 255, g: 224, b: 0, a: 0 } # d - Yellow
# Object composed of decoded MIDI representing time signature of the light display
currentTrack:
startTime: 123578916,
endTime: 12345667,
ticks: [
# 1
{ notes: ["a"], time: 19, duration: 900 },
{ notes: ["b"], time: 986, duration: 900 },
{ notes: ["c"], time: 1939, duration: 900 },
{ notes: ["d"], time: 2908, duration: 900 },
{ notes: ["a"], time: 3879, duration: 900 },
{ notes: ["b"], time: 4843, duration: 900 },
{ notes: ["c"], time: 5811, duration: 900 },
{ notes: ["d"], time: 6801, duration: 900 },
{ notes: ["a"], time: 7747, duration: 900 },
{ notes: ["b"], time: 8715, duration: 900 },
{ notes: ["c"], time: 9682, duration: 900 },
{ notes: ["d"], time: 10645, duration: 900 },
{ notes: ["a"], time: 11607, duration: 900 },
{ notes: ["b"], time: 12585, duration: 900 },
{ notes: ["c"], time: 13556, duration: 900 },
{ notes: ["d"], time: 14521, duration: 900 },
# 9
{ notes: ["a"], time: 15486, duration: 900 },
{ notes: ["b"], time: 16455, duration: 900 },
{ notes: ["c"], time: 17415, duration: 900 },
{ notes: ["d"], time: 18419, duration: 900 },
{ notes: ["a"], time: 19362, duration: 900 },
{ notes: ["b"], time: 20294, duration: 900 },
{ notes: ["c"], time: 21275, duration: 900 },
{ notes: ["d"], time: 22263, duration: 900 },
{ notes: ["c"], time: 23235, duration: 307 },
{ notes: ["a"], time: 23876, duration: 159 },
{ notes: ["c"], time: 24198, duration: 309 },
{ notes: ["a"], time: 24843, duration: 155 },
{ notes: ["c"], time: 25162, duration: 327 },
{ notes: ["a"], time: 25811, duration: 163 },
{ notes: ["c"], time: 26134, duration: 315 },
{ notes: ["a"], time: 26779, duration: 162 },
{ notes: ["c"], time: 27101, duration: 324 },
{ notes: ["a"], time: 27746, duration: 164 },
{ notes: ["c"], time: 28067, duration: 326 },
{ notes: ["a"], time: 28714, duration: 161 },
# 16
{ notes: ["c"], time: 29037, duration: 324 },
{ notes: ["a"], time: 29682, duration: 161 },
{ notes: ["c"], time: 30005, duration: 323 },
{ notes: ["a"], time: 30650, duration: 161 },
{ notes: ["d"], time: 30972, duration: 324 },
{ notes: ["b"], time: 31940, duration: 326 },
{ notes: ["c"], time: 32908, duration: 330 },
{ notes: ["a"], time: 33875, duration: 324 },
{ notes: ["a"], time: 36778, duration: 160 },
{ notes: ["b"], time: 37101, duration: 162 },
{ notes: ["c"], time: 37424, duration: 162 },
{ notes: ["d"], time: 37746, duration: 164 },
{ notes: ["a"], time: 38069, duration: 325 },
{ notes: ["b"], time: 38392, duration: 162 },
{ notes: ["a"], time: 39682, duration: 162 },
{ notes: ["b"], time: 40005, duration: 161 },
{ notes: ["c"], time: 40327, duration: 163 },
# 22
{ notes: ["a"], time: 41617, duration: 165 },
{ notes: ["b"], time: 41940, duration: 163 },
{ notes: ["c"], time: 42263, duration: 161 },
{ notes: ["d"], time: 46456, duration: 322 },
{ notes: ["c"], time: 46783, duration: 322 },
{ notes: ["b"], time: 47100, duration: 161 },
{ notes: ["a"], time: 47424, duration: 322 },
{ notes: ["d"], time: 47751, duration: 320 },
{ notes: ["c"], time: 48069, duration: 320 },
{ notes: ["d"], time: 48393, duration: 320 },
{ notes: ["c"], time: 48719, duration: 320 },
{ notes: ["b"], time: 49037, duration: 162 },
{ notes: ["a"], time: 49359, duration: 328 },
{ notes: ["d"], time: 49682, duration: 322 },
{ notes: ["c"], time: 50009, duration: 316 },
# 27
{ notes: ["d"], time: 54197, duration: 324 },
{ notes: ["c"], time: 54521, duration: 323 },
{ notes: ["b"], time: 54842, duration: 161 },
{ notes: ["a"], time: 55165, duration: 324 },
{ notes: ["d"], time: 55488, duration: 324 },
{ notes: ["c"], time: 55811, duration: 325 },
{ notes: ["d"], time: 56134, duration: 323 },
{ notes: ["c"], time: 56456, duration: 322 },
{ notes: ["b"], time: 56783, duration: 157 },
{ notes: ["a"], time: 57101, duration: 322 },
{ notes: ["d"], time: 57428, duration: 322 },
{ notes: ["c"], time: 57746, duration: 162 },
{ notes: ["b"], time: 58069, duration: 321 },
{ notes: ["d"], time: 58714, duration: 325 },
{ notes: ["b"], time: 59037, duration: 324 },
{ notes: ["d"], time: 59684, duration: 323 },
# 32
{ notes: ["b"], time: 60004, duration: 325 },
{ notes: ["d"], time: 60650, duration: 324 },
{ notes: ["b"], time: 60972, duration: 323 },
{ notes: ["d"], time: 61617, duration: 326 },
{ notes: ["b"], time: 61940, duration: 323 },
{ notes: ["d"], time: 62585, duration: 325 },
{ notes: ["b"], time: 62908, duration: 322 },
{ notes: ["d"], time: 63549, duration: 328 },
{ notes: ["b"], time: 63875, duration: 321 },
{ notes: ["d"], time: 64521, duration: 319 },
{ notes: ["b"], time: 64838, duration: 343 },
{ notes: ["d"], time: 65488, duration: 327 },
{ notes: ["b"], time: 65811, duration: 319 },
{ notes: ["d"], time: 66456, duration: 324 },
{ notes: ["b"], time: 66777, duration: 328 },
{ notes: ["d"], time: 67424, duration: 324 },
{ notes: ["b"], time: 67746, duration: 325 },
{ notes: ["d"], time: 68392, duration: 324 },
{ notes: ["b"], time: 68714, duration: 325 },
{ notes: ["d"], time: 69359, duration: 325 },
{ notes: ["b"], time: 69683, duration: 321 },
{ notes: ["d"], time: 70326, duration: 321 },
{ notes: ["b"], time: 70651, duration: 321 },
{ notes: ["d"], time: 71294, duration: 323 },
# 38
{ notes: ["b"], time: 71617, duration: 322 },
{ notes: ["d"], time: 72263, duration: 322 },
{ notes: ["b"], time: 72585, duration: 323 },
{ notes: ["d"], time: 73230, duration: 323 },
{ notes: ["b"], time: 73553, duration: 323 },
{ notes: ["d"], time: 74198, duration: 323 },
{ notes: ["b"], time: 74526, duration: 318 },
{ notes: ["d"], time: 75166, duration: 322 },
{ notes: ["b"], time: 75495, duration: 315 },
{ notes: ["d"], time: 76134, duration: 321 },
{ notes: ["b"], time: 76460, duration: 320 },
{ notes: ["a","c"], time: 77425, duration: 161 },
{ notes: ["a","c"], time: 78392, duration: 161 },
{ notes: ["a","c"], time: 79363, duration: 164 },
{ notes: ["a","c"], time: 80327, duration: 161 },
{ notes: ["a","c"], time: 81294, duration: 167 },
{ notes: ["a","c"], time: 82262, duration: 167 },
# 44
{ notes: ["a","c"], time: 83230, duration: 159 },
{ notes: ["b","d"], time: 84198, duration: 162 },
{ notes: ["a","c"], time: 85166, duration: 159 },
{ notes: ["a","c"], time: 86137, duration: 162 },
{ notes: ["a","c"], time: 87101, duration: 163 },
{ notes: ["a","c"], time: 88066, duration: 132 },
{ notes: ["a","c"], time: 89038, duration: 158 },
{ notes: ["a","c"], time: 90004, duration: 170 },
{ notes: ["a","c"], time: 90972, duration: 161 },
{ notes: ["b","d"], time: 91940, duration: 165 },
{ notes: ["a"], time: 92909, duration: 1937 },
{ notes: ["b"], time: 94843, duration: 1936 },
{ notes: ["c"], time: 96779, duration: 1937 },
# 52
{ notes: ["d"], time: 98714, duration: 1940 },
{ notes: ["a"], time: 100650, duration: 1938 },
{ notes: ["b"], time: 102585, duration: 900 },
{ notes: ["c"], time: 103553, duration: 900 },
{ notes: ["d"], time: 104521, duration: 163 },
{ notes: ["c"], time: 105487, duration: 157 },
{ notes: ["b"], time: 106456, duration: 163 },
{ notes: ["a"], time: 107425, duration: 156 },
{ notes: ["d"], time: 108391, duration: 162 },
{ notes: ["c"], time: 109359, duration: 159 },
{ notes: ["b"], time: 110326, duration: 164 },
{ notes: ["a"], time: 111295, duration: 160 },
# pg 2, 59
{ notes: ["a","c"], time: 112264, duration: 166 },
{ notes: ["a","c"], time: 113230, duration: 159 },
{ notes: ["a","c"], time: 114198, duration: 167 },
{ notes: ["a","c"], time: 115164, duration: 134 },
{ notes: ["a","c"], time: 116133, duration: 161 },
{ notes: ["a","c"], time: 117101, duration: 163 },
{ notes: ["a","c"], time: 118069, duration: 160 },
{ notes: ["b","d"], time: 119037, duration: 160 },
{ notes: ["a","c"], time: 120004, duration: 164 },
{ notes: ["a","c"], time: 120972, duration: 164 },
{ notes: ["a","c"], time: 121940, duration: 163 },
{ notes: ["a","c"], time: 122907, duration: 162 },
{ notes: ["a","c"], time: 123874, duration: 164 },
{ notes: ["a","c"], time: 124843, duration: 161 },
# 66
{ notes: ["a","c"], time: 125811, duration: 164 },
{ notes: ["b","d"], time: 126780, duration: 160 },
{ notes: ["a"], time: 127746, duration: 1939 },
{ notes: ["b"], time: 129682, duration: 1938 },
{ notes: ["c"], time: 131617, duration: 1934 },
{ notes: ["d"], time: 133556, duration: 1934 },
{ notes: ["a"], time: 135488, duration: 1936 },
{ notes: ["b"], time: 137424, duration: 900 },
{ notes: ["c"], time: 138391, duration: 900 },
{ notes: ["d"], time: 139359, duration: 1937 },
{ notes: ["a"], time: 141294, duration: 1937 },
{ notes: ["b"], time: 143230, duration: 1937 },
# 76
{ notes: ["c"], time: 145327, duration: 1775 },
{ notes: ["a"], time: 166461, duration: 900 },
{ notes: ["b"], time: 167426, duration: 900 },
{ notes: ["c"], time: 168386, duration: 900 },
{ notes: ["d"], time: 169359, duration: 900 },
{ notes: ["a"], time: 170328, duration: 900 },
{ notes: ["b"], time: 171295, duration: 900 },
{ notes: ["c"], time: 172265, duration: 900 },
{ notes: ["d"], time: 173227, duration: 900 },
{ notes: ["a"], time: 174198, duration: 900 },
{ notes: ["b"], time: 175165, duration: 900 },
{ notes: ["c"], time: 176126, duration: 900 },
{ notes: ["d"], time: 177104, duration: 900 },
# 93
{ notes: ["a"], time: 178068, duration: 900 },
{ notes: ["b"], time: 179036, duration: 900 },
{ notes: ["c"], time: 180008, duration: 900 },
{ notes: ["d"], time: 180972, duration: 900 },
{ notes: ["a"], time: 181936, duration: 164 },
{ notes: ["b"], time: 182907, duration: 159 },
{ notes: ["c"], time: 183875, duration: 159 },
{ notes: ["d"], time: 184843, duration: 162 },
{ notes: ["d"], time: 185488, duration: 163 },
{ notes: ["a"], time: 187746, duration: 163 },
{ notes: ["b"], time: 188069, duration: 160 },
{ notes: ["c"], time: 189036, duration: 200 },
{ notes: ["d"], time: 189359, duration: 161 },
{ notes: ["d"], time: 190649, duration: 326 },
{ notes: ["a"], time: 191295, duration: 163 },
# 100
{ notes: ["b"], time: 192587, duration: 330 },
{ notes: ["d"], time: 193230, duration: 164 },
{ notes: ["b"], time: 193552, duration: 320 },
{ notes: ["d"], time: 194197, duration: 164 },
{ notes: ["b"], time: 194520, duration: 324 },
{ notes: ["d"], time: 195165, duration: 162 },
{ notes: ["b"], time: 195488, duration: 325 },
{ notes: ["d"], time: 196133, duration: 162 },
{ notes: ["b"], time: 196456, duration: 322 },
{ notes: ["d"], time: 197101, duration: 159 },
{ notes: ["a"], time: 197424, duration: 161 },
{ notes: ["b"], time: 197746, duration: 150 },
{ notes: ["a"], time: 197907, duration: 160 },
{ notes: ["c"], time: 198071, duration: 160 },
{ notes: ["d"], time: 198230, duration: 163 },
{ notes: ["a"], time: 198391, duration: 162 },
{ notes: ["b"], time: 198714, duration: 150 },
{ notes: ["a"], time: 198875, duration: 161 },
{ notes: ["c"], time: 199036, duration: 162 },
{ notes: ["d"], time: 199198, duration: 161 },
{ notes: ["a"], time: 199359, duration: 162 },
{ notes: ["b"], time: 199682, duration: 150 },
{ notes: ["a"], time: 199843, duration: 163 },
{ notes: ["c"], time: 200004, duration: 161 },
{ notes: ["d"], time: 200170, duration: 157 },
{ notes: ["c"], time: 200327, duration: 160 },
{ notes: ["b"], time: 200649, duration: 107 },
{ notes: ["a"], time: 200811, duration: 150 },
{ notes: ["c"], time: 200972, duration: 150 },
# 106
{ notes: ["a"], time: 203231, duration: 162 },
{ notes: ["b"], time: 203398, duration: 153 },
{ notes: ["c"], time: 203555, duration: 162 },
{ notes: ["d"], time: 203714, duration: 161 },
{ notes: ["a"], time: 203883, duration: 153 },
{ notes: ["b"], time: 204036, duration: 163 },
{ notes: ["c"], time: 204198, duration: 159 },
{ notes: ["d"], time: 204360, duration: 162 },
{ notes: ["a"], time: 204520, duration: 320 },
{ notes: ["c"], time: 204846, duration: 155 },
{ notes: ["a"], time: 206133, duration: 163 },
{ notes: ["b"], time: 206294, duration: 164 },
{ notes: ["c"], time: 206456, duration: 165 },
{ notes: ["d"], time: 206617, duration: 163 },
{ notes: ["a"], time: 206778, duration: 164 },
{ notes: ["c"], time: 206940, duration: 163 },
{ notes: ["a"], time: 208069, duration: 167 },
{ notes: ["b"], time: 208230, duration: 159 },
{ notes: ["c"], time: 208395, duration: 158 },
{ notes: ["d"], time: 208558, duration: 159 },
{ notes: ["a"], time: 208715, duration: 162 },
{ notes: ["c"], time: 208875, duration: 150 },
{ notes: ["b"], time: 209036, duration: 326 },
{ notes: ["d"], time: 209682, duration: 163 },
{ notes: ["b"], time: 210003, duration: 323 },
{ notes: ["d"], time: 210649, duration: 161 },
{ notes: ["b"], time: 210971, duration: 327 },
{ notes: ["d"], time: 211616, duration: 163 },
{ notes: ["b"], time: 211940, duration: 322 },
{ notes: ["d"], time: 212585, duration: 162 },
# 111
{ notes: ["b"], time: 212907, duration: 323 },
{ notes: ["d"], time: 213553, duration: 159 },
{ notes: ["b"], time: 213875, duration: 323 },
{ notes: ["d"], time: 214520, duration: 162 },
{ notes: ["b"], time: 214844, duration: 321 },
{ notes: ["d"], time: 215488, duration: 161 },
{ notes: ["b"], time: 215811, duration: 324 },
{ notes: ["d"], time: 216456, duration: 161 },
{ notes: ["b"], time: 216778, duration: 324 },
{ notes: ["d"], time: 217424, duration: 150 },
{ notes: ["b"], time: 217746, duration: 323 },
{ notes: ["d"], time: 218391, duration: 160 },
{ notes: ["b"], time: 218714, duration: 323 },
{ notes: ["d"], time: 219359, duration: 161 },
{ notes: ["b"], time: 219683, duration: 320 },
{ notes: ["d"], time: 220327, duration: 150 },
{ notes: ["b"], time: 220649, duration: 324 },
{ notes: ["d"], time: 221294, duration: 161 },
{ notes: ["b"], time: 221617, duration: 323 },
{ notes: ["d"], time: 222262, duration: 161 },
{ notes: ["b"], time: 222584, duration: 325 },
{ notes: ["d"], time: 223230, duration: 160 },
{ notes: ["b"], time: 223553, duration: 323 },
{ notes: ["d"], time: 224198, duration: 161 },
# 117
{ notes: ["a","c"], time: 224520, duration: 162 },
{ notes: ["b","d"], time: 225488, duration: 162 },
{ notes: ["a","c"], time: 226456, duration: 163 },
{ notes: ["b","d"], time: 227423, duration: 161 },
{ notes: ["a","b","c","d"], time: 228390, duration: 3551 },
{ notes: ["a","b","c","d"], time: 232262, duration: 162 }
] | 30984 | ###*
* CrowdSync version 0.6.5
* (c) 2011 <NAME> - www.centralaz.com
* CrowdSync may be freely distributed under the MIT license.
* For all details and documentation head to https://github.com/centralaz/crowdsync
###
class window.CrowdSync
constructor: (options = {}) ->
if options then @settings = options
@initSettings(options)
if @settings.useCanvas is false then @loadNotesFromDom() else @initCanvas()
@initDocument()
# Initializes settings to their defaults when app is initialized
initSettings: (options) ->
@deltaOffset = Number.MAX_VALUE
@playHeadIndex = 0
@settings.cycleLength = options.cycleLength or 10
@settings.campus = options.campus or 1
@settings.displayLogo = options.displayLogo or false
@settings.displaySplash = options.displaySplash or false
@settings.serverCheckCount = 1
@settings.displayCountDown = options.displayCountDown or true
@settings.countDownLength = options.countDownLength or 30000
@settings.debugging = options.debugging or false
@settings.notes = options.notes or ['a','b','c','d']
@settings.randomizeColor = if options.randomizeColor? then options.randomizeColor else true
@clientNotes = []
@settings.useCanvas = options.useCanvas or false
@settings.shouldPlayAudio = options.shouldPlayAudio or false
@settings.audioStartOffset = options.audioStartOffset or 0
@settings.audioFileName = options.audioFileName or ''
if @settings.shouldPlayAudio is true
@audio = new Audio(@settings.audioFileName)
@playingAudio = false
@testAudio()
# Kicks the tires on audio playback.
testAudio: ->
if typeof webkitAudioContext is 'undefined' then return
@audioContext = new webkitAudioContext()
@source = @audioContext.createBufferSource();
@processor = @audioContext.createJavaScriptNode(2048);
# When audio metadata becomes available, log end date to determine any possible delay in playback
audioAvailable = (event) => @processor.onaudioprocess = null
@source.connect(@processor)
@processor.connect(@audioContext.destination)
request = new XMLHttpRequest()
request.open('GET', @settings.audioFileName, true)
request.responseType = 'arraybuffer'
# Attempts to load file via ArrayBuffer from an AJAX request and autoplay.
request.onload = () =>
@source.buffer = @audioContext.createBuffer(request.response, false)
@source.looping = true
@processor.onaudioprocess = audioAvailable
@source.noteOn(0)
request.send()
# Prepares DOM based on default/client settings
initDocument: ->
if @settings.displayCountDown is true then $('<div class="count-down"/>').appendTo('body')
if @settings.debugging is true then $('<div id="debug"/>').appendTo('body')
if @settings.displayLogo is true
for note in @clientNotes
$(".#{note}").addClass("logo-#{note}")
# Based on user settings will gather the "notes" the client is responsible for playing
loadNotesFromDom: ->
addNote = (note, array) ->
if $.inArray(note, array) is -1 then array.push(note)
# If we've already got the DOM configured with colors, don't do anything...
if @settings.randomizeColor is false
# Find the notes that are defined in the markup to store in settings
for note in @settings.notes
if $('.main-screen').hasClass(note)
addNote(note, @clientNotes)
if @settings.debugging is false then $('.main-screen').text('')
else
# Add new note to the dom and store them in settings
that = @
$('.main-screen').removeClass(@settings.notes.join(' ')).each ->
i = Math.floor(Math.random() * that.settings.notes.length)
theNote = that.settings.notes[i]
$(this).addClass(theNote)
addNote(theNote, that.clientNotes)
if that.settings.debugging is true then $(this).text(theNote)
# Wrapper for console.log to guard against errors in browsers that don't support it
log: (message) ->
if typeof console isnt 'undefined' and console.log then console.log(message)
# After getting the current notes to watch, and the track from the server,
# filter out any ticks in the current track that the client doesn't need
# to care about.
filterNotes: ->
@currentTrack.ticks = $.grep @currentTrack.ticks, (element, index) =>
hasNotes = $.grep element.notes, (note, i) =>
result = $.inArray(note, @clientNotes)
result > -1
hasNotes.length > 0
if @settings.debugging is true
@log('Filtering out mismatched notes...')
@log(@currentTrack)
# Once notes have been filtered, set each tick's play time based on adjusted start time
convertToClientTime: ->
if @settings.debugging is true then @log("Current start time: #{@currentTrack.startTime}")
@currentTrack.startTime = @currentTrack.startTime + @deltaOffset
# Countdown starts 30 sec prior to start time
@currentTrack.countDownStartTime = @currentTrack.startTime - @settings.countDownLength
$.each @currentTrack.ticks, (index, value) =>
value.time += @currentTrack.startTime
if @settings.debugging is true
@log 'Converting relative timecodes to client time...'
@log(@currentTrack)
# Formats seconds passed in to a more human readable format: e.g. - 3:16
formatCountDownTime: (seconds) ->
minutes = Math.floor(seconds / 60) % 60
seconds = seconds % 60
if minutes > 0
if seconds.toString().length is 1 then seconds = "0#{seconds}"
return "#{minutes}:#{seconds}"
else return seconds
# Writes debugging timer info to the DOM
writeTimerInfo: (delta) ->
$ul = $('<ul/>')
$ul.append "<li>Client Time: #{@clientTime.getTime()}</li>"
$ul.append "<li>Server Time: #{@serverTime}</li>"
$ul.append "<li>Delta: #{delta}</li>"
$ul.append "<li>Min Delta: #{@deltaOffset}</li>"
$ul.prependTo '#debug'
# Initiate polling the server to get the difference between client and server time
start: (count) ->
if @debugging is true then $('<div id="debug"/>').appendTo 'body'
@deltaCount = count
@deltaTimer = setInterval(=>
@getDelta()
, 500)
# Pings the server to check the current time
getDelta: ->
$.ajax
url: '/CrowdSync.asmx/GetTime'
type: 'GET'
data: ''
contentType: 'application/json; charset=utf-8'
dataType: 'json'
success: (result) =>
@serverTime = result.d
@clientTime = new Date()
delta = @clientTime.getTime() - @serverTime
@deltaOffset = delta if delta < @deltaOffset
if @settings.debugging is true then @writeTimerInfo(delta)
# When we're done computing the time delta, load the next track...
if @settings.serverCheckCount++ >= @deltaCount
clearTimeout(@deltaTimer)
@loadNextTrack()
false
error: (result, status, error) =>
clearTimeout(@deltaTimer)
if @settings.debugging is true then @log(result.responseText)
false
# Loads the next track to play
loadNextTrack: ->
if @settings.debugging is true then @log('Loading next track...')
$.ajax
url: "/CrowdSync.asmx/GetNextStartByCampusID?campusID=#{@settings.campus}"
type: 'GET'
data: ''
contentType: 'application/json; charset=utf-8'
dataType: 'json'
success: (result) =>
startTime = result.d.startTime
endTime = startTime + @currentTrack.ticks[@currentTrack.ticks.length - 1].time + @deltaOffset
@currentTrack.startTime = startTime
@currentTrack.endTime = endTime
if @settings.debugging is true
serverTime = new Date(@currentTrack.startTime)
$('#debug').prepend "<h3>Server Start Time: #{serverTime.toTimeString()}.#{serverTime.getMilliseconds()}</h3>"
@filterNotes()
@convertToClientTime()
if @settings.debugging is true
adjustedTime = new Date(@currentTrack.startTime)
$('#debug').prepend "<h3>Adjusted Start Time: #{adjustedTime.toTimeString()}.#{adjustedTime.getMilliseconds()}</h3>"
$('#debug').prepend "Current Notes: #{@clientNotes.join(', ')}"
@countDownTimer = setInterval(=>
@countDown()
, @settings.cycleLength)
false
error: (result, status, error) =>
if @settings.debugging is true then @log(result.responseText)
false
# Determines if/when to show the countdown on the DOM and plays audio
countDown: ->
theTime = new Date()
# Has the count down started yet?
if @currentTrack.countDownStartTime <= theTime # and theTime < @currentTrack.startTime
# Counting Down...
remainingMilliseconds = @currentTrack.startTime - theTime.getTime()
# Is it time to play the audio track?
audioPlayTime = @currentTrack.startTime + @settings.audioStartOffset + @settings.cycleLength # - @audioDelay
if @settings.shouldPlayAudio is true and audioPlayTime <= theTime and @playingAudio is false
if @settings.debugging then @log 'Playing audio...'
@audio.play()
@playingAudio = true
if @settings.debugging then $('.main-screen').text(remainingMilliseconds)
if remainingMilliseconds <= 0
if @settings.displayLogo is true then $('.main-screen').removeClass("logo-#{@settings.notes.join(' logo-')}")
if @settings.displaySplash is true then $('.splash').removeClass('splash')
clearTimeout(@countDownTimer)
@play()
if @settings.displayCountDown is true
remainingSeconds = Math.ceil(remainingMilliseconds / 1000)
$('.count-down').text(@formatCountDownTime(remainingSeconds))
if remainingMilliseconds <= 0
$('.count-down').fadeOut 'slow', -> $(this).remove()
# Initiates visual element, whether displayed via DOM manipulation or Canvas
play: ->
if @settings.debugging is true then @log "Starting tick..."
func = if @settings.useCanvas is false then @paintDom else @paintCanvas
@cycleTimer = setInterval(=>
@tick(func)
, @settings.cycleLength)
# Determines the current position within the song and will start or stop visualization
tick: (callback) ->
theTime = new Date()
currentTick = @currentTrack.ticks[@playHeadIndex]
if currentTick? and theTime >= currentTick.time
callback.call(@, theTime, currentTick)
@playHeadIndex += 1
# Stop playing, the current song has ended...
else if theTime > @currentTrack.endTime
clearTimeout(@cycleTimer)
if @settings.useCanvas is true then @clearCanvas()
if @settings.debugging is true then @log('Song has ended...')
if @settings.shouldPlayAudio is true
if @settings.debugging is true then 'Stopping audio track...'
setTimeout(=>
@audio.pause()
@playingAudio = false
, 1000)
# Presentation has finished, fade out...
setTimeout(->
$('.overlay').fadeIn('slow')
, 3000)
# Load next track once the current one has completed...
#@loadNextTrack()
# Displays song data to the DOM via adding classes to '.main-screen' elements
paintDom: (theTime, theTick) ->
selector = ".#{theTick.notes.join(', .')}"
$(selector).removeClass('off')
setTimeout(->
$(selector).addClass('off')
, theTick.duration)
# Prepares canvas for visualization to be drawn
initCanvas: ->
@clientNotes = @settings.notes
if @settings.debugging then @log 'Initializing canvas...'
@canvasWidth = 1240 # 1280 document.width
@canvasHeight = 728 # 768 document.height
@canvas = document.getElementById('main-screen')
@canvas.width = @canvasWidth
@canvas.height = @canvasHeight
@context = @canvas.getContext('2d')
@lights = []
@plotTree()
# Plots points of light on Canvas x,y and assigns colors in Christmas tree visualization
plotTree: ->
# Plot Christmas Tree lights here...
if @settings.debugging then @log 'Plotting points...'
colSpacing = 17
rowSpacing = colSpacing
xOffset = Math.ceil(@canvasWidth / 2)
yOffset = Math.ceil(@canvasHeight * .05)
for i in [0..38]
if i is 38 then cols = 4
else if i is 37 then cols = 7
else if i > 0 then cols = Math.ceil(i / 4 + 2)
else cols = 1
yPos = (i * rowSpacing) + yOffset
colSpacing += .05
widthFactor = Math.sin((i+5) / 18) * 50
for j in [0..cols]
xPos = xOffset - (cols * widthFactor / 2) + (j * widthFactor)
index = Math.floor(Math.random() * @settings.notes.length)
noteName = @settings.notes[index]
xPos = @nudge(xPos)
yPos = @nudge(yPos)
@lights.push(
x: xPos
innerX: xPos
y: yPos
innerY: yPos
color: @canvasColors[noteName]
note: @settings.notes[index]
)
if @settings.debugging is true then @log @lights
# Paint lights ~100 frames per second
@canvasTimer = setInterval(=>
@paintLights()
, @settings.cycleLength)
# Clears canvas and kills timer that controls rendering tree to free up resources
clearCanvas: ->
clearTimeout(@canvasTimer)
@context.clearRect(0, 0, @canvasWidth, @canvasHeight)
# Randomizes light position based on it's initial position to make the tree appaer more organic
nudge: (n) ->
d = Math.floor(Math.random() * 10)
n + if Math.random() > .5 then -d else d
# Creates variance in position of blur effect on each 'light'
nudgeBlur: (n, center, radius) ->
d = if Math.random() * 100 > 30 then 1 else 0
d = if Math.random() > .5 then -d else d
n = n + d
if n >= center + radius - 3 then n = n - 1
else if n <= center - radius + 3 then n = n + 1
n
# Assigns alpha values of each 'light' on the canvas and sets up a timeout to fade out the lights
paintCanvas: (theTime, theTick) ->
for note in theTick.notes
if @settings.debugging is true then @log note
@canvasColors[note].a = 0.81
setTimeout(=>
@lightsOut(theTick)
, theTick.duration)
# Actually paints each light on the Canvas
paintLights: ->
# Draw lights onto canvas here...
@context.clearRect(0, 0, @canvasWidth, @canvasHeight)
radians = Math.PI * 2
radius = 13
for light in @lights
color = @canvasColors[light.note]
#@context.fillStyle = "rgba(#{color.r}, #{color.g}, #{color.b}, #{color.a})"
light.innerX = @nudgeBlur(light.innerX, light.x, radius)
light.innerY = @nudgeBlur(light.innerY, light.y, radius)
gradient = @context.createRadialGradient(light.innerX, light.innerY, 0, light.x, light.y, radius)
gradient.addColorStop(0.6, "rgba(#{color.r}, #{color.g}, #{color.b}, #{color.a})")
gradient.addColorStop(1, "rgba(#{color.r}, #{color.g}, #{color.b}, 0)")
@context.fillStyle = gradient
@context.beginPath()
@context.arc(light.x, light.y, radius, 0, radians, true)
@context.closePath()
@context.fill()
# Stores a reference to timer ID and initializes callback to 'dim' lights
lightsOut: (theTick) ->
if @settings.debugging is true then "Turning off '#{theTick.notes.join(', ')}'"
fadeTimer = setInterval(=>
@fadeLights(theTick)
, @settings.cycleLength)
theTick.fadeTimer = fadeTimer
# Fades out lights by decrementing the alpha value. Sets to 0 and kills fade timer when less than 5% opacity
fadeLights: (theTick) ->
for note in theTick.notes
@canvasColors[note].a -= .5
if @canvasColors[note].a <= 0.05
@canvasColors[note].a = 0
clearTimeout(theTick.fadeTimer)
# Object to represent color values for Christmas tree light visualization
canvasColors:
a: { r: 255, g: 4, b: 38, a: 0 }, # a - Red
b: { r: 0, g: 201, b: 235, a: 0 }, # b - Blue
c: { r: 46, g: 248, b: 25, a: 0 }, # c - Green
d: { r: 255, g: 224, b: 0, a: 0 } # d - Yellow
# Object composed of decoded MIDI representing time signature of the light display
currentTrack:
startTime: 123578916,
endTime: 12345667,
ticks: [
# 1
{ notes: ["a"], time: 19, duration: 900 },
{ notes: ["b"], time: 986, duration: 900 },
{ notes: ["c"], time: 1939, duration: 900 },
{ notes: ["d"], time: 2908, duration: 900 },
{ notes: ["a"], time: 3879, duration: 900 },
{ notes: ["b"], time: 4843, duration: 900 },
{ notes: ["c"], time: 5811, duration: 900 },
{ notes: ["d"], time: 6801, duration: 900 },
{ notes: ["a"], time: 7747, duration: 900 },
{ notes: ["b"], time: 8715, duration: 900 },
{ notes: ["c"], time: 9682, duration: 900 },
{ notes: ["d"], time: 10645, duration: 900 },
{ notes: ["a"], time: 11607, duration: 900 },
{ notes: ["b"], time: 12585, duration: 900 },
{ notes: ["c"], time: 13556, duration: 900 },
{ notes: ["d"], time: 14521, duration: 900 },
# 9
{ notes: ["a"], time: 15486, duration: 900 },
{ notes: ["b"], time: 16455, duration: 900 },
{ notes: ["c"], time: 17415, duration: 900 },
{ notes: ["d"], time: 18419, duration: 900 },
{ notes: ["a"], time: 19362, duration: 900 },
{ notes: ["b"], time: 20294, duration: 900 },
{ notes: ["c"], time: 21275, duration: 900 },
{ notes: ["d"], time: 22263, duration: 900 },
{ notes: ["c"], time: 23235, duration: 307 },
{ notes: ["a"], time: 23876, duration: 159 },
{ notes: ["c"], time: 24198, duration: 309 },
{ notes: ["a"], time: 24843, duration: 155 },
{ notes: ["c"], time: 25162, duration: 327 },
{ notes: ["a"], time: 25811, duration: 163 },
{ notes: ["c"], time: 26134, duration: 315 },
{ notes: ["a"], time: 26779, duration: 162 },
{ notes: ["c"], time: 27101, duration: 324 },
{ notes: ["a"], time: 27746, duration: 164 },
{ notes: ["c"], time: 28067, duration: 326 },
{ notes: ["a"], time: 28714, duration: 161 },
# 16
{ notes: ["c"], time: 29037, duration: 324 },
{ notes: ["a"], time: 29682, duration: 161 },
{ notes: ["c"], time: 30005, duration: 323 },
{ notes: ["a"], time: 30650, duration: 161 },
{ notes: ["d"], time: 30972, duration: 324 },
{ notes: ["b"], time: 31940, duration: 326 },
{ notes: ["c"], time: 32908, duration: 330 },
{ notes: ["a"], time: 33875, duration: 324 },
{ notes: ["a"], time: 36778, duration: 160 },
{ notes: ["b"], time: 37101, duration: 162 },
{ notes: ["c"], time: 37424, duration: 162 },
{ notes: ["d"], time: 37746, duration: 164 },
{ notes: ["a"], time: 38069, duration: 325 },
{ notes: ["b"], time: 38392, duration: 162 },
{ notes: ["a"], time: 39682, duration: 162 },
{ notes: ["b"], time: 40005, duration: 161 },
{ notes: ["c"], time: 40327, duration: 163 },
# 22
{ notes: ["a"], time: 41617, duration: 165 },
{ notes: ["b"], time: 41940, duration: 163 },
{ notes: ["c"], time: 42263, duration: 161 },
{ notes: ["d"], time: 46456, duration: 322 },
{ notes: ["c"], time: 46783, duration: 322 },
{ notes: ["b"], time: 47100, duration: 161 },
{ notes: ["a"], time: 47424, duration: 322 },
{ notes: ["d"], time: 47751, duration: 320 },
{ notes: ["c"], time: 48069, duration: 320 },
{ notes: ["d"], time: 48393, duration: 320 },
{ notes: ["c"], time: 48719, duration: 320 },
{ notes: ["b"], time: 49037, duration: 162 },
{ notes: ["a"], time: 49359, duration: 328 },
{ notes: ["d"], time: 49682, duration: 322 },
{ notes: ["c"], time: 50009, duration: 316 },
# 27
{ notes: ["d"], time: 54197, duration: 324 },
{ notes: ["c"], time: 54521, duration: 323 },
{ notes: ["b"], time: 54842, duration: 161 },
{ notes: ["a"], time: 55165, duration: 324 },
{ notes: ["d"], time: 55488, duration: 324 },
{ notes: ["c"], time: 55811, duration: 325 },
{ notes: ["d"], time: 56134, duration: 323 },
{ notes: ["c"], time: 56456, duration: 322 },
{ notes: ["b"], time: 56783, duration: 157 },
{ notes: ["a"], time: 57101, duration: 322 },
{ notes: ["d"], time: 57428, duration: 322 },
{ notes: ["c"], time: 57746, duration: 162 },
{ notes: ["b"], time: 58069, duration: 321 },
{ notes: ["d"], time: 58714, duration: 325 },
{ notes: ["b"], time: 59037, duration: 324 },
{ notes: ["d"], time: 59684, duration: 323 },
# 32
{ notes: ["b"], time: 60004, duration: 325 },
{ notes: ["d"], time: 60650, duration: 324 },
{ notes: ["b"], time: 60972, duration: 323 },
{ notes: ["d"], time: 61617, duration: 326 },
{ notes: ["b"], time: 61940, duration: 323 },
{ notes: ["d"], time: 62585, duration: 325 },
{ notes: ["b"], time: 62908, duration: 322 },
{ notes: ["d"], time: 63549, duration: 328 },
{ notes: ["b"], time: 63875, duration: 321 },
{ notes: ["d"], time: 64521, duration: 319 },
{ notes: ["b"], time: 64838, duration: 343 },
{ notes: ["d"], time: 65488, duration: 327 },
{ notes: ["b"], time: 65811, duration: 319 },
{ notes: ["d"], time: 66456, duration: 324 },
{ notes: ["b"], time: 66777, duration: 328 },
{ notes: ["d"], time: 67424, duration: 324 },
{ notes: ["b"], time: 67746, duration: 325 },
{ notes: ["d"], time: 68392, duration: 324 },
{ notes: ["b"], time: 68714, duration: 325 },
{ notes: ["d"], time: 69359, duration: 325 },
{ notes: ["b"], time: 69683, duration: 321 },
{ notes: ["d"], time: 70326, duration: 321 },
{ notes: ["b"], time: 70651, duration: 321 },
{ notes: ["d"], time: 71294, duration: 323 },
# 38
{ notes: ["b"], time: 71617, duration: 322 },
{ notes: ["d"], time: 72263, duration: 322 },
{ notes: ["b"], time: 72585, duration: 323 },
{ notes: ["d"], time: 73230, duration: 323 },
{ notes: ["b"], time: 73553, duration: 323 },
{ notes: ["d"], time: 74198, duration: 323 },
{ notes: ["b"], time: 74526, duration: 318 },
{ notes: ["d"], time: 75166, duration: 322 },
{ notes: ["b"], time: 75495, duration: 315 },
{ notes: ["d"], time: 76134, duration: 321 },
{ notes: ["b"], time: 76460, duration: 320 },
{ notes: ["a","c"], time: 77425, duration: 161 },
{ notes: ["a","c"], time: 78392, duration: 161 },
{ notes: ["a","c"], time: 79363, duration: 164 },
{ notes: ["a","c"], time: 80327, duration: 161 },
{ notes: ["a","c"], time: 81294, duration: 167 },
{ notes: ["a","c"], time: 82262, duration: 167 },
# 44
{ notes: ["a","c"], time: 83230, duration: 159 },
{ notes: ["b","d"], time: 84198, duration: 162 },
{ notes: ["a","c"], time: 85166, duration: 159 },
{ notes: ["a","c"], time: 86137, duration: 162 },
{ notes: ["a","c"], time: 87101, duration: 163 },
{ notes: ["a","c"], time: 88066, duration: 132 },
{ notes: ["a","c"], time: 89038, duration: 158 },
{ notes: ["a","c"], time: 90004, duration: 170 },
{ notes: ["a","c"], time: 90972, duration: 161 },
{ notes: ["b","d"], time: 91940, duration: 165 },
{ notes: ["a"], time: 92909, duration: 1937 },
{ notes: ["b"], time: 94843, duration: 1936 },
{ notes: ["c"], time: 96779, duration: 1937 },
# 52
{ notes: ["d"], time: 98714, duration: 1940 },
{ notes: ["a"], time: 100650, duration: 1938 },
{ notes: ["b"], time: 102585, duration: 900 },
{ notes: ["c"], time: 103553, duration: 900 },
{ notes: ["d"], time: 104521, duration: 163 },
{ notes: ["c"], time: 105487, duration: 157 },
{ notes: ["b"], time: 106456, duration: 163 },
{ notes: ["a"], time: 107425, duration: 156 },
{ notes: ["d"], time: 108391, duration: 162 },
{ notes: ["c"], time: 109359, duration: 159 },
{ notes: ["b"], time: 110326, duration: 164 },
{ notes: ["a"], time: 111295, duration: 160 },
# pg 2, 59
{ notes: ["a","c"], time: 112264, duration: 166 },
{ notes: ["a","c"], time: 113230, duration: 159 },
{ notes: ["a","c"], time: 114198, duration: 167 },
{ notes: ["a","c"], time: 115164, duration: 134 },
{ notes: ["a","c"], time: 116133, duration: 161 },
{ notes: ["a","c"], time: 117101, duration: 163 },
{ notes: ["a","c"], time: 118069, duration: 160 },
{ notes: ["b","d"], time: 119037, duration: 160 },
{ notes: ["a","c"], time: 120004, duration: 164 },
{ notes: ["a","c"], time: 120972, duration: 164 },
{ notes: ["a","c"], time: 121940, duration: 163 },
{ notes: ["a","c"], time: 122907, duration: 162 },
{ notes: ["a","c"], time: 123874, duration: 164 },
{ notes: ["a","c"], time: 124843, duration: 161 },
# 66
{ notes: ["a","c"], time: 125811, duration: 164 },
{ notes: ["b","d"], time: 126780, duration: 160 },
{ notes: ["a"], time: 127746, duration: 1939 },
{ notes: ["b"], time: 129682, duration: 1938 },
{ notes: ["c"], time: 131617, duration: 1934 },
{ notes: ["d"], time: 133556, duration: 1934 },
{ notes: ["a"], time: 135488, duration: 1936 },
{ notes: ["b"], time: 137424, duration: 900 },
{ notes: ["c"], time: 138391, duration: 900 },
{ notes: ["d"], time: 139359, duration: 1937 },
{ notes: ["a"], time: 141294, duration: 1937 },
{ notes: ["b"], time: 143230, duration: 1937 },
# 76
{ notes: ["c"], time: 145327, duration: 1775 },
{ notes: ["a"], time: 166461, duration: 900 },
{ notes: ["b"], time: 167426, duration: 900 },
{ notes: ["c"], time: 168386, duration: 900 },
{ notes: ["d"], time: 169359, duration: 900 },
{ notes: ["a"], time: 170328, duration: 900 },
{ notes: ["b"], time: 171295, duration: 900 },
{ notes: ["c"], time: 172265, duration: 900 },
{ notes: ["d"], time: 173227, duration: 900 },
{ notes: ["a"], time: 174198, duration: 900 },
{ notes: ["b"], time: 175165, duration: 900 },
{ notes: ["c"], time: 176126, duration: 900 },
{ notes: ["d"], time: 177104, duration: 900 },
# 93
{ notes: ["a"], time: 178068, duration: 900 },
{ notes: ["b"], time: 179036, duration: 900 },
{ notes: ["c"], time: 180008, duration: 900 },
{ notes: ["d"], time: 180972, duration: 900 },
{ notes: ["a"], time: 181936, duration: 164 },
{ notes: ["b"], time: 182907, duration: 159 },
{ notes: ["c"], time: 183875, duration: 159 },
{ notes: ["d"], time: 184843, duration: 162 },
{ notes: ["d"], time: 185488, duration: 163 },
{ notes: ["a"], time: 187746, duration: 163 },
{ notes: ["b"], time: 188069, duration: 160 },
{ notes: ["c"], time: 189036, duration: 200 },
{ notes: ["d"], time: 189359, duration: 161 },
{ notes: ["d"], time: 190649, duration: 326 },
{ notes: ["a"], time: 191295, duration: 163 },
# 100
{ notes: ["b"], time: 192587, duration: 330 },
{ notes: ["d"], time: 193230, duration: 164 },
{ notes: ["b"], time: 193552, duration: 320 },
{ notes: ["d"], time: 194197, duration: 164 },
{ notes: ["b"], time: 194520, duration: 324 },
{ notes: ["d"], time: 195165, duration: 162 },
{ notes: ["b"], time: 195488, duration: 325 },
{ notes: ["d"], time: 196133, duration: 162 },
{ notes: ["b"], time: 196456, duration: 322 },
{ notes: ["d"], time: 197101, duration: 159 },
{ notes: ["a"], time: 197424, duration: 161 },
{ notes: ["b"], time: 197746, duration: 150 },
{ notes: ["a"], time: 197907, duration: 160 },
{ notes: ["c"], time: 198071, duration: 160 },
{ notes: ["d"], time: 198230, duration: 163 },
{ notes: ["a"], time: 198391, duration: 162 },
{ notes: ["b"], time: 198714, duration: 150 },
{ notes: ["a"], time: 198875, duration: 161 },
{ notes: ["c"], time: 199036, duration: 162 },
{ notes: ["d"], time: 199198, duration: 161 },
{ notes: ["a"], time: 199359, duration: 162 },
{ notes: ["b"], time: 199682, duration: 150 },
{ notes: ["a"], time: 199843, duration: 163 },
{ notes: ["c"], time: 200004, duration: 161 },
{ notes: ["d"], time: 200170, duration: 157 },
{ notes: ["c"], time: 200327, duration: 160 },
{ notes: ["b"], time: 200649, duration: 107 },
{ notes: ["a"], time: 200811, duration: 150 },
{ notes: ["c"], time: 200972, duration: 150 },
# 106
{ notes: ["a"], time: 203231, duration: 162 },
{ notes: ["b"], time: 203398, duration: 153 },
{ notes: ["c"], time: 203555, duration: 162 },
{ notes: ["d"], time: 203714, duration: 161 },
{ notes: ["a"], time: 203883, duration: 153 },
{ notes: ["b"], time: 204036, duration: 163 },
{ notes: ["c"], time: 204198, duration: 159 },
{ notes: ["d"], time: 204360, duration: 162 },
{ notes: ["a"], time: 204520, duration: 320 },
{ notes: ["c"], time: 204846, duration: 155 },
{ notes: ["a"], time: 206133, duration: 163 },
{ notes: ["b"], time: 206294, duration: 164 },
{ notes: ["c"], time: 206456, duration: 165 },
{ notes: ["d"], time: 206617, duration: 163 },
{ notes: ["a"], time: 206778, duration: 164 },
{ notes: ["c"], time: 206940, duration: 163 },
{ notes: ["a"], time: 208069, duration: 167 },
{ notes: ["b"], time: 208230, duration: 159 },
{ notes: ["c"], time: 208395, duration: 158 },
{ notes: ["d"], time: 208558, duration: 159 },
{ notes: ["a"], time: 208715, duration: 162 },
{ notes: ["c"], time: 208875, duration: 150 },
{ notes: ["b"], time: 209036, duration: 326 },
{ notes: ["d"], time: 209682, duration: 163 },
{ notes: ["b"], time: 210003, duration: 323 },
{ notes: ["d"], time: 210649, duration: 161 },
{ notes: ["b"], time: 210971, duration: 327 },
{ notes: ["d"], time: 211616, duration: 163 },
{ notes: ["b"], time: 211940, duration: 322 },
{ notes: ["d"], time: 212585, duration: 162 },
# 111
{ notes: ["b"], time: 212907, duration: 323 },
{ notes: ["d"], time: 213553, duration: 159 },
{ notes: ["b"], time: 213875, duration: 323 },
{ notes: ["d"], time: 214520, duration: 162 },
{ notes: ["b"], time: 214844, duration: 321 },
{ notes: ["d"], time: 215488, duration: 161 },
{ notes: ["b"], time: 215811, duration: 324 },
{ notes: ["d"], time: 216456, duration: 161 },
{ notes: ["b"], time: 216778, duration: 324 },
{ notes: ["d"], time: 217424, duration: 150 },
{ notes: ["b"], time: 217746, duration: 323 },
{ notes: ["d"], time: 218391, duration: 160 },
{ notes: ["b"], time: 218714, duration: 323 },
{ notes: ["d"], time: 219359, duration: 161 },
{ notes: ["b"], time: 219683, duration: 320 },
{ notes: ["d"], time: 220327, duration: 150 },
{ notes: ["b"], time: 220649, duration: 324 },
{ notes: ["d"], time: 221294, duration: 161 },
{ notes: ["b"], time: 221617, duration: 323 },
{ notes: ["d"], time: 222262, duration: 161 },
{ notes: ["b"], time: 222584, duration: 325 },
{ notes: ["d"], time: 223230, duration: 160 },
{ notes: ["b"], time: 223553, duration: 323 },
{ notes: ["d"], time: 224198, duration: 161 },
# 117
{ notes: ["a","c"], time: 224520, duration: 162 },
{ notes: ["b","d"], time: 225488, duration: 162 },
{ notes: ["a","c"], time: 226456, duration: 163 },
{ notes: ["b","d"], time: 227423, duration: 161 },
{ notes: ["a","b","c","d"], time: 228390, duration: 3551 },
{ notes: ["a","b","c","d"], time: 232262, duration: 162 }
] | true | ###*
* CrowdSync version 0.6.5
* (c) 2011 PI:NAME:<NAME>END_PI - www.centralaz.com
* CrowdSync may be freely distributed under the MIT license.
* For all details and documentation head to https://github.com/centralaz/crowdsync
###
class window.CrowdSync
constructor: (options = {}) ->
if options then @settings = options
@initSettings(options)
if @settings.useCanvas is false then @loadNotesFromDom() else @initCanvas()
@initDocument()
# Initializes settings to their defaults when app is initialized
initSettings: (options) ->
@deltaOffset = Number.MAX_VALUE
@playHeadIndex = 0
@settings.cycleLength = options.cycleLength or 10
@settings.campus = options.campus or 1
@settings.displayLogo = options.displayLogo or false
@settings.displaySplash = options.displaySplash or false
@settings.serverCheckCount = 1
@settings.displayCountDown = options.displayCountDown or true
@settings.countDownLength = options.countDownLength or 30000
@settings.debugging = options.debugging or false
@settings.notes = options.notes or ['a','b','c','d']
@settings.randomizeColor = if options.randomizeColor? then options.randomizeColor else true
@clientNotes = []
@settings.useCanvas = options.useCanvas or false
@settings.shouldPlayAudio = options.shouldPlayAudio or false
@settings.audioStartOffset = options.audioStartOffset or 0
@settings.audioFileName = options.audioFileName or ''
if @settings.shouldPlayAudio is true
@audio = new Audio(@settings.audioFileName)
@playingAudio = false
@testAudio()
# Kicks the tires on audio playback.
testAudio: ->
if typeof webkitAudioContext is 'undefined' then return
@audioContext = new webkitAudioContext()
@source = @audioContext.createBufferSource();
@processor = @audioContext.createJavaScriptNode(2048);
# When audio metadata becomes available, log end date to determine any possible delay in playback
audioAvailable = (event) => @processor.onaudioprocess = null
@source.connect(@processor)
@processor.connect(@audioContext.destination)
request = new XMLHttpRequest()
request.open('GET', @settings.audioFileName, true)
request.responseType = 'arraybuffer'
# Attempts to load file via ArrayBuffer from an AJAX request and autoplay.
request.onload = () =>
@source.buffer = @audioContext.createBuffer(request.response, false)
@source.looping = true
@processor.onaudioprocess = audioAvailable
@source.noteOn(0)
request.send()
# Prepares DOM based on default/client settings
initDocument: ->
if @settings.displayCountDown is true then $('<div class="count-down"/>').appendTo('body')
if @settings.debugging is true then $('<div id="debug"/>').appendTo('body')
if @settings.displayLogo is true
for note in @clientNotes
$(".#{note}").addClass("logo-#{note}")
# Based on user settings will gather the "notes" the client is responsible for playing
loadNotesFromDom: ->
addNote = (note, array) ->
if $.inArray(note, array) is -1 then array.push(note)
# If we've already got the DOM configured with colors, don't do anything...
if @settings.randomizeColor is false
# Find the notes that are defined in the markup to store in settings
for note in @settings.notes
if $('.main-screen').hasClass(note)
addNote(note, @clientNotes)
if @settings.debugging is false then $('.main-screen').text('')
else
# Add new note to the dom and store them in settings
that = @
$('.main-screen').removeClass(@settings.notes.join(' ')).each ->
i = Math.floor(Math.random() * that.settings.notes.length)
theNote = that.settings.notes[i]
$(this).addClass(theNote)
addNote(theNote, that.clientNotes)
if that.settings.debugging is true then $(this).text(theNote)
# Wrapper for console.log to guard against errors in browsers that don't support it
log: (message) ->
if typeof console isnt 'undefined' and console.log then console.log(message)
# After getting the current notes to watch, and the track from the server,
# filter out any ticks in the current track that the client doesn't need
# to care about.
filterNotes: ->
@currentTrack.ticks = $.grep @currentTrack.ticks, (element, index) =>
hasNotes = $.grep element.notes, (note, i) =>
result = $.inArray(note, @clientNotes)
result > -1
hasNotes.length > 0
if @settings.debugging is true
@log('Filtering out mismatched notes...')
@log(@currentTrack)
# Once notes have been filtered, set each tick's play time based on adjusted start time
convertToClientTime: ->
if @settings.debugging is true then @log("Current start time: #{@currentTrack.startTime}")
@currentTrack.startTime = @currentTrack.startTime + @deltaOffset
# Countdown starts 30 sec prior to start time
@currentTrack.countDownStartTime = @currentTrack.startTime - @settings.countDownLength
$.each @currentTrack.ticks, (index, value) =>
value.time += @currentTrack.startTime
if @settings.debugging is true
@log 'Converting relative timecodes to client time...'
@log(@currentTrack)
# Formats seconds passed in to a more human readable format: e.g. - 3:16
formatCountDownTime: (seconds) ->
minutes = Math.floor(seconds / 60) % 60
seconds = seconds % 60
if minutes > 0
if seconds.toString().length is 1 then seconds = "0#{seconds}"
return "#{minutes}:#{seconds}"
else return seconds
# Writes debugging timer info to the DOM
writeTimerInfo: (delta) ->
$ul = $('<ul/>')
$ul.append "<li>Client Time: #{@clientTime.getTime()}</li>"
$ul.append "<li>Server Time: #{@serverTime}</li>"
$ul.append "<li>Delta: #{delta}</li>"
$ul.append "<li>Min Delta: #{@deltaOffset}</li>"
$ul.prependTo '#debug'
# Initiate polling the server to get the difference between client and server time
start: (count) ->
if @debugging is true then $('<div id="debug"/>').appendTo 'body'
@deltaCount = count
@deltaTimer = setInterval(=>
@getDelta()
, 500)
# Pings the server to check the current time
getDelta: ->
$.ajax
url: '/CrowdSync.asmx/GetTime'
type: 'GET'
data: ''
contentType: 'application/json; charset=utf-8'
dataType: 'json'
success: (result) =>
@serverTime = result.d
@clientTime = new Date()
delta = @clientTime.getTime() - @serverTime
@deltaOffset = delta if delta < @deltaOffset
if @settings.debugging is true then @writeTimerInfo(delta)
# When we're done computing the time delta, load the next track...
if @settings.serverCheckCount++ >= @deltaCount
clearTimeout(@deltaTimer)
@loadNextTrack()
false
error: (result, status, error) =>
clearTimeout(@deltaTimer)
if @settings.debugging is true then @log(result.responseText)
false
# Loads the next track to play
loadNextTrack: ->
if @settings.debugging is true then @log('Loading next track...')
$.ajax
url: "/CrowdSync.asmx/GetNextStartByCampusID?campusID=#{@settings.campus}"
type: 'GET'
data: ''
contentType: 'application/json; charset=utf-8'
dataType: 'json'
success: (result) =>
startTime = result.d.startTime
endTime = startTime + @currentTrack.ticks[@currentTrack.ticks.length - 1].time + @deltaOffset
@currentTrack.startTime = startTime
@currentTrack.endTime = endTime
if @settings.debugging is true
serverTime = new Date(@currentTrack.startTime)
$('#debug').prepend "<h3>Server Start Time: #{serverTime.toTimeString()}.#{serverTime.getMilliseconds()}</h3>"
@filterNotes()
@convertToClientTime()
if @settings.debugging is true
adjustedTime = new Date(@currentTrack.startTime)
$('#debug').prepend "<h3>Adjusted Start Time: #{adjustedTime.toTimeString()}.#{adjustedTime.getMilliseconds()}</h3>"
$('#debug').prepend "Current Notes: #{@clientNotes.join(', ')}"
@countDownTimer = setInterval(=>
@countDown()
, @settings.cycleLength)
false
error: (result, status, error) =>
if @settings.debugging is true then @log(result.responseText)
false
# Determines if/when to show the countdown on the DOM and plays audio
countDown: ->
theTime = new Date()
# Has the count down started yet?
if @currentTrack.countDownStartTime <= theTime # and theTime < @currentTrack.startTime
# Counting Down...
remainingMilliseconds = @currentTrack.startTime - theTime.getTime()
# Is it time to play the audio track?
audioPlayTime = @currentTrack.startTime + @settings.audioStartOffset + @settings.cycleLength # - @audioDelay
if @settings.shouldPlayAudio is true and audioPlayTime <= theTime and @playingAudio is false
if @settings.debugging then @log 'Playing audio...'
@audio.play()
@playingAudio = true
if @settings.debugging then $('.main-screen').text(remainingMilliseconds)
if remainingMilliseconds <= 0
if @settings.displayLogo is true then $('.main-screen').removeClass("logo-#{@settings.notes.join(' logo-')}")
if @settings.displaySplash is true then $('.splash').removeClass('splash')
clearTimeout(@countDownTimer)
@play()
if @settings.displayCountDown is true
remainingSeconds = Math.ceil(remainingMilliseconds / 1000)
$('.count-down').text(@formatCountDownTime(remainingSeconds))
if remainingMilliseconds <= 0
$('.count-down').fadeOut 'slow', -> $(this).remove()
# Initiates visual element, whether displayed via DOM manipulation or Canvas
play: ->
if @settings.debugging is true then @log "Starting tick..."
func = if @settings.useCanvas is false then @paintDom else @paintCanvas
@cycleTimer = setInterval(=>
@tick(func)
, @settings.cycleLength)
# Determines the current position within the song and will start or stop visualization
tick: (callback) ->
theTime = new Date()
currentTick = @currentTrack.ticks[@playHeadIndex]
if currentTick? and theTime >= currentTick.time
callback.call(@, theTime, currentTick)
@playHeadIndex += 1
# Stop playing, the current song has ended...
else if theTime > @currentTrack.endTime
clearTimeout(@cycleTimer)
if @settings.useCanvas is true then @clearCanvas()
if @settings.debugging is true then @log('Song has ended...')
if @settings.shouldPlayAudio is true
if @settings.debugging is true then 'Stopping audio track...'
setTimeout(=>
@audio.pause()
@playingAudio = false
, 1000)
# Presentation has finished, fade out...
setTimeout(->
$('.overlay').fadeIn('slow')
, 3000)
# Load next track once the current one has completed...
#@loadNextTrack()
# Displays song data to the DOM via adding classes to '.main-screen' elements
paintDom: (theTime, theTick) ->
selector = ".#{theTick.notes.join(', .')}"
$(selector).removeClass('off')
setTimeout(->
$(selector).addClass('off')
, theTick.duration)
# Prepares canvas for visualization to be drawn
initCanvas: ->
@clientNotes = @settings.notes
if @settings.debugging then @log 'Initializing canvas...'
@canvasWidth = 1240 # 1280 document.width
@canvasHeight = 728 # 768 document.height
@canvas = document.getElementById('main-screen')
@canvas.width = @canvasWidth
@canvas.height = @canvasHeight
@context = @canvas.getContext('2d')
@lights = []
@plotTree()
# Plots points of light on Canvas x,y and assigns colors in Christmas tree visualization
plotTree: ->
# Plot Christmas Tree lights here...
if @settings.debugging then @log 'Plotting points...'
colSpacing = 17
rowSpacing = colSpacing
xOffset = Math.ceil(@canvasWidth / 2)
yOffset = Math.ceil(@canvasHeight * .05)
for i in [0..38]
if i is 38 then cols = 4
else if i is 37 then cols = 7
else if i > 0 then cols = Math.ceil(i / 4 + 2)
else cols = 1
yPos = (i * rowSpacing) + yOffset
colSpacing += .05
widthFactor = Math.sin((i+5) / 18) * 50
for j in [0..cols]
xPos = xOffset - (cols * widthFactor / 2) + (j * widthFactor)
index = Math.floor(Math.random() * @settings.notes.length)
noteName = @settings.notes[index]
xPos = @nudge(xPos)
yPos = @nudge(yPos)
@lights.push(
x: xPos
innerX: xPos
y: yPos
innerY: yPos
color: @canvasColors[noteName]
note: @settings.notes[index]
)
if @settings.debugging is true then @log @lights
# Paint lights ~100 frames per second
@canvasTimer = setInterval(=>
@paintLights()
, @settings.cycleLength)
# Clears canvas and kills timer that controls rendering tree to free up resources
clearCanvas: ->
clearTimeout(@canvasTimer)
@context.clearRect(0, 0, @canvasWidth, @canvasHeight)
# Randomizes light position based on it's initial position to make the tree appaer more organic
nudge: (n) ->
d = Math.floor(Math.random() * 10)
n + if Math.random() > .5 then -d else d
# Creates variance in position of blur effect on each 'light'
nudgeBlur: (n, center, radius) ->
d = if Math.random() * 100 > 30 then 1 else 0
d = if Math.random() > .5 then -d else d
n = n + d
if n >= center + radius - 3 then n = n - 1
else if n <= center - radius + 3 then n = n + 1
n
# Assigns alpha values of each 'light' on the canvas and sets up a timeout to fade out the lights
paintCanvas: (theTime, theTick) ->
for note in theTick.notes
if @settings.debugging is true then @log note
@canvasColors[note].a = 0.81
setTimeout(=>
@lightsOut(theTick)
, theTick.duration)
# Actually paints each light on the Canvas
paintLights: ->
# Draw lights onto canvas here...
@context.clearRect(0, 0, @canvasWidth, @canvasHeight)
radians = Math.PI * 2
radius = 13
for light in @lights
color = @canvasColors[light.note]
#@context.fillStyle = "rgba(#{color.r}, #{color.g}, #{color.b}, #{color.a})"
light.innerX = @nudgeBlur(light.innerX, light.x, radius)
light.innerY = @nudgeBlur(light.innerY, light.y, radius)
gradient = @context.createRadialGradient(light.innerX, light.innerY, 0, light.x, light.y, radius)
gradient.addColorStop(0.6, "rgba(#{color.r}, #{color.g}, #{color.b}, #{color.a})")
gradient.addColorStop(1, "rgba(#{color.r}, #{color.g}, #{color.b}, 0)")
@context.fillStyle = gradient
@context.beginPath()
@context.arc(light.x, light.y, radius, 0, radians, true)
@context.closePath()
@context.fill()
# Stores a reference to timer ID and initializes callback to 'dim' lights
lightsOut: (theTick) ->
if @settings.debugging is true then "Turning off '#{theTick.notes.join(', ')}'"
fadeTimer = setInterval(=>
@fadeLights(theTick)
, @settings.cycleLength)
theTick.fadeTimer = fadeTimer
# Fades out lights by decrementing the alpha value. Sets to 0 and kills fade timer when less than 5% opacity
fadeLights: (theTick) ->
for note in theTick.notes
@canvasColors[note].a -= .5
if @canvasColors[note].a <= 0.05
@canvasColors[note].a = 0
clearTimeout(theTick.fadeTimer)
# Object to represent color values for Christmas tree light visualization
canvasColors:
a: { r: 255, g: 4, b: 38, a: 0 }, # a - Red
b: { r: 0, g: 201, b: 235, a: 0 }, # b - Blue
c: { r: 46, g: 248, b: 25, a: 0 }, # c - Green
d: { r: 255, g: 224, b: 0, a: 0 } # d - Yellow
# Object composed of decoded MIDI representing time signature of the light display
currentTrack:
startTime: 123578916,
endTime: 12345667,
ticks: [
# 1
{ notes: ["a"], time: 19, duration: 900 },
{ notes: ["b"], time: 986, duration: 900 },
{ notes: ["c"], time: 1939, duration: 900 },
{ notes: ["d"], time: 2908, duration: 900 },
{ notes: ["a"], time: 3879, duration: 900 },
{ notes: ["b"], time: 4843, duration: 900 },
{ notes: ["c"], time: 5811, duration: 900 },
{ notes: ["d"], time: 6801, duration: 900 },
{ notes: ["a"], time: 7747, duration: 900 },
{ notes: ["b"], time: 8715, duration: 900 },
{ notes: ["c"], time: 9682, duration: 900 },
{ notes: ["d"], time: 10645, duration: 900 },
{ notes: ["a"], time: 11607, duration: 900 },
{ notes: ["b"], time: 12585, duration: 900 },
{ notes: ["c"], time: 13556, duration: 900 },
{ notes: ["d"], time: 14521, duration: 900 },
# 9
{ notes: ["a"], time: 15486, duration: 900 },
{ notes: ["b"], time: 16455, duration: 900 },
{ notes: ["c"], time: 17415, duration: 900 },
{ notes: ["d"], time: 18419, duration: 900 },
{ notes: ["a"], time: 19362, duration: 900 },
{ notes: ["b"], time: 20294, duration: 900 },
{ notes: ["c"], time: 21275, duration: 900 },
{ notes: ["d"], time: 22263, duration: 900 },
{ notes: ["c"], time: 23235, duration: 307 },
{ notes: ["a"], time: 23876, duration: 159 },
{ notes: ["c"], time: 24198, duration: 309 },
{ notes: ["a"], time: 24843, duration: 155 },
{ notes: ["c"], time: 25162, duration: 327 },
{ notes: ["a"], time: 25811, duration: 163 },
{ notes: ["c"], time: 26134, duration: 315 },
{ notes: ["a"], time: 26779, duration: 162 },
{ notes: ["c"], time: 27101, duration: 324 },
{ notes: ["a"], time: 27746, duration: 164 },
{ notes: ["c"], time: 28067, duration: 326 },
{ notes: ["a"], time: 28714, duration: 161 },
# 16
{ notes: ["c"], time: 29037, duration: 324 },
{ notes: ["a"], time: 29682, duration: 161 },
{ notes: ["c"], time: 30005, duration: 323 },
{ notes: ["a"], time: 30650, duration: 161 },
{ notes: ["d"], time: 30972, duration: 324 },
{ notes: ["b"], time: 31940, duration: 326 },
{ notes: ["c"], time: 32908, duration: 330 },
{ notes: ["a"], time: 33875, duration: 324 },
{ notes: ["a"], time: 36778, duration: 160 },
{ notes: ["b"], time: 37101, duration: 162 },
{ notes: ["c"], time: 37424, duration: 162 },
{ notes: ["d"], time: 37746, duration: 164 },
{ notes: ["a"], time: 38069, duration: 325 },
{ notes: ["b"], time: 38392, duration: 162 },
{ notes: ["a"], time: 39682, duration: 162 },
{ notes: ["b"], time: 40005, duration: 161 },
{ notes: ["c"], time: 40327, duration: 163 },
# 22
{ notes: ["a"], time: 41617, duration: 165 },
{ notes: ["b"], time: 41940, duration: 163 },
{ notes: ["c"], time: 42263, duration: 161 },
{ notes: ["d"], time: 46456, duration: 322 },
{ notes: ["c"], time: 46783, duration: 322 },
{ notes: ["b"], time: 47100, duration: 161 },
{ notes: ["a"], time: 47424, duration: 322 },
{ notes: ["d"], time: 47751, duration: 320 },
{ notes: ["c"], time: 48069, duration: 320 },
{ notes: ["d"], time: 48393, duration: 320 },
{ notes: ["c"], time: 48719, duration: 320 },
{ notes: ["b"], time: 49037, duration: 162 },
{ notes: ["a"], time: 49359, duration: 328 },
{ notes: ["d"], time: 49682, duration: 322 },
{ notes: ["c"], time: 50009, duration: 316 },
# 27
{ notes: ["d"], time: 54197, duration: 324 },
{ notes: ["c"], time: 54521, duration: 323 },
{ notes: ["b"], time: 54842, duration: 161 },
{ notes: ["a"], time: 55165, duration: 324 },
{ notes: ["d"], time: 55488, duration: 324 },
{ notes: ["c"], time: 55811, duration: 325 },
{ notes: ["d"], time: 56134, duration: 323 },
{ notes: ["c"], time: 56456, duration: 322 },
{ notes: ["b"], time: 56783, duration: 157 },
{ notes: ["a"], time: 57101, duration: 322 },
{ notes: ["d"], time: 57428, duration: 322 },
{ notes: ["c"], time: 57746, duration: 162 },
{ notes: ["b"], time: 58069, duration: 321 },
{ notes: ["d"], time: 58714, duration: 325 },
{ notes: ["b"], time: 59037, duration: 324 },
{ notes: ["d"], time: 59684, duration: 323 },
# 32
{ notes: ["b"], time: 60004, duration: 325 },
{ notes: ["d"], time: 60650, duration: 324 },
{ notes: ["b"], time: 60972, duration: 323 },
{ notes: ["d"], time: 61617, duration: 326 },
{ notes: ["b"], time: 61940, duration: 323 },
{ notes: ["d"], time: 62585, duration: 325 },
{ notes: ["b"], time: 62908, duration: 322 },
{ notes: ["d"], time: 63549, duration: 328 },
{ notes: ["b"], time: 63875, duration: 321 },
{ notes: ["d"], time: 64521, duration: 319 },
{ notes: ["b"], time: 64838, duration: 343 },
{ notes: ["d"], time: 65488, duration: 327 },
{ notes: ["b"], time: 65811, duration: 319 },
{ notes: ["d"], time: 66456, duration: 324 },
{ notes: ["b"], time: 66777, duration: 328 },
{ notes: ["d"], time: 67424, duration: 324 },
{ notes: ["b"], time: 67746, duration: 325 },
{ notes: ["d"], time: 68392, duration: 324 },
{ notes: ["b"], time: 68714, duration: 325 },
{ notes: ["d"], time: 69359, duration: 325 },
{ notes: ["b"], time: 69683, duration: 321 },
{ notes: ["d"], time: 70326, duration: 321 },
{ notes: ["b"], time: 70651, duration: 321 },
{ notes: ["d"], time: 71294, duration: 323 },
# 38
{ notes: ["b"], time: 71617, duration: 322 },
{ notes: ["d"], time: 72263, duration: 322 },
{ notes: ["b"], time: 72585, duration: 323 },
{ notes: ["d"], time: 73230, duration: 323 },
{ notes: ["b"], time: 73553, duration: 323 },
{ notes: ["d"], time: 74198, duration: 323 },
{ notes: ["b"], time: 74526, duration: 318 },
{ notes: ["d"], time: 75166, duration: 322 },
{ notes: ["b"], time: 75495, duration: 315 },
{ notes: ["d"], time: 76134, duration: 321 },
{ notes: ["b"], time: 76460, duration: 320 },
{ notes: ["a","c"], time: 77425, duration: 161 },
{ notes: ["a","c"], time: 78392, duration: 161 },
{ notes: ["a","c"], time: 79363, duration: 164 },
{ notes: ["a","c"], time: 80327, duration: 161 },
{ notes: ["a","c"], time: 81294, duration: 167 },
{ notes: ["a","c"], time: 82262, duration: 167 },
# 44
{ notes: ["a","c"], time: 83230, duration: 159 },
{ notes: ["b","d"], time: 84198, duration: 162 },
{ notes: ["a","c"], time: 85166, duration: 159 },
{ notes: ["a","c"], time: 86137, duration: 162 },
{ notes: ["a","c"], time: 87101, duration: 163 },
{ notes: ["a","c"], time: 88066, duration: 132 },
{ notes: ["a","c"], time: 89038, duration: 158 },
{ notes: ["a","c"], time: 90004, duration: 170 },
{ notes: ["a","c"], time: 90972, duration: 161 },
{ notes: ["b","d"], time: 91940, duration: 165 },
{ notes: ["a"], time: 92909, duration: 1937 },
{ notes: ["b"], time: 94843, duration: 1936 },
{ notes: ["c"], time: 96779, duration: 1937 },
# 52
{ notes: ["d"], time: 98714, duration: 1940 },
{ notes: ["a"], time: 100650, duration: 1938 },
{ notes: ["b"], time: 102585, duration: 900 },
{ notes: ["c"], time: 103553, duration: 900 },
{ notes: ["d"], time: 104521, duration: 163 },
{ notes: ["c"], time: 105487, duration: 157 },
{ notes: ["b"], time: 106456, duration: 163 },
{ notes: ["a"], time: 107425, duration: 156 },
{ notes: ["d"], time: 108391, duration: 162 },
{ notes: ["c"], time: 109359, duration: 159 },
{ notes: ["b"], time: 110326, duration: 164 },
{ notes: ["a"], time: 111295, duration: 160 },
# pg 2, 59
{ notes: ["a","c"], time: 112264, duration: 166 },
{ notes: ["a","c"], time: 113230, duration: 159 },
{ notes: ["a","c"], time: 114198, duration: 167 },
{ notes: ["a","c"], time: 115164, duration: 134 },
{ notes: ["a","c"], time: 116133, duration: 161 },
{ notes: ["a","c"], time: 117101, duration: 163 },
{ notes: ["a","c"], time: 118069, duration: 160 },
{ notes: ["b","d"], time: 119037, duration: 160 },
{ notes: ["a","c"], time: 120004, duration: 164 },
{ notes: ["a","c"], time: 120972, duration: 164 },
{ notes: ["a","c"], time: 121940, duration: 163 },
{ notes: ["a","c"], time: 122907, duration: 162 },
{ notes: ["a","c"], time: 123874, duration: 164 },
{ notes: ["a","c"], time: 124843, duration: 161 },
# 66
{ notes: ["a","c"], time: 125811, duration: 164 },
{ notes: ["b","d"], time: 126780, duration: 160 },
{ notes: ["a"], time: 127746, duration: 1939 },
{ notes: ["b"], time: 129682, duration: 1938 },
{ notes: ["c"], time: 131617, duration: 1934 },
{ notes: ["d"], time: 133556, duration: 1934 },
{ notes: ["a"], time: 135488, duration: 1936 },
{ notes: ["b"], time: 137424, duration: 900 },
{ notes: ["c"], time: 138391, duration: 900 },
{ notes: ["d"], time: 139359, duration: 1937 },
{ notes: ["a"], time: 141294, duration: 1937 },
{ notes: ["b"], time: 143230, duration: 1937 },
# 76
{ notes: ["c"], time: 145327, duration: 1775 },
{ notes: ["a"], time: 166461, duration: 900 },
{ notes: ["b"], time: 167426, duration: 900 },
{ notes: ["c"], time: 168386, duration: 900 },
{ notes: ["d"], time: 169359, duration: 900 },
{ notes: ["a"], time: 170328, duration: 900 },
{ notes: ["b"], time: 171295, duration: 900 },
{ notes: ["c"], time: 172265, duration: 900 },
{ notes: ["d"], time: 173227, duration: 900 },
{ notes: ["a"], time: 174198, duration: 900 },
{ notes: ["b"], time: 175165, duration: 900 },
{ notes: ["c"], time: 176126, duration: 900 },
{ notes: ["d"], time: 177104, duration: 900 },
# 93
{ notes: ["a"], time: 178068, duration: 900 },
{ notes: ["b"], time: 179036, duration: 900 },
{ notes: ["c"], time: 180008, duration: 900 },
{ notes: ["d"], time: 180972, duration: 900 },
{ notes: ["a"], time: 181936, duration: 164 },
{ notes: ["b"], time: 182907, duration: 159 },
{ notes: ["c"], time: 183875, duration: 159 },
{ notes: ["d"], time: 184843, duration: 162 },
{ notes: ["d"], time: 185488, duration: 163 },
{ notes: ["a"], time: 187746, duration: 163 },
{ notes: ["b"], time: 188069, duration: 160 },
{ notes: ["c"], time: 189036, duration: 200 },
{ notes: ["d"], time: 189359, duration: 161 },
{ notes: ["d"], time: 190649, duration: 326 },
{ notes: ["a"], time: 191295, duration: 163 },
# 100
{ notes: ["b"], time: 192587, duration: 330 },
{ notes: ["d"], time: 193230, duration: 164 },
{ notes: ["b"], time: 193552, duration: 320 },
{ notes: ["d"], time: 194197, duration: 164 },
{ notes: ["b"], time: 194520, duration: 324 },
{ notes: ["d"], time: 195165, duration: 162 },
{ notes: ["b"], time: 195488, duration: 325 },
{ notes: ["d"], time: 196133, duration: 162 },
{ notes: ["b"], time: 196456, duration: 322 },
{ notes: ["d"], time: 197101, duration: 159 },
{ notes: ["a"], time: 197424, duration: 161 },
{ notes: ["b"], time: 197746, duration: 150 },
{ notes: ["a"], time: 197907, duration: 160 },
{ notes: ["c"], time: 198071, duration: 160 },
{ notes: ["d"], time: 198230, duration: 163 },
{ notes: ["a"], time: 198391, duration: 162 },
{ notes: ["b"], time: 198714, duration: 150 },
{ notes: ["a"], time: 198875, duration: 161 },
{ notes: ["c"], time: 199036, duration: 162 },
{ notes: ["d"], time: 199198, duration: 161 },
{ notes: ["a"], time: 199359, duration: 162 },
{ notes: ["b"], time: 199682, duration: 150 },
{ notes: ["a"], time: 199843, duration: 163 },
{ notes: ["c"], time: 200004, duration: 161 },
{ notes: ["d"], time: 200170, duration: 157 },
{ notes: ["c"], time: 200327, duration: 160 },
{ notes: ["b"], time: 200649, duration: 107 },
{ notes: ["a"], time: 200811, duration: 150 },
{ notes: ["c"], time: 200972, duration: 150 },
# 106
{ notes: ["a"], time: 203231, duration: 162 },
{ notes: ["b"], time: 203398, duration: 153 },
{ notes: ["c"], time: 203555, duration: 162 },
{ notes: ["d"], time: 203714, duration: 161 },
{ notes: ["a"], time: 203883, duration: 153 },
{ notes: ["b"], time: 204036, duration: 163 },
{ notes: ["c"], time: 204198, duration: 159 },
{ notes: ["d"], time: 204360, duration: 162 },
{ notes: ["a"], time: 204520, duration: 320 },
{ notes: ["c"], time: 204846, duration: 155 },
{ notes: ["a"], time: 206133, duration: 163 },
{ notes: ["b"], time: 206294, duration: 164 },
{ notes: ["c"], time: 206456, duration: 165 },
{ notes: ["d"], time: 206617, duration: 163 },
{ notes: ["a"], time: 206778, duration: 164 },
{ notes: ["c"], time: 206940, duration: 163 },
{ notes: ["a"], time: 208069, duration: 167 },
{ notes: ["b"], time: 208230, duration: 159 },
{ notes: ["c"], time: 208395, duration: 158 },
{ notes: ["d"], time: 208558, duration: 159 },
{ notes: ["a"], time: 208715, duration: 162 },
{ notes: ["c"], time: 208875, duration: 150 },
{ notes: ["b"], time: 209036, duration: 326 },
{ notes: ["d"], time: 209682, duration: 163 },
{ notes: ["b"], time: 210003, duration: 323 },
{ notes: ["d"], time: 210649, duration: 161 },
{ notes: ["b"], time: 210971, duration: 327 },
{ notes: ["d"], time: 211616, duration: 163 },
{ notes: ["b"], time: 211940, duration: 322 },
{ notes: ["d"], time: 212585, duration: 162 },
# 111
{ notes: ["b"], time: 212907, duration: 323 },
{ notes: ["d"], time: 213553, duration: 159 },
{ notes: ["b"], time: 213875, duration: 323 },
{ notes: ["d"], time: 214520, duration: 162 },
{ notes: ["b"], time: 214844, duration: 321 },
{ notes: ["d"], time: 215488, duration: 161 },
{ notes: ["b"], time: 215811, duration: 324 },
{ notes: ["d"], time: 216456, duration: 161 },
{ notes: ["b"], time: 216778, duration: 324 },
{ notes: ["d"], time: 217424, duration: 150 },
{ notes: ["b"], time: 217746, duration: 323 },
{ notes: ["d"], time: 218391, duration: 160 },
{ notes: ["b"], time: 218714, duration: 323 },
{ notes: ["d"], time: 219359, duration: 161 },
{ notes: ["b"], time: 219683, duration: 320 },
{ notes: ["d"], time: 220327, duration: 150 },
{ notes: ["b"], time: 220649, duration: 324 },
{ notes: ["d"], time: 221294, duration: 161 },
{ notes: ["b"], time: 221617, duration: 323 },
{ notes: ["d"], time: 222262, duration: 161 },
{ notes: ["b"], time: 222584, duration: 325 },
{ notes: ["d"], time: 223230, duration: 160 },
{ notes: ["b"], time: 223553, duration: 323 },
{ notes: ["d"], time: 224198, duration: 161 },
# 117
{ notes: ["a","c"], time: 224520, duration: 162 },
{ notes: ["b","d"], time: 225488, duration: 162 },
{ notes: ["a","c"], time: 226456, duration: 163 },
{ notes: ["b","d"], time: 227423, duration: 161 },
{ notes: ["a","b","c","d"], time: 228390, duration: 3551 },
{ notes: ["a","b","c","d"], time: 232262, duration: 162 }
] |
[
{
"context": "\n beforeEach ->\n options =\n value : 'Fatih Acet'\n name : 'name'\n checked : yes\n\n ",
"end": 254,
"score": 0.998893141746521,
"start": 244,
"tag": "NAME",
"value": "Fatih Acet"
},
{
"context": " =\n value : 'Fatih Acet'\n n... | src/tests/components/inputs/test_checkbox.coffee | dashersw/spark | 1 | goog = goog or goog = require: ->
goog.require 'spark.components.Checkbox'
goog.require 'spark.components.Field'
describe 'spark.components.Checkbox', ->
checkbox = null
options = null
beforeEach ->
options =
value : 'Fatih Acet'
name : 'name'
checked : yes
checkbox = new spark.components.Checkbox options
it 'should extends spark.components.Field', ->
expect(checkbox instanceof spark.components.Field).toBeTruthy()
it 'should be checked if checked option passed truthy in options', ->
expect(checkbox.isChecked()).toBeTruthy()
expect(checkbox.getElement().checked).toBeTruthy()
it 'should be type checkbox', ->
expect(checkbox.getAttribute('type')).toBe 'checkbox'
it 'should check/uncheck the element and return actual state', ->
cb = new spark.components.Checkbox
expect(cb.isChecked()).toBeFalsy()
cb.check()
expect(cb.isChecked()).toBeTruthy()
cb.uncheck()
expect(cb.isChecked()).toBeFalsy()
it 'should emit StateChanged event with proper state', ->
state = null
checkbox.on 'StateChanged', (e) ->
state = e.data
checkbox.check()
expect(state).toBeTruthy()
checkbox.check() # try to check again to test state change
expect(state).toBeTruthy()
checkbox.uncheck()
expect(state).toBeFalsy()
it 'should return value as boolean', ->
expect(checkbox.getValue()).toBeTruthy()
checkbox.uncheck()
expect(checkbox.getValue()).toBeFalsy()
| 147622 | goog = goog or goog = require: ->
goog.require 'spark.components.Checkbox'
goog.require 'spark.components.Field'
describe 'spark.components.Checkbox', ->
checkbox = null
options = null
beforeEach ->
options =
value : '<NAME>'
name : '<NAME>'
checked : yes
checkbox = new spark.components.Checkbox options
it 'should extends spark.components.Field', ->
expect(checkbox instanceof spark.components.Field).toBeTruthy()
it 'should be checked if checked option passed truthy in options', ->
expect(checkbox.isChecked()).toBeTruthy()
expect(checkbox.getElement().checked).toBeTruthy()
it 'should be type checkbox', ->
expect(checkbox.getAttribute('type')).toBe 'checkbox'
it 'should check/uncheck the element and return actual state', ->
cb = new spark.components.Checkbox
expect(cb.isChecked()).toBeFalsy()
cb.check()
expect(cb.isChecked()).toBeTruthy()
cb.uncheck()
expect(cb.isChecked()).toBeFalsy()
it 'should emit StateChanged event with proper state', ->
state = null
checkbox.on 'StateChanged', (e) ->
state = e.data
checkbox.check()
expect(state).toBeTruthy()
checkbox.check() # try to check again to test state change
expect(state).toBeTruthy()
checkbox.uncheck()
expect(state).toBeFalsy()
it 'should return value as boolean', ->
expect(checkbox.getValue()).toBeTruthy()
checkbox.uncheck()
expect(checkbox.getValue()).toBeFalsy()
| true | goog = goog or goog = require: ->
goog.require 'spark.components.Checkbox'
goog.require 'spark.components.Field'
describe 'spark.components.Checkbox', ->
checkbox = null
options = null
beforeEach ->
options =
value : 'PI:NAME:<NAME>END_PI'
name : 'PI:NAME:<NAME>END_PI'
checked : yes
checkbox = new spark.components.Checkbox options
it 'should extends spark.components.Field', ->
expect(checkbox instanceof spark.components.Field).toBeTruthy()
it 'should be checked if checked option passed truthy in options', ->
expect(checkbox.isChecked()).toBeTruthy()
expect(checkbox.getElement().checked).toBeTruthy()
it 'should be type checkbox', ->
expect(checkbox.getAttribute('type')).toBe 'checkbox'
it 'should check/uncheck the element and return actual state', ->
cb = new spark.components.Checkbox
expect(cb.isChecked()).toBeFalsy()
cb.check()
expect(cb.isChecked()).toBeTruthy()
cb.uncheck()
expect(cb.isChecked()).toBeFalsy()
it 'should emit StateChanged event with proper state', ->
state = null
checkbox.on 'StateChanged', (e) ->
state = e.data
checkbox.check()
expect(state).toBeTruthy()
checkbox.check() # try to check again to test state change
expect(state).toBeTruthy()
checkbox.uncheck()
expect(state).toBeFalsy()
it 'should return value as boolean', ->
expect(checkbox.getValue()).toBeTruthy()
checkbox.uncheck()
expect(checkbox.getValue()).toBeFalsy()
|
[
{
"context": "', { method: 'addIncomingIntegration' }\n\n\t\ttoken = Random.id(48)\n\n\t\tintegration.type = 'webhook-incoming'\n\t\tinteg",
"end": 2539,
"score": 0.8902661800384521,
"start": 2527,
"tag": "KEY",
"value": "Random.id(48"
}
] | packages/rocketchat-integrations/server/methods/incoming/addIncomingIntegration.coffee | org100h1/Rocket.Panda | 0 | Meteor.methods
addIncomingIntegration: (integration) ->
if (not RocketChat.authz.hasPermission @userId, 'manage-integrations') and (not RocketChat.authz.hasPermission @userId, 'manage-own-integrations')
throw new Meteor.Error 'not_authorized'
if not _.isString(integration.channel)
throw new Meteor.Error 'error-invalid-channel', 'Invalid channel', { method: 'addIncomingIntegration' }
if integration.channel.trim() is ''
throw new Meteor.Error 'error-invalid-channel', 'Invalid channel', { method: 'addIncomingIntegration' }
if integration.channel[0] not in ['@', '#']
throw new Meteor.Error 'error-invalid-channel-start-with-chars', 'Invalid channel. Start with @ or #', { method: 'addIncomingIntegration' }
if not _.isString(integration.username)
throw new Meteor.Error 'error-invalid-username', 'Invalid username', { method: 'addIncomingIntegration' }
if integration.username.trim() is ''
throw new Meteor.Error 'error-invalid-username', 'Invalid username', { method: 'addIncomingIntegration' }
if integration.scriptEnabled is true and integration.script? and integration.script.trim() isnt ''
try
babelOptions = Babel.getDefaultOptions()
babelOptions.externalHelpers = false
integration.scriptCompiled = Babel.compile(integration.script, babelOptions).code
integration.scriptError = undefined
catch e
integration.scriptCompiled = undefined
integration.scriptError = _.pick e, 'name', 'message', 'pos', 'loc', 'codeFrame'
record = undefined
channelType = integration.channel[0]
channel = integration.channel.substr(1)
switch channelType
when '#'
record = RocketChat.models.Rooms.findOne
$or: [
{_id: channel}
{name: channel}
]
when '@'
record = RocketChat.models.Users.findOne
$or: [
{_id: channel}
{username: channel}
]
if record is undefined
throw new Meteor.Error 'error-invalid-room', 'Invalid room', { method: 'addIncomingIntegration' }
if record.usernames? and
(not RocketChat.authz.hasPermission @userId, 'manage-integrations') and
(RocketChat.authz.hasPermission @userId, 'manage-own-integrations') and
Meteor.user()?.username not in record.usernames
throw new Meteor.Error 'error-invalid-channel', 'Invalid Channel', { method: 'addIncomingIntegration' }
user = RocketChat.models.Users.findOne({username: integration.username})
if not user?
throw new Meteor.Error 'error-invalid-user', 'Invalid user', { method: 'addIncomingIntegration' }
token = Random.id(48)
integration.type = 'webhook-incoming'
integration.token = token
integration.userId = user._id
integration._createdAt = new Date
integration._createdBy = RocketChat.models.Users.findOne @userId, {fields: {username: 1}}
RocketChat.models.Roles.addUserRoles user._id, 'bot'
integration._id = RocketChat.models.Integrations.insert integration
return integration
| 192489 | Meteor.methods
addIncomingIntegration: (integration) ->
if (not RocketChat.authz.hasPermission @userId, 'manage-integrations') and (not RocketChat.authz.hasPermission @userId, 'manage-own-integrations')
throw new Meteor.Error 'not_authorized'
if not _.isString(integration.channel)
throw new Meteor.Error 'error-invalid-channel', 'Invalid channel', { method: 'addIncomingIntegration' }
if integration.channel.trim() is ''
throw new Meteor.Error 'error-invalid-channel', 'Invalid channel', { method: 'addIncomingIntegration' }
if integration.channel[0] not in ['@', '#']
throw new Meteor.Error 'error-invalid-channel-start-with-chars', 'Invalid channel. Start with @ or #', { method: 'addIncomingIntegration' }
if not _.isString(integration.username)
throw new Meteor.Error 'error-invalid-username', 'Invalid username', { method: 'addIncomingIntegration' }
if integration.username.trim() is ''
throw new Meteor.Error 'error-invalid-username', 'Invalid username', { method: 'addIncomingIntegration' }
if integration.scriptEnabled is true and integration.script? and integration.script.trim() isnt ''
try
babelOptions = Babel.getDefaultOptions()
babelOptions.externalHelpers = false
integration.scriptCompiled = Babel.compile(integration.script, babelOptions).code
integration.scriptError = undefined
catch e
integration.scriptCompiled = undefined
integration.scriptError = _.pick e, 'name', 'message', 'pos', 'loc', 'codeFrame'
record = undefined
channelType = integration.channel[0]
channel = integration.channel.substr(1)
switch channelType
when '#'
record = RocketChat.models.Rooms.findOne
$or: [
{_id: channel}
{name: channel}
]
when '@'
record = RocketChat.models.Users.findOne
$or: [
{_id: channel}
{username: channel}
]
if record is undefined
throw new Meteor.Error 'error-invalid-room', 'Invalid room', { method: 'addIncomingIntegration' }
if record.usernames? and
(not RocketChat.authz.hasPermission @userId, 'manage-integrations') and
(RocketChat.authz.hasPermission @userId, 'manage-own-integrations') and
Meteor.user()?.username not in record.usernames
throw new Meteor.Error 'error-invalid-channel', 'Invalid Channel', { method: 'addIncomingIntegration' }
user = RocketChat.models.Users.findOne({username: integration.username})
if not user?
throw new Meteor.Error 'error-invalid-user', 'Invalid user', { method: 'addIncomingIntegration' }
token = <KEY>)
integration.type = 'webhook-incoming'
integration.token = token
integration.userId = user._id
integration._createdAt = new Date
integration._createdBy = RocketChat.models.Users.findOne @userId, {fields: {username: 1}}
RocketChat.models.Roles.addUserRoles user._id, 'bot'
integration._id = RocketChat.models.Integrations.insert integration
return integration
| true | Meteor.methods
addIncomingIntegration: (integration) ->
if (not RocketChat.authz.hasPermission @userId, 'manage-integrations') and (not RocketChat.authz.hasPermission @userId, 'manage-own-integrations')
throw new Meteor.Error 'not_authorized'
if not _.isString(integration.channel)
throw new Meteor.Error 'error-invalid-channel', 'Invalid channel', { method: 'addIncomingIntegration' }
if integration.channel.trim() is ''
throw new Meteor.Error 'error-invalid-channel', 'Invalid channel', { method: 'addIncomingIntegration' }
if integration.channel[0] not in ['@', '#']
throw new Meteor.Error 'error-invalid-channel-start-with-chars', 'Invalid channel. Start with @ or #', { method: 'addIncomingIntegration' }
if not _.isString(integration.username)
throw new Meteor.Error 'error-invalid-username', 'Invalid username', { method: 'addIncomingIntegration' }
if integration.username.trim() is ''
throw new Meteor.Error 'error-invalid-username', 'Invalid username', { method: 'addIncomingIntegration' }
if integration.scriptEnabled is true and integration.script? and integration.script.trim() isnt ''
try
babelOptions = Babel.getDefaultOptions()
babelOptions.externalHelpers = false
integration.scriptCompiled = Babel.compile(integration.script, babelOptions).code
integration.scriptError = undefined
catch e
integration.scriptCompiled = undefined
integration.scriptError = _.pick e, 'name', 'message', 'pos', 'loc', 'codeFrame'
record = undefined
channelType = integration.channel[0]
channel = integration.channel.substr(1)
switch channelType
when '#'
record = RocketChat.models.Rooms.findOne
$or: [
{_id: channel}
{name: channel}
]
when '@'
record = RocketChat.models.Users.findOne
$or: [
{_id: channel}
{username: channel}
]
if record is undefined
throw new Meteor.Error 'error-invalid-room', 'Invalid room', { method: 'addIncomingIntegration' }
if record.usernames? and
(not RocketChat.authz.hasPermission @userId, 'manage-integrations') and
(RocketChat.authz.hasPermission @userId, 'manage-own-integrations') and
Meteor.user()?.username not in record.usernames
throw new Meteor.Error 'error-invalid-channel', 'Invalid Channel', { method: 'addIncomingIntegration' }
user = RocketChat.models.Users.findOne({username: integration.username})
if not user?
throw new Meteor.Error 'error-invalid-user', 'Invalid user', { method: 'addIncomingIntegration' }
token = PI:KEY:<KEY>END_PI)
integration.type = 'webhook-incoming'
integration.token = token
integration.userId = user._id
integration._createdAt = new Date
integration._createdBy = RocketChat.models.Users.findOne @userId, {fields: {username: 1}}
RocketChat.models.Roles.addUserRoles user._id, 'bot'
integration._id = RocketChat.models.Integrations.insert integration
return integration
|
[
{
"context": "s\" : {\n \"def\" : [ {\n \"name\" : \"Patient\",\n \"context\" : \"Patient\",\n ",
"end": 3051,
"score": 0.7815399765968323,
"start": 3044,
"tag": "NAME",
"value": "Patient"
},
{
"context": "rary\" : {\n \"identifier\" : {\... | Src/coffeescript/cql-execution/test/elm/query/data.coffee | esteban-aliverti/clinical_quality_language | 0 | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.coffee to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### DateRangeOptimizedQuery
library TestSnippet version '1'
using QUICK
parameter MeasurementPeriod default interval[DateTime(2013, 1, 1), DateTime(2014, 1, 1))
valueset "Ambulatory/ED Visit" = '2.16.840.1.113883.3.464.1003.101.12.1061'
context Patient
define EncountersDuringMP = [Encounter] E where E.period during MeasurementPeriod
define AmbulatoryEncountersDuringMP = [Encounter: "Ambulatory/ED Visit"] E where E.period during MeasurementPeriod
define AmbulatoryEncountersIncludedInMP = [Encounter: "Ambulatory/ED Visit"] E where E.period included in MeasurementPeriod
###
module.exports['DateRangeOptimizedQuery'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "MeasurementPeriod",
"default" : {
"lowClosed" : true,
"highClosed" : false,
"type" : "Interval",
"low" : {
"name" : "DateTime",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "2013",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
} ]
},
"high" : {
"name" : "DateTime",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "2014",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
} ]
}
}
} ]
},
"valueSets" : {
"def" : [ {
"name" : "Ambulatory/ED Visit",
"id" : "2.16.840.1.113883.3.464.1003.101.12.1061"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "EncountersDuringMP",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"dateProperty" : "period",
"type" : "Retrieve",
"dateRange" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
}
} ],
"relationship" : [ ]
}
}, {
"name" : "AmbulatoryEncountersDuringMP",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"codeProperty" : "type",
"dateProperty" : "period",
"type" : "Retrieve",
"codes" : {
"name" : "Ambulatory/ED Visit",
"type" : "ValueSetRef"
},
"dateRange" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
}
} ],
"relationship" : [ ]
}
}, {
"name" : "AmbulatoryEncountersIncludedInMP",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"codeProperty" : "type",
"dateProperty" : "period",
"type" : "Retrieve",
"codes" : {
"name" : "Ambulatory/ED Visit",
"type" : "ValueSetRef"
},
"dateRange" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
}
} ],
"relationship" : [ ]
}
} ]
}
}
}
### IncludesQuery
library TestSnippet version '1'
using QUICK
parameter MeasurementPeriod default interval[DateTime(2013, 1, 1), DateTime(2014, 1, 1))
valueset "Ambulatory/ED Visit" = '2.16.840.1.113883.3.464.1003.101.12.1061'
context Patient
define MPIncludedAmbulatoryEncounters = [Encounter: "Ambulatory/ED Visit"] E where MeasurementPeriod includes E.period
###
module.exports['IncludesQuery'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "MeasurementPeriod",
"default" : {
"lowClosed" : true,
"highClosed" : false,
"type" : "Interval",
"low" : {
"name" : "DateTime",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "2013",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
} ]
},
"high" : {
"name" : "DateTime",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "2014",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
} ]
}
}
} ]
},
"valueSets" : {
"def" : [ {
"name" : "Ambulatory/ED Visit",
"id" : "2.16.840.1.113883.3.464.1003.101.12.1061"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "MPIncludedAmbulatoryEncounters",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"codeProperty" : "type",
"type" : "Retrieve",
"codes" : {
"name" : "Ambulatory/ED Visit",
"type" : "ValueSetRef"
}
}
} ],
"relationship" : [ ],
"where" : {
"type" : "Includes",
"operand" : [ {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}, {
"path" : "period",
"scope" : "E",
"type" : "Property"
} ]
}
}
} ]
}
}
}
### MultiSourceQuery
library TestSnippet version '1'
using QUICK
parameter MeasurementPeriod default interval[DateTime(2013, 1, 1), DateTime(2014, 1, 1))
context Patient
define msQueryWhere = foreach [Encounter] E,
[Condition] C
where E.period included in MeasurementPeriod
define msQueryWhere2 = foreach [Encounter] E, [Condition] C
where E.period included in MeasurementPeriod and C.id = 'http://cqframework.org/3/2'
define msQuery = foreach [Encounter] E, [Condition] C return {E: E, C:C}
###
module.exports['MultiSourceQuery'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "MeasurementPeriod",
"default" : {
"lowClosed" : true,
"highClosed" : false,
"type" : "Interval",
"low" : {
"name" : "DateTime",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "2013",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
} ]
},
"high" : {
"name" : "DateTime",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "2014",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
} ]
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "msQueryWhere",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"dateProperty" : "period",
"type" : "Retrieve",
"dateRange" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
}
}, {
"alias" : "C",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Condition",
"templateId" : "cqf-condition",
"type" : "Retrieve"
}
} ],
"relationship" : [ ],
"return" : {
"distinct" : true,
"expression" : {
"type" : "Tuple",
"element" : [ {
"name" : "E",
"value" : {
"name" : "E",
"type" : "AliasRef"
}
}, {
"name" : "C",
"value" : {
"name" : "C",
"type" : "AliasRef"
}
} ]
}
}
}
}, {
"name" : "msQueryWhere2",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"dateProperty" : "period",
"type" : "Retrieve",
"dateRange" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
}
}, {
"alias" : "C",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Condition",
"templateId" : "cqf-condition",
"type" : "Retrieve"
}
} ],
"relationship" : [ ],
"where" : {
"type" : "Equal",
"operand" : [ {
"path" : "id",
"scope" : "C",
"type" : "Property"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "http://cqframework.org/3/2",
"type" : "Literal"
} ]
},
"return" : {
"distinct" : true,
"expression" : {
"type" : "Tuple",
"element" : [ {
"name" : "E",
"value" : {
"name" : "E",
"type" : "AliasRef"
}
}, {
"name" : "C",
"value" : {
"name" : "C",
"type" : "AliasRef"
}
} ]
}
}
}
}, {
"name" : "msQuery",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
}, {
"alias" : "C",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Condition",
"templateId" : "cqf-condition",
"type" : "Retrieve"
}
} ],
"relationship" : [ ],
"return" : {
"expression" : {
"type" : "Tuple",
"element" : [ {
"name" : "E",
"value" : {
"name" : "E",
"type" : "AliasRef"
}
}, {
"name" : "C",
"value" : {
"name" : "C",
"type" : "AliasRef"
}
} ]
}
}
}
} ]
}
}
}
### QueryRelationship
library TestSnippet version '1'
using QUICK
context Patient
define withQuery = [Encounter] E
with [Condition] C such that C.id= 'http://cqframework.org/3/2'
define withQuery2 = [Encounter] E
with [Condition] C such that C.id = 'http://cqframework.org/3'
define withOutQuery = [Encounter] E
without [Condition] C such that C.id = 'http://cqframework.org/3/'
define withOutQuery2 = [Encounter] E
without [Condition] C such that C.id = 'http://cqframework.org/3/2'
###
module.exports['QueryRelationship'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "withQuery",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
} ],
"relationship" : [ {
"alias" : "C",
"type" : "With",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Condition",
"templateId" : "cqf-condition",
"type" : "Retrieve"
},
"suchThat" : {
"type" : "Equal",
"operand" : [ {
"path" : "id",
"scope" : "C",
"type" : "Property"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "http://cqframework.org/3/2",
"type" : "Literal"
} ]
}
} ]
}
}, {
"name" : "withQuery2",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
} ],
"relationship" : [ {
"alias" : "C",
"type" : "With",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Condition",
"templateId" : "cqf-condition",
"type" : "Retrieve"
},
"suchThat" : {
"type" : "Equal",
"operand" : [ {
"path" : "id",
"scope" : "C",
"type" : "Property"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "http://cqframework.org/3",
"type" : "Literal"
} ]
}
} ]
}
}, {
"name" : "withOutQuery",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
} ],
"relationship" : [ {
"alias" : "C",
"type" : "Without",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Condition",
"templateId" : "cqf-condition",
"type" : "Retrieve"
},
"suchThat" : {
"type" : "Equal",
"operand" : [ {
"path" : "id",
"scope" : "C",
"type" : "Property"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "http://cqframework.org/3/",
"type" : "Literal"
} ]
}
} ]
}
}, {
"name" : "withOutQuery2",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
} ],
"relationship" : [ {
"alias" : "C",
"type" : "Without",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Condition",
"templateId" : "cqf-condition",
"type" : "Retrieve"
},
"suchThat" : {
"type" : "Equal",
"operand" : [ {
"path" : "id",
"scope" : "C",
"type" : "Property"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "http://cqframework.org/3/2",
"type" : "Literal"
} ]
}
} ]
}
} ]
}
}
}
### QueryDefine
library TestSnippet version '1'
using QUICK
context Patient
define query = [Encounter] E
define a = E
return {E: E, a:a}
###
module.exports['QueryDefine'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "query",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
} ],
"define" : [ {
"identifier" : "a",
"expression" : {
"name" : "E",
"type" : "AliasRef"
}
} ],
"relationship" : [ ],
"return" : {
"expression" : {
"type" : "Tuple",
"element" : [ {
"name" : "E",
"value" : {
"name" : "E",
"type" : "AliasRef"
}
}, {
"name" : "a",
"value" : {
"name" : "a",
"type" : "QueryDefineRef"
}
} ]
}
}
}
} ]
}
}
}
### Tuple
library TestSnippet version '1'
using QUICK
context Patient
define query = [Encounter] E return {id: E.id, thing: E.status}
###
module.exports['Tuple'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "query",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
} ],
"relationship" : [ ],
"return" : {
"expression" : {
"type" : "Tuple",
"element" : [ {
"name" : "id",
"value" : {
"path" : "id",
"scope" : "E",
"type" : "Property"
}
}, {
"name" : "thing",
"value" : {
"path" : "status",
"scope" : "E",
"type" : "Property"
}
} ]
}
}
}
} ]
}
}
}
### Sorting
library TestSnippet version '1'
using QUICK
context Patient
define singleAsc = [Encounter] E return {E : E} sort by E.id
define singleDesc = [Encounter] E return {E : E} sort by E.id desc
###
module.exports['Sorting'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "singleAsc",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
} ],
"relationship" : [ ],
"return" : {
"expression" : {
"type" : "Tuple",
"element" : [ {
"name" : "E",
"value" : {
"name" : "E",
"type" : "AliasRef"
}
} ]
}
},
"sort" : {
"by" : [ {
"direction" : "asc",
"type" : "ByExpression",
"expression" : {
"path" : "id",
"scope" : "E",
"type" : "Property"
}
} ]
}
}
}, {
"name" : "singleDesc",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
} ],
"relationship" : [ ],
"return" : {
"expression" : {
"type" : "Tuple",
"element" : [ {
"name" : "E",
"value" : {
"name" : "E",
"type" : "AliasRef"
}
} ]
}
},
"sort" : {
"by" : [ {
"direction" : "desc",
"type" : "ByExpression",
"expression" : {
"path" : "id",
"scope" : "E",
"type" : "Property"
}
} ]
}
}
} ]
}
}
}
| 105233 | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.coffee to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### DateRangeOptimizedQuery
library TestSnippet version '1'
using QUICK
parameter MeasurementPeriod default interval[DateTime(2013, 1, 1), DateTime(2014, 1, 1))
valueset "Ambulatory/ED Visit" = '2.16.840.1.113883.3.464.1003.101.12.1061'
context Patient
define EncountersDuringMP = [Encounter] E where E.period during MeasurementPeriod
define AmbulatoryEncountersDuringMP = [Encounter: "Ambulatory/ED Visit"] E where E.period during MeasurementPeriod
define AmbulatoryEncountersIncludedInMP = [Encounter: "Ambulatory/ED Visit"] E where E.period included in MeasurementPeriod
###
module.exports['DateRangeOptimizedQuery'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "MeasurementPeriod",
"default" : {
"lowClosed" : true,
"highClosed" : false,
"type" : "Interval",
"low" : {
"name" : "DateTime",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "2013",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
} ]
},
"high" : {
"name" : "DateTime",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "2014",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
} ]
}
}
} ]
},
"valueSets" : {
"def" : [ {
"name" : "Ambulatory/ED Visit",
"id" : "2.16.840.1.113883.3.464.1003.101.12.1061"
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "EncountersDuringMP",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"dateProperty" : "period",
"type" : "Retrieve",
"dateRange" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
}
} ],
"relationship" : [ ]
}
}, {
"name" : "AmbulatoryEncountersDuringMP",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"codeProperty" : "type",
"dateProperty" : "period",
"type" : "Retrieve",
"codes" : {
"name" : "Ambulatory/ED Visit",
"type" : "ValueSetRef"
},
"dateRange" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
}
} ],
"relationship" : [ ]
}
}, {
"name" : "AmbulatoryEncountersIncludedInMP",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"codeProperty" : "type",
"dateProperty" : "period",
"type" : "Retrieve",
"codes" : {
"name" : "Ambulatory/ED Visit",
"type" : "ValueSetRef"
},
"dateRange" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
}
} ],
"relationship" : [ ]
}
} ]
}
}
}
### IncludesQuery
library TestSnippet version '1'
using QUICK
parameter MeasurementPeriod default interval[DateTime(2013, 1, 1), DateTime(2014, 1, 1))
valueset "Ambulatory/ED Visit" = '2.16.840.1.113883.3.464.1003.101.12.1061'
context Patient
define MPIncludedAmbulatoryEncounters = [Encounter: "Ambulatory/ED Visit"] E where MeasurementPeriod includes E.period
###
module.exports['IncludesQuery'] = {
"library" : {
"identifier" : {
"id" : "<NAME>Snippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "MeasurementPeriod",
"default" : {
"lowClosed" : true,
"highClosed" : false,
"type" : "Interval",
"low" : {
"name" : "DateTime",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "2013",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
} ]
},
"high" : {
"name" : "DateTime",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "2014",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
} ]
}
}
} ]
},
"valueSets" : {
"def" : [ {
"name" : "Ambulatory/ED Visit",
"id" : "2.16.840.1.113883.3.464.1003.101.12.1061"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "MPIncludedAmbulatoryEncounters",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"codeProperty" : "type",
"type" : "Retrieve",
"codes" : {
"name" : "Ambulatory/ED Visit",
"type" : "ValueSetRef"
}
}
} ],
"relationship" : [ ],
"where" : {
"type" : "Includes",
"operand" : [ {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}, {
"path" : "period",
"scope" : "E",
"type" : "Property"
} ]
}
}
} ]
}
}
}
### MultiSourceQuery
library TestSnippet version '1'
using QUICK
parameter MeasurementPeriod default interval[DateTime(2013, 1, 1), DateTime(2014, 1, 1))
context Patient
define msQueryWhere = foreach [Encounter] E,
[Condition] C
where E.period included in MeasurementPeriod
define msQueryWhere2 = foreach [Encounter] E, [Condition] C
where E.period included in MeasurementPeriod and C.id = 'http://cqframework.org/3/2'
define msQuery = foreach [Encounter] E, [Condition] C return {E: E, C:C}
###
module.exports['MultiSourceQuery'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "MeasurementPeriod",
"default" : {
"lowClosed" : true,
"highClosed" : false,
"type" : "Interval",
"low" : {
"name" : "DateTime",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "2013",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
} ]
},
"high" : {
"name" : "DateTime",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "2014",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
} ]
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "msQueryWhere",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"dateProperty" : "period",
"type" : "Retrieve",
"dateRange" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
}
}, {
"alias" : "C",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Condition",
"templateId" : "cqf-condition",
"type" : "Retrieve"
}
} ],
"relationship" : [ ],
"return" : {
"distinct" : true,
"expression" : {
"type" : "Tuple",
"element" : [ {
"name" : "<NAME>",
"value" : {
"name" : "<NAME>",
"type" : "AliasRef"
}
}, {
"name" : "<NAME>",
"value" : {
"name" : "<NAME>",
"type" : "AliasRef"
}
} ]
}
}
}
}, {
"name" : "msQueryWhere2",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"dateProperty" : "period",
"type" : "Retrieve",
"dateRange" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
}
}, {
"alias" : "C",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Condition",
"templateId" : "cqf-condition",
"type" : "Retrieve"
}
} ],
"relationship" : [ ],
"where" : {
"type" : "Equal",
"operand" : [ {
"path" : "id",
"scope" : "C",
"type" : "Property"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "http://cqframework.org/3/2",
"type" : "Literal"
} ]
},
"return" : {
"distinct" : true,
"expression" : {
"type" : "Tuple",
"element" : [ {
"name" : "<NAME>",
"value" : {
"name" : "<NAME>",
"type" : "AliasRef"
}
}, {
"name" : "<NAME>",
"value" : {
"name" : "<NAME>",
"type" : "AliasRef"
}
} ]
}
}
}
}, {
"name" : "msQuery",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
}, {
"alias" : "C",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Condition",
"templateId" : "cqf-condition",
"type" : "Retrieve"
}
} ],
"relationship" : [ ],
"return" : {
"expression" : {
"type" : "Tuple",
"element" : [ {
"name" : "<NAME>",
"value" : {
"name" : "<NAME>",
"type" : "AliasRef"
}
}, {
"name" : "<NAME>",
"value" : {
"name" : "<NAME>",
"type" : "AliasRef"
}
} ]
}
}
}
} ]
}
}
}
### QueryRelationship
library TestSnippet version '1'
using QUICK
context Patient
define withQuery = [Encounter] E
with [Condition] C such that C.id= 'http://cqframework.org/3/2'
define withQuery2 = [Encounter] E
with [Condition] C such that C.id = 'http://cqframework.org/3'
define withOutQuery = [Encounter] E
without [Condition] C such that C.id = 'http://cqframework.org/3/'
define withOutQuery2 = [Encounter] E
without [Condition] C such that C.id = 'http://cqframework.org/3/2'
###
module.exports['QueryRelationship'] = {
"library" : {
"identifier" : {
"id" : "<NAME>Snippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "withQuery",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
} ],
"relationship" : [ {
"alias" : "C",
"type" : "With",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Condition",
"templateId" : "cqf-condition",
"type" : "Retrieve"
},
"suchThat" : {
"type" : "Equal",
"operand" : [ {
"path" : "id",
"scope" : "C",
"type" : "Property"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "http://cqframework.org/3/2",
"type" : "Literal"
} ]
}
} ]
}
}, {
"name" : "withQuery2",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
} ],
"relationship" : [ {
"alias" : "C",
"type" : "With",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Condition",
"templateId" : "cqf-condition",
"type" : "Retrieve"
},
"suchThat" : {
"type" : "Equal",
"operand" : [ {
"path" : "id",
"scope" : "C",
"type" : "Property"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "http://cqframework.org/3",
"type" : "Literal"
} ]
}
} ]
}
}, {
"name" : "withOutQuery",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
} ],
"relationship" : [ {
"alias" : "C",
"type" : "Without",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Condition",
"templateId" : "cqf-condition",
"type" : "Retrieve"
},
"suchThat" : {
"type" : "Equal",
"operand" : [ {
"path" : "id",
"scope" : "C",
"type" : "Property"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "http://cqframework.org/3/",
"type" : "Literal"
} ]
}
} ]
}
}, {
"name" : "withOutQuery2",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
} ],
"relationship" : [ {
"alias" : "C",
"type" : "Without",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Condition",
"templateId" : "cqf-condition",
"type" : "Retrieve"
},
"suchThat" : {
"type" : "Equal",
"operand" : [ {
"path" : "id",
"scope" : "C",
"type" : "Property"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "http://cqframework.org/3/2",
"type" : "Literal"
} ]
}
} ]
}
} ]
}
}
}
### QueryDefine
library TestSnippet version '1'
using QUICK
context Patient
define query = [Encounter] E
define a = E
return {E: E, a:a}
###
module.exports['QueryDefine'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "query",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
} ],
"define" : [ {
"identifier" : "a",
"expression" : {
"name" : "E",
"type" : "AliasRef"
}
} ],
"relationship" : [ ],
"return" : {
"expression" : {
"type" : "Tuple",
"element" : [ {
"name" : "E",
"value" : {
"name" : "E",
"type" : "AliasRef"
}
}, {
"name" : "a",
"value" : {
"name" : "a",
"type" : "QueryDefineRef"
}
} ]
}
}
}
} ]
}
}
}
### Tuple
library TestSnippet version '1'
using QUICK
context Patient
define query = [Encounter] E return {id: E.id, thing: E.status}
###
module.exports['Tuple'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "query",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
} ],
"relationship" : [ ],
"return" : {
"expression" : {
"type" : "Tuple",
"element" : [ {
"name" : "id",
"value" : {
"path" : "id",
"scope" : "E",
"type" : "Property"
}
}, {
"name" : "thing",
"value" : {
"path" : "status",
"scope" : "E",
"type" : "Property"
}
} ]
}
}
}
} ]
}
}
}
### Sorting
library TestSnippet version '1'
using QUICK
context Patient
define singleAsc = [Encounter] E return {E : E} sort by E.id
define singleDesc = [Encounter] E return {E : E} sort by E.id desc
###
module.exports['Sorting'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
} ],
"relationship" : [ ],
"return" : {
"expression" : {
"type" : "Tuple",
"element" : [ {
"name" : "E",
"value" : {
"name" : "E",
"type" : "AliasRef"
}
} ]
}
},
"sort" : {
"by" : [ {
"direction" : "asc",
"type" : "ByExpression",
"expression" : {
"path" : "id",
"scope" : "E",
"type" : "Property"
}
} ]
}
}
}, {
"name" : "<NAME>Desc",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
} ],
"relationship" : [ ],
"return" : {
"expression" : {
"type" : "Tuple",
"element" : [ {
"name" : "<NAME>",
"value" : {
"name" : "<NAME>",
"type" : "AliasRef"
}
} ]
}
},
"sort" : {
"by" : [ {
"direction" : "desc",
"type" : "ByExpression",
"expression" : {
"path" : "id",
"scope" : "E",
"type" : "Property"
}
} ]
}
}
} ]
}
}
}
| true | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.coffee to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### DateRangeOptimizedQuery
library TestSnippet version '1'
using QUICK
parameter MeasurementPeriod default interval[DateTime(2013, 1, 1), DateTime(2014, 1, 1))
valueset "Ambulatory/ED Visit" = '2.16.840.1.113883.3.464.1003.101.12.1061'
context Patient
define EncountersDuringMP = [Encounter] E where E.period during MeasurementPeriod
define AmbulatoryEncountersDuringMP = [Encounter: "Ambulatory/ED Visit"] E where E.period during MeasurementPeriod
define AmbulatoryEncountersIncludedInMP = [Encounter: "Ambulatory/ED Visit"] E where E.period included in MeasurementPeriod
###
module.exports['DateRangeOptimizedQuery'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "MeasurementPeriod",
"default" : {
"lowClosed" : true,
"highClosed" : false,
"type" : "Interval",
"low" : {
"name" : "DateTime",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "2013",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
} ]
},
"high" : {
"name" : "DateTime",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "2014",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
} ]
}
}
} ]
},
"valueSets" : {
"def" : [ {
"name" : "Ambulatory/ED Visit",
"id" : "2.16.840.1.113883.3.464.1003.101.12.1061"
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "EncountersDuringMP",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"dateProperty" : "period",
"type" : "Retrieve",
"dateRange" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
}
} ],
"relationship" : [ ]
}
}, {
"name" : "AmbulatoryEncountersDuringMP",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"codeProperty" : "type",
"dateProperty" : "period",
"type" : "Retrieve",
"codes" : {
"name" : "Ambulatory/ED Visit",
"type" : "ValueSetRef"
},
"dateRange" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
}
} ],
"relationship" : [ ]
}
}, {
"name" : "AmbulatoryEncountersIncludedInMP",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"codeProperty" : "type",
"dateProperty" : "period",
"type" : "Retrieve",
"codes" : {
"name" : "Ambulatory/ED Visit",
"type" : "ValueSetRef"
},
"dateRange" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
}
} ],
"relationship" : [ ]
}
} ]
}
}
}
### IncludesQuery
library TestSnippet version '1'
using QUICK
parameter MeasurementPeriod default interval[DateTime(2013, 1, 1), DateTime(2014, 1, 1))
valueset "Ambulatory/ED Visit" = '2.16.840.1.113883.3.464.1003.101.12.1061'
context Patient
define MPIncludedAmbulatoryEncounters = [Encounter: "Ambulatory/ED Visit"] E where MeasurementPeriod includes E.period
###
module.exports['IncludesQuery'] = {
"library" : {
"identifier" : {
"id" : "PI:NAME:<NAME>END_PISnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "MeasurementPeriod",
"default" : {
"lowClosed" : true,
"highClosed" : false,
"type" : "Interval",
"low" : {
"name" : "DateTime",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "2013",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
} ]
},
"high" : {
"name" : "DateTime",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "2014",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
} ]
}
}
} ]
},
"valueSets" : {
"def" : [ {
"name" : "Ambulatory/ED Visit",
"id" : "2.16.840.1.113883.3.464.1003.101.12.1061"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "MPIncludedAmbulatoryEncounters",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"codeProperty" : "type",
"type" : "Retrieve",
"codes" : {
"name" : "Ambulatory/ED Visit",
"type" : "ValueSetRef"
}
}
} ],
"relationship" : [ ],
"where" : {
"type" : "Includes",
"operand" : [ {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}, {
"path" : "period",
"scope" : "E",
"type" : "Property"
} ]
}
}
} ]
}
}
}
### MultiSourceQuery
library TestSnippet version '1'
using QUICK
parameter MeasurementPeriod default interval[DateTime(2013, 1, 1), DateTime(2014, 1, 1))
context Patient
define msQueryWhere = foreach [Encounter] E,
[Condition] C
where E.period included in MeasurementPeriod
define msQueryWhere2 = foreach [Encounter] E, [Condition] C
where E.period included in MeasurementPeriod and C.id = 'http://cqframework.org/3/2'
define msQuery = foreach [Encounter] E, [Condition] C return {E: E, C:C}
###
module.exports['MultiSourceQuery'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "MeasurementPeriod",
"default" : {
"lowClosed" : true,
"highClosed" : false,
"type" : "Interval",
"low" : {
"name" : "DateTime",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "2013",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
} ]
},
"high" : {
"name" : "DateTime",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "2014",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}int",
"value" : "1",
"type" : "Literal"
} ]
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "msQueryWhere",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"dateProperty" : "period",
"type" : "Retrieve",
"dateRange" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
}
}, {
"alias" : "C",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Condition",
"templateId" : "cqf-condition",
"type" : "Retrieve"
}
} ],
"relationship" : [ ],
"return" : {
"distinct" : true,
"expression" : {
"type" : "Tuple",
"element" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"value" : {
"name" : "PI:NAME:<NAME>END_PI",
"type" : "AliasRef"
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"value" : {
"name" : "PI:NAME:<NAME>END_PI",
"type" : "AliasRef"
}
} ]
}
}
}
}, {
"name" : "msQueryWhere2",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"dateProperty" : "period",
"type" : "Retrieve",
"dateRange" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
}
}, {
"alias" : "C",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Condition",
"templateId" : "cqf-condition",
"type" : "Retrieve"
}
} ],
"relationship" : [ ],
"where" : {
"type" : "Equal",
"operand" : [ {
"path" : "id",
"scope" : "C",
"type" : "Property"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "http://cqframework.org/3/2",
"type" : "Literal"
} ]
},
"return" : {
"distinct" : true,
"expression" : {
"type" : "Tuple",
"element" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"value" : {
"name" : "PI:NAME:<NAME>END_PI",
"type" : "AliasRef"
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"value" : {
"name" : "PI:NAME:<NAME>END_PI",
"type" : "AliasRef"
}
} ]
}
}
}
}, {
"name" : "msQuery",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
}, {
"alias" : "C",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Condition",
"templateId" : "cqf-condition",
"type" : "Retrieve"
}
} ],
"relationship" : [ ],
"return" : {
"expression" : {
"type" : "Tuple",
"element" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"value" : {
"name" : "PI:NAME:<NAME>END_PI",
"type" : "AliasRef"
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"value" : {
"name" : "PI:NAME:<NAME>END_PI",
"type" : "AliasRef"
}
} ]
}
}
}
} ]
}
}
}
### QueryRelationship
library TestSnippet version '1'
using QUICK
context Patient
define withQuery = [Encounter] E
with [Condition] C such that C.id= 'http://cqframework.org/3/2'
define withQuery2 = [Encounter] E
with [Condition] C such that C.id = 'http://cqframework.org/3'
define withOutQuery = [Encounter] E
without [Condition] C such that C.id = 'http://cqframework.org/3/'
define withOutQuery2 = [Encounter] E
without [Condition] C such that C.id = 'http://cqframework.org/3/2'
###
module.exports['QueryRelationship'] = {
"library" : {
"identifier" : {
"id" : "PI:NAME:<NAME>END_PISnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "withQuery",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
} ],
"relationship" : [ {
"alias" : "C",
"type" : "With",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Condition",
"templateId" : "cqf-condition",
"type" : "Retrieve"
},
"suchThat" : {
"type" : "Equal",
"operand" : [ {
"path" : "id",
"scope" : "C",
"type" : "Property"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "http://cqframework.org/3/2",
"type" : "Literal"
} ]
}
} ]
}
}, {
"name" : "withQuery2",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
} ],
"relationship" : [ {
"alias" : "C",
"type" : "With",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Condition",
"templateId" : "cqf-condition",
"type" : "Retrieve"
},
"suchThat" : {
"type" : "Equal",
"operand" : [ {
"path" : "id",
"scope" : "C",
"type" : "Property"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "http://cqframework.org/3",
"type" : "Literal"
} ]
}
} ]
}
}, {
"name" : "withOutQuery",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
} ],
"relationship" : [ {
"alias" : "C",
"type" : "Without",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Condition",
"templateId" : "cqf-condition",
"type" : "Retrieve"
},
"suchThat" : {
"type" : "Equal",
"operand" : [ {
"path" : "id",
"scope" : "C",
"type" : "Property"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "http://cqframework.org/3/",
"type" : "Literal"
} ]
}
} ]
}
}, {
"name" : "withOutQuery2",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
} ],
"relationship" : [ {
"alias" : "C",
"type" : "Without",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Condition",
"templateId" : "cqf-condition",
"type" : "Retrieve"
},
"suchThat" : {
"type" : "Equal",
"operand" : [ {
"path" : "id",
"scope" : "C",
"type" : "Property"
}, {
"valueType" : "{http://www.w3.org/2001/XMLSchema}string",
"value" : "http://cqframework.org/3/2",
"type" : "Literal"
} ]
}
} ]
}
} ]
}
}
}
### QueryDefine
library TestSnippet version '1'
using QUICK
context Patient
define query = [Encounter] E
define a = E
return {E: E, a:a}
###
module.exports['QueryDefine'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "query",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
} ],
"define" : [ {
"identifier" : "a",
"expression" : {
"name" : "E",
"type" : "AliasRef"
}
} ],
"relationship" : [ ],
"return" : {
"expression" : {
"type" : "Tuple",
"element" : [ {
"name" : "E",
"value" : {
"name" : "E",
"type" : "AliasRef"
}
}, {
"name" : "a",
"value" : {
"name" : "a",
"type" : "QueryDefineRef"
}
} ]
}
}
}
} ]
}
}
}
### Tuple
library TestSnippet version '1'
using QUICK
context Patient
define query = [Encounter] E return {id: E.id, thing: E.status}
###
module.exports['Tuple'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "query",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
} ],
"relationship" : [ ],
"return" : {
"expression" : {
"type" : "Tuple",
"element" : [ {
"name" : "id",
"value" : {
"path" : "id",
"scope" : "E",
"type" : "Property"
}
}, {
"name" : "thing",
"value" : {
"path" : "status",
"scope" : "E",
"type" : "Property"
}
} ]
}
}
}
} ]
}
}
}
### Sorting
library TestSnippet version '1'
using QUICK
context Patient
define singleAsc = [Encounter] E return {E : E} sort by E.id
define singleDesc = [Encounter] E return {E : E} sort by E.id desc
###
module.exports['Sorting'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "QUICK",
"uri" : "http://org.hl7.fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://org.hl7.fhir}Patient",
"templateId" : "cqf-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
} ],
"relationship" : [ ],
"return" : {
"expression" : {
"type" : "Tuple",
"element" : [ {
"name" : "E",
"value" : {
"name" : "E",
"type" : "AliasRef"
}
} ]
}
},
"sort" : {
"by" : [ {
"direction" : "asc",
"type" : "ByExpression",
"expression" : {
"path" : "id",
"scope" : "E",
"type" : "Property"
}
} ]
}
}
}, {
"name" : "PI:NAME:<NAME>END_PIDesc",
"context" : "Patient",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "E",
"expression" : {
"dataType" : "{http://org.hl7.fhir}Encounter",
"templateId" : "cqf-encounter",
"type" : "Retrieve"
}
} ],
"relationship" : [ ],
"return" : {
"expression" : {
"type" : "Tuple",
"element" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"value" : {
"name" : "PI:NAME:<NAME>END_PI",
"type" : "AliasRef"
}
} ]
}
},
"sort" : {
"by" : [ {
"direction" : "desc",
"type" : "ByExpression",
"expression" : {
"path" : "id",
"scope" : "E",
"type" : "Property"
}
} ]
}
}
} ]
}
}
}
|
[
{
"context": "lumns ?= new Backbone.Collection [\n { name: 'greeting' }\n { name: 'everyone' }\n ]\n\n model ?=",
"end": 216,
"score": 0.9975782632827759,
"start": 208,
"tag": "NAME",
"value": "greeting"
},
{
"context": "ction [\n { name: 'greeting' }\n { na... | spec/body-row-columns-spec.coffee | juanca/marion-tree | 1 | describe 'BodyRowColumns', ->
BodyRowColumns = require '../lib/javascripts/body-row-columns'
view = null
initView = ({ columns, model } = {}) ->
columns ?= new Backbone.Collection [
{ name: 'greeting' }
{ name: 'everyone' }
]
model ?= new Backbone.Model
greeting: 'hola'
everyone: 'todos'
view = new BodyRowColumns { columns, model }
showView = ->
initView(arguments...).render()
afterEach ->
view?.destroy()
view = null
it 'has a className', ->
expect(showView().$el).toHaveClass 'body-row-columns'
it 'defaults the childView to a StringCell', ->
renderedText = showView().children.map (stringCellView) -> stringCellView.$el.text()
expect(renderedText).toEqual ['hola', 'todos']
it 'uses the cell of the column', ->
showView columns: new Backbone.Collection [
{ cell: Backbone.Marionette.ItemView.extend template: -> 'hello' }
{ cell: Backbone.Marionette.ItemView.extend template: -> 'world' }
]
renderedText = view.children.map (stringCellView) -> stringCellView.$el.text()
expect(renderedText).toEqual ['hello', 'world']
it 'uses BodyRowColumns for many cells', ->
showView columns: new Backbone.Collection [
{ cells: [
{ cell: Backbone.Marionette.ItemView.extend template: -> 'hello' }
{ cell: Backbone.Marionette.ItemView.extend template: -> 'world' }
] }
]
renderedText = view.children.first().children.map (stringCellView) -> stringCellView.$el.text()
expect(renderedText).toEqual ['hello', 'world']
| 216032 | describe 'BodyRowColumns', ->
BodyRowColumns = require '../lib/javascripts/body-row-columns'
view = null
initView = ({ columns, model } = {}) ->
columns ?= new Backbone.Collection [
{ name: '<NAME>' }
{ name: '<NAME>' }
]
model ?= new Backbone.Model
greeting: 'h<NAME>'
everyone: 'todos'
view = new BodyRowColumns { columns, model }
showView = ->
initView(arguments...).render()
afterEach ->
view?.destroy()
view = null
it 'has a className', ->
expect(showView().$el).toHaveClass 'body-row-columns'
it 'defaults the childView to a StringCell', ->
renderedText = showView().children.map (stringCellView) -> stringCellView.$el.text()
expect(renderedText).toEqual ['hola', 'todos']
it 'uses the cell of the column', ->
showView columns: new Backbone.Collection [
{ cell: Backbone.Marionette.ItemView.extend template: -> 'hello' }
{ cell: Backbone.Marionette.ItemView.extend template: -> 'world' }
]
renderedText = view.children.map (stringCellView) -> stringCellView.$el.text()
expect(renderedText).toEqual ['hello', 'world']
it 'uses BodyRowColumns for many cells', ->
showView columns: new Backbone.Collection [
{ cells: [
{ cell: Backbone.Marionette.ItemView.extend template: -> 'hello' }
{ cell: Backbone.Marionette.ItemView.extend template: -> 'world' }
] }
]
renderedText = view.children.first().children.map (stringCellView) -> stringCellView.$el.text()
expect(renderedText).toEqual ['hello', 'world']
| true | describe 'BodyRowColumns', ->
BodyRowColumns = require '../lib/javascripts/body-row-columns'
view = null
initView = ({ columns, model } = {}) ->
columns ?= new Backbone.Collection [
{ name: 'PI:NAME:<NAME>END_PI' }
{ name: 'PI:NAME:<NAME>END_PI' }
]
model ?= new Backbone.Model
greeting: 'hPI:NAME:<NAME>END_PI'
everyone: 'todos'
view = new BodyRowColumns { columns, model }
showView = ->
initView(arguments...).render()
afterEach ->
view?.destroy()
view = null
it 'has a className', ->
expect(showView().$el).toHaveClass 'body-row-columns'
it 'defaults the childView to a StringCell', ->
renderedText = showView().children.map (stringCellView) -> stringCellView.$el.text()
expect(renderedText).toEqual ['hola', 'todos']
it 'uses the cell of the column', ->
showView columns: new Backbone.Collection [
{ cell: Backbone.Marionette.ItemView.extend template: -> 'hello' }
{ cell: Backbone.Marionette.ItemView.extend template: -> 'world' }
]
renderedText = view.children.map (stringCellView) -> stringCellView.$el.text()
expect(renderedText).toEqual ['hello', 'world']
it 'uses BodyRowColumns for many cells', ->
showView columns: new Backbone.Collection [
{ cells: [
{ cell: Backbone.Marionette.ItemView.extend template: -> 'hello' }
{ cell: Backbone.Marionette.ItemView.extend template: -> 'world' }
] }
]
renderedText = view.children.first().children.map (stringCellView) -> stringCellView.$el.text()
expect(renderedText).toEqual ['hello', 'world']
|
[
{
"context": "\n\n\t_.forIn thing, (val, key) ->\n\t\tif key is 'using_filesort' and val is true\n\t\t\tfilesorts.push thing\n\n\t\tif",
"end": 293,
"score": 0.5359348058700562,
"start": 288,
"tag": "KEY",
"value": "files"
}
] | lib/checks/filesort.coffee | juristat/mysql2-auditor | 0 | _ = require 'lodash'
module.exports = (entry, result) ->
if entry.explanation?
fs = findFilesort entry.explanation
if fs.length > 0
result.warning "Query uses #{fs.length} filesort(s)"
findFilesort = (thing) ->
filesorts = []
_.forIn thing, (val, key) ->
if key is 'using_filesort' and val is true
filesorts.push thing
if _.isArray val
val.forEach (elm) ->
if _.isObject elm
filesorts = filesorts.concat findFilesort elm
if _.isObject val
filesorts = filesorts.concat findFilesort val
filesorts
| 142977 | _ = require 'lodash'
module.exports = (entry, result) ->
if entry.explanation?
fs = findFilesort entry.explanation
if fs.length > 0
result.warning "Query uses #{fs.length} filesort(s)"
findFilesort = (thing) ->
filesorts = []
_.forIn thing, (val, key) ->
if key is 'using_<KEY>ort' and val is true
filesorts.push thing
if _.isArray val
val.forEach (elm) ->
if _.isObject elm
filesorts = filesorts.concat findFilesort elm
if _.isObject val
filesorts = filesorts.concat findFilesort val
filesorts
| true | _ = require 'lodash'
module.exports = (entry, result) ->
if entry.explanation?
fs = findFilesort entry.explanation
if fs.length > 0
result.warning "Query uses #{fs.length} filesort(s)"
findFilesort = (thing) ->
filesorts = []
_.forIn thing, (val, key) ->
if key is 'using_PI:KEY:<KEY>END_PIort' and val is true
filesorts.push thing
if _.isArray val
val.forEach (elm) ->
if _.isObject elm
filesorts = filesorts.concat findFilesort elm
if _.isObject val
filesorts = filesorts.concat findFilesort val
filesorts
|
[
{
"context": "ontact/shared/tableview.tpl'\n\n COL_COOKIE_KEY = 'list_columns:'\n ORDER_KEY = 'columns_order:'\n\n $cols",
"end": 420,
"score": 0.5193333625793457,
"start": 416,
"tag": "KEY",
"value": "list"
},
{
"context": "t/shared/tableview.tpl'\n\n COL_COOKIE_KEY = 'list_colu... | vendor/assets/javascripts/keybridge/kb.tableview.js.coffee | eduvo/bootstrap-sass | 0 | ###
Keybridge Table view control
columns_statements: This file define the field candidate,
field label and sort arguments.
###
define (require)->
require 'jquery.currency'
UrlPath = require 'keybridge/urlpath'
Pagination = require 'keybridge/kb.pagination'
ColumnStatements = require 'contact/shared/columns_statements'
TableViewTemplate = require 'contact/shared/tableview.tpl'
COL_COOKIE_KEY = 'list_columns:'
ORDER_KEY = 'columns_order:'
$cols_window = $('.define-cols-window')
cols_target = $cols_window.data 'target'
COL_ORDER_BY_HASH = ColumnStatements[cols_target].columns_order_by
COLUMN_LABEL = ColumnStatements[cols_target].column_label
TITLE_COL = TableViewTemplate.title_col
TITLE_ROW = TableViewTemplate.title_row
COL = TableViewTemplate.col
COL_NAMECARD = TableViewTemplate.col_namecard
COL_ORG_GROUP = TableViewTemplate.col_org_group
ROW = TableViewTemplate.row
DATE_FORMAT = "MMM D, YYYY"
CR = "<br/>"
PPL = 'people'
ORG = 'organization'
class TableView
_duration = 200
_get = _.debounce $.get, _duration
_pagination = new Pagination $('.pages-selector')
_getString = (str) ->
return '' unless str
str
_isNowrap = (key) ->
key in [
'country_name'
]
_prepareColumn = (column_key, column_object, data) ->
return '' unless column_object
if $.type(column_object) is 'object'
switch column_key
when 'primary_address' then do ->
address = "<p class='address'>"
address += "#{_getString column_object.address} #{CR}" if column_object.address
address += "#{_getString column_object.address_ii} #{CR}" if column_object.address_ii
address += "#{_getString column_object.city}, " if column_object.city
address += "#{_getString column_object.state} " if column_object.state
address += "#{_getString column_object.postal_code} #{CR}" if column_object.postal_code
address += "#{_getString column_object.country_name} #{CR}" if column_object.country_name
address += "</p>"
else do ->
''
else if $.isArray(column_object)
return '' unless column_object.length
switch column_key
when 'annual_upsell_value_items', 'enabled_subscriptions', 'subscriptions'
Mustache.render TableViewTemplate.annual_upsell, column_object
when 'invoices'
Mustache.render TableViewTemplate.invoices_dl, column_object
when 'invoices.total'
Mustache.render TableViewTemplate.invoices_amount, column_object
when 'invoices.status'
Mustache.render TableViewTemplate.invoices_status, column_object
when 'invoices.due_on'
Mustache.render TableViewTemplate.invoices_due_on, _.map column_object, (object) ->
object.due_on = moment(object.due_on).format DATE_FORMAT
object
when 'invoices.issued_on'
Mustache.render TableViewTemplate.invoices_issued_on, _.map column_object, (object) ->
object.issued_on = moment(object.issued_on).format DATE_FORMAT
object
else
switch column_key
when 'expected_price'
"<span class='currency'>#{column_object}</span>"
when 'name'
"<span class='org-name'>#{column_object}</span>"
when 'organization.name'
"<a href='/organization/#{data.organization.id}'>#{column_object}</a>"
when 'billing_renewal_month'
moment()
.months(column_object - 1)
.format('MMMM')
when 'subscription_status_name'
"<a href='#' class='status-filter' data-param='type_ids' data-id='#{data.subscription_status_id}'>#{ column_object }"
when 'country_name'
Mustache.render TableViewTemplate.country_name,
country_alpha2: data.country_alpha2
country_name: column_object
country_icon: data.country_icon
else
column_object
# Prepare key value b/c the key value might have a point symbol that repre-
# sents to use child object's attribute.
_prepareKey = (key) ->
key_list = key.split '.'
return key_list
is_user_define_col: no
col_list: []
params_white_list:[
'target'
'order'
'type_ids'
'region_ids'
'tag_ids'
'product_ids'
'page'
'per'
]
reset_title: yes
constructor: (@url, @$container, @$title_container, @template, @is_user_define_col) ->
if @is_user_define_col
throw Error("Need $title_container") unless @$title_container
throw Error("Need col_list in cookie") unless @col_list
UrlPath.registryAction updateAction = =>
hash = window.location.hash
params = UrlPath.refineParam hash
if $.isEmptyObject(params) and gon?.cache_contacts_first_p?
@renderAll gon.cache_contacts_first_p
$('.namecard').namecard()
_pagination?.updatePagination params
else
@sendRequest params, ->
$('.namecard').namecard()
_pagination?.updatePagination params
updateAction()
$container.on 'content:update', (e) =>
@reset_title = yes
if @data.length
@$container
.closest('div')
.addClass 'loading'
@renderAll @data
$('.adjustable .cells').resizable handles: 'e'
$('.namecard').namecard()
@$container
.closest('div').removeClass 'loading'
else
$(UrlPath).trigger 'forceupdate'
renderAll: (list) ->
# Cache the data
@data = list
@col_list = $.cookie(COL_COOKIE_KEY + cols_target).split ','
@$container.empty()
@$container.append(@renderOne data, seq) for data, seq in list
if @is_user_define_col and @col_list.length and @reset_title
@$title_container.html @renderDefineTitle(@col_list, $('#accordion-company-contacts-title th'))
@$title_container.trigger 'refresh_sorting_symbol'
@reset_title = no
$('.currency').currency decimals: 0
$('#column-control').trigger 'force.active' if @col_list.length > 4
yes
renderOne: (data, seq) ->
if @is_user_define_col and @col_list.length
renderedContent = @renderDefineCols @col_list, data, seq
else
renderedContent = Mustache.render(@template, data)
return renderedContent
renderDefineTitle: (cols, $orgin_title) ->
row_content = ''
t_class = 'adjustable'
_.each cols, (key) ->
row_content += Mustache.render TITLE_COL,
value: COLUMN_LABEL[key]
id: COL_ORDER_BY_HASH[key]
key: key
t_class: t_class
c_class: unless COL_ORDER_BY_HASH[key] is '' then 'sortable' else 'unsortable'
Mustache.render TITLE_ROW, cols: row_content
renderDefineCols: (cols, data, seq) ->
return '' unless cols.length and data
row_content = []
col_raw = ''
_.each cols, (key, index)->
[parent, child] = _prepareKey key
col_val = ''
if parent of data
col_val = if child and child of data[parent] then data[parent][child] else data[parent]
col_val = _prepareColumn key, col_val, data
if index is 0 and cols_target is PPL
col_raw = Mustache.render COL_NAMECARD, value: col_val, data: data
else if index is 0 and cols_target is ORG
col_raw = Mustache.render COL_ORG_GROUP, value: col_val, data: data
else
col_raw = Mustache.render COL, value: col_val
col_raw = Mustache.render COL, value: col_val, special_class: 'nowrap' if _isNowrap(key)
row_content.push col_raw
return Mustache.render ROW, cols: row_content.join(''), id: data.id
sendRequest: (params, callback) ->
@$container
.closest('div')
.addClass 'loading'
_get @url, params, (result) =>
@renderAll result
$('.adjustable .cells').resizable handles: 'e'
callback?()
@$container
.closest('div').removeClass 'loading'
@$container.trigger 'refresh_filter', [params]
filterParams: (params) ->
params = _.pick params, @params_white_list
changeState: (params, callback) ->
params = @filterParams params
unless params['page']? then UrlPath.remove('page')
_.each params, (value, key) ->
UrlPath.update key, value
do UrlPath.route
| 29580 | ###
Keybridge Table view control
columns_statements: This file define the field candidate,
field label and sort arguments.
###
define (require)->
require 'jquery.currency'
UrlPath = require 'keybridge/urlpath'
Pagination = require 'keybridge/kb.pagination'
ColumnStatements = require 'contact/shared/columns_statements'
TableViewTemplate = require 'contact/shared/tableview.tpl'
COL_COOKIE_KEY = '<KEY>_<KEY>:'
ORDER_KEY = 'columns_order:'
$cols_window = $('.define-cols-window')
cols_target = $cols_window.data 'target'
COL_ORDER_BY_HASH = ColumnStatements[cols_target].columns_order_by
COLUMN_LABEL = ColumnStatements[cols_target].column_label
TITLE_COL = TableViewTemplate.title_col
TITLE_ROW = TableViewTemplate.title_row
COL = TableViewTemplate.col
COL_NAMECARD = TableViewTemplate.col_namecard
COL_ORG_GROUP = TableViewTemplate.col_org_group
ROW = TableViewTemplate.row
DATE_FORMAT = "MMM D, YYYY"
CR = "<br/>"
PPL = 'people'
ORG = 'organization'
class TableView
_duration = 200
_get = _.debounce $.get, _duration
_pagination = new Pagination $('.pages-selector')
_getString = (str) ->
return '' unless str
str
_isNowrap = (key) ->
key in [
'country_name'
]
_prepareColumn = (column_key, column_object, data) ->
return '' unless column_object
if $.type(column_object) is 'object'
switch column_key
when 'primary_address' then do ->
address = "<p class='address'>"
address += "#{_getString column_object.address} #{CR}" if column_object.address
address += "#{_getString column_object.address_ii} #{CR}" if column_object.address_ii
address += "#{_getString column_object.city}, " if column_object.city
address += "#{_getString column_object.state} " if column_object.state
address += "#{_getString column_object.postal_code} #{CR}" if column_object.postal_code
address += "#{_getString column_object.country_name} #{CR}" if column_object.country_name
address += "</p>"
else do ->
''
else if $.isArray(column_object)
return '' unless column_object.length
switch column_key
when 'annual_upsell_value_items', 'enabled_subscriptions', 'subscriptions'
Mustache.render TableViewTemplate.annual_upsell, column_object
when 'invoices'
Mustache.render TableViewTemplate.invoices_dl, column_object
when 'invoices.total'
Mustache.render TableViewTemplate.invoices_amount, column_object
when 'invoices.status'
Mustache.render TableViewTemplate.invoices_status, column_object
when 'invoices.due_on'
Mustache.render TableViewTemplate.invoices_due_on, _.map column_object, (object) ->
object.due_on = moment(object.due_on).format DATE_FORMAT
object
when 'invoices.issued_on'
Mustache.render TableViewTemplate.invoices_issued_on, _.map column_object, (object) ->
object.issued_on = moment(object.issued_on).format DATE_FORMAT
object
else
switch column_key
when 'expected_price'
"<span class='currency'>#{column_object}</span>"
when 'name'
"<span class='org-name'>#{column_object}</span>"
when 'organization.name'
"<a href='/organization/#{data.organization.id}'>#{column_object}</a>"
when 'billing_renewal_month'
moment()
.months(column_object - 1)
.format('MMMM')
when 'subscription_status_name'
"<a href='#' class='status-filter' data-param='type_ids' data-id='#{data.subscription_status_id}'>#{ column_object }"
when 'country_name'
Mustache.render TableViewTemplate.country_name,
country_alpha2: data.country_alpha2
country_name: column_object
country_icon: data.country_icon
else
column_object
# Prepare key value b/c the key value might have a point symbol that repre-
# sents to use child object's attribute.
_prepareKey = (key) ->
key_list = key.split '.'
return key_list
is_user_define_col: no
col_list: []
params_white_list:[
'target'
'order'
'type_ids'
'region_ids'
'tag_ids'
'product_ids'
'page'
'per'
]
reset_title: yes
constructor: (@url, @$container, @$title_container, @template, @is_user_define_col) ->
if @is_user_define_col
throw Error("Need $title_container") unless @$title_container
throw Error("Need col_list in cookie") unless @col_list
UrlPath.registryAction updateAction = =>
hash = window.location.hash
params = UrlPath.refineParam hash
if $.isEmptyObject(params) and gon?.cache_contacts_first_p?
@renderAll gon.cache_contacts_first_p
$('.namecard').namecard()
_pagination?.updatePagination params
else
@sendRequest params, ->
$('.namecard').namecard()
_pagination?.updatePagination params
updateAction()
$container.on 'content:update', (e) =>
@reset_title = yes
if @data.length
@$container
.closest('div')
.addClass 'loading'
@renderAll @data
$('.adjustable .cells').resizable handles: 'e'
$('.namecard').namecard()
@$container
.closest('div').removeClass 'loading'
else
$(UrlPath).trigger 'forceupdate'
renderAll: (list) ->
# Cache the data
@data = list
@col_list = $.cookie(COL_COOKIE_KEY + cols_target).split ','
@$container.empty()
@$container.append(@renderOne data, seq) for data, seq in list
if @is_user_define_col and @col_list.length and @reset_title
@$title_container.html @renderDefineTitle(@col_list, $('#accordion-company-contacts-title th'))
@$title_container.trigger 'refresh_sorting_symbol'
@reset_title = no
$('.currency').currency decimals: 0
$('#column-control').trigger 'force.active' if @col_list.length > 4
yes
renderOne: (data, seq) ->
if @is_user_define_col and @col_list.length
renderedContent = @renderDefineCols @col_list, data, seq
else
renderedContent = Mustache.render(@template, data)
return renderedContent
renderDefineTitle: (cols, $orgin_title) ->
row_content = ''
t_class = 'adjustable'
_.each cols, (key) ->
row_content += Mustache.render TITLE_COL,
value: COLUMN_LABEL[key]
id: COL_ORDER_BY_HASH[key]
key: key
t_class: t_class
c_class: unless COL_ORDER_BY_HASH[key] is '' then 'sortable' else 'unsortable'
Mustache.render TITLE_ROW, cols: row_content
renderDefineCols: (cols, data, seq) ->
return '' unless cols.length and data
row_content = []
col_raw = ''
_.each cols, (key, index)->
[parent, child] = _prepareKey key
col_val = ''
if parent of data
col_val = if child and child of data[parent] then data[parent][child] else data[parent]
col_val = _prepareColumn key, col_val, data
if index is 0 and cols_target is PPL
col_raw = Mustache.render COL_NAMECARD, value: col_val, data: data
else if index is 0 and cols_target is ORG
col_raw = Mustache.render COL_ORG_GROUP, value: col_val, data: data
else
col_raw = Mustache.render COL, value: col_val
col_raw = Mustache.render COL, value: col_val, special_class: 'nowrap' if _isNowrap(key)
row_content.push col_raw
return Mustache.render ROW, cols: row_content.join(''), id: data.id
sendRequest: (params, callback) ->
@$container
.closest('div')
.addClass 'loading'
_get @url, params, (result) =>
@renderAll result
$('.adjustable .cells').resizable handles: 'e'
callback?()
@$container
.closest('div').removeClass 'loading'
@$container.trigger 'refresh_filter', [params]
filterParams: (params) ->
params = _.pick params, @params_white_list
changeState: (params, callback) ->
params = @filterParams params
unless params['page']? then UrlPath.remove('page')
_.each params, (value, key) ->
UrlPath.update key, value
do UrlPath.route
| true | ###
Keybridge Table view control
columns_statements: This file define the field candidate,
field label and sort arguments.
###
define (require)->
require 'jquery.currency'
UrlPath = require 'keybridge/urlpath'
Pagination = require 'keybridge/kb.pagination'
ColumnStatements = require 'contact/shared/columns_statements'
TableViewTemplate = require 'contact/shared/tableview.tpl'
COL_COOKIE_KEY = 'PI:KEY:<KEY>END_PI_PI:KEY:<KEY>END_PI:'
ORDER_KEY = 'columns_order:'
$cols_window = $('.define-cols-window')
cols_target = $cols_window.data 'target'
COL_ORDER_BY_HASH = ColumnStatements[cols_target].columns_order_by
COLUMN_LABEL = ColumnStatements[cols_target].column_label
TITLE_COL = TableViewTemplate.title_col
TITLE_ROW = TableViewTemplate.title_row
COL = TableViewTemplate.col
COL_NAMECARD = TableViewTemplate.col_namecard
COL_ORG_GROUP = TableViewTemplate.col_org_group
ROW = TableViewTemplate.row
DATE_FORMAT = "MMM D, YYYY"
CR = "<br/>"
PPL = 'people'
ORG = 'organization'
class TableView
_duration = 200
_get = _.debounce $.get, _duration
_pagination = new Pagination $('.pages-selector')
_getString = (str) ->
return '' unless str
str
_isNowrap = (key) ->
key in [
'country_name'
]
_prepareColumn = (column_key, column_object, data) ->
return '' unless column_object
if $.type(column_object) is 'object'
switch column_key
when 'primary_address' then do ->
address = "<p class='address'>"
address += "#{_getString column_object.address} #{CR}" if column_object.address
address += "#{_getString column_object.address_ii} #{CR}" if column_object.address_ii
address += "#{_getString column_object.city}, " if column_object.city
address += "#{_getString column_object.state} " if column_object.state
address += "#{_getString column_object.postal_code} #{CR}" if column_object.postal_code
address += "#{_getString column_object.country_name} #{CR}" if column_object.country_name
address += "</p>"
else do ->
''
else if $.isArray(column_object)
return '' unless column_object.length
switch column_key
when 'annual_upsell_value_items', 'enabled_subscriptions', 'subscriptions'
Mustache.render TableViewTemplate.annual_upsell, column_object
when 'invoices'
Mustache.render TableViewTemplate.invoices_dl, column_object
when 'invoices.total'
Mustache.render TableViewTemplate.invoices_amount, column_object
when 'invoices.status'
Mustache.render TableViewTemplate.invoices_status, column_object
when 'invoices.due_on'
Mustache.render TableViewTemplate.invoices_due_on, _.map column_object, (object) ->
object.due_on = moment(object.due_on).format DATE_FORMAT
object
when 'invoices.issued_on'
Mustache.render TableViewTemplate.invoices_issued_on, _.map column_object, (object) ->
object.issued_on = moment(object.issued_on).format DATE_FORMAT
object
else
switch column_key
when 'expected_price'
"<span class='currency'>#{column_object}</span>"
when 'name'
"<span class='org-name'>#{column_object}</span>"
when 'organization.name'
"<a href='/organization/#{data.organization.id}'>#{column_object}</a>"
when 'billing_renewal_month'
moment()
.months(column_object - 1)
.format('MMMM')
when 'subscription_status_name'
"<a href='#' class='status-filter' data-param='type_ids' data-id='#{data.subscription_status_id}'>#{ column_object }"
when 'country_name'
Mustache.render TableViewTemplate.country_name,
country_alpha2: data.country_alpha2
country_name: column_object
country_icon: data.country_icon
else
column_object
# Prepare key value b/c the key value might have a point symbol that repre-
# sents to use child object's attribute.
_prepareKey = (key) ->
key_list = key.split '.'
return key_list
is_user_define_col: no
col_list: []
params_white_list:[
'target'
'order'
'type_ids'
'region_ids'
'tag_ids'
'product_ids'
'page'
'per'
]
reset_title: yes
constructor: (@url, @$container, @$title_container, @template, @is_user_define_col) ->
if @is_user_define_col
throw Error("Need $title_container") unless @$title_container
throw Error("Need col_list in cookie") unless @col_list
UrlPath.registryAction updateAction = =>
hash = window.location.hash
params = UrlPath.refineParam hash
if $.isEmptyObject(params) and gon?.cache_contacts_first_p?
@renderAll gon.cache_contacts_first_p
$('.namecard').namecard()
_pagination?.updatePagination params
else
@sendRequest params, ->
$('.namecard').namecard()
_pagination?.updatePagination params
updateAction()
$container.on 'content:update', (e) =>
@reset_title = yes
if @data.length
@$container
.closest('div')
.addClass 'loading'
@renderAll @data
$('.adjustable .cells').resizable handles: 'e'
$('.namecard').namecard()
@$container
.closest('div').removeClass 'loading'
else
$(UrlPath).trigger 'forceupdate'
renderAll: (list) ->
# Cache the data
@data = list
@col_list = $.cookie(COL_COOKIE_KEY + cols_target).split ','
@$container.empty()
@$container.append(@renderOne data, seq) for data, seq in list
if @is_user_define_col and @col_list.length and @reset_title
@$title_container.html @renderDefineTitle(@col_list, $('#accordion-company-contacts-title th'))
@$title_container.trigger 'refresh_sorting_symbol'
@reset_title = no
$('.currency').currency decimals: 0
$('#column-control').trigger 'force.active' if @col_list.length > 4
yes
renderOne: (data, seq) ->
if @is_user_define_col and @col_list.length
renderedContent = @renderDefineCols @col_list, data, seq
else
renderedContent = Mustache.render(@template, data)
return renderedContent
renderDefineTitle: (cols, $orgin_title) ->
row_content = ''
t_class = 'adjustable'
_.each cols, (key) ->
row_content += Mustache.render TITLE_COL,
value: COLUMN_LABEL[key]
id: COL_ORDER_BY_HASH[key]
key: key
t_class: t_class
c_class: unless COL_ORDER_BY_HASH[key] is '' then 'sortable' else 'unsortable'
Mustache.render TITLE_ROW, cols: row_content
renderDefineCols: (cols, data, seq) ->
return '' unless cols.length and data
row_content = []
col_raw = ''
_.each cols, (key, index)->
[parent, child] = _prepareKey key
col_val = ''
if parent of data
col_val = if child and child of data[parent] then data[parent][child] else data[parent]
col_val = _prepareColumn key, col_val, data
if index is 0 and cols_target is PPL
col_raw = Mustache.render COL_NAMECARD, value: col_val, data: data
else if index is 0 and cols_target is ORG
col_raw = Mustache.render COL_ORG_GROUP, value: col_val, data: data
else
col_raw = Mustache.render COL, value: col_val
col_raw = Mustache.render COL, value: col_val, special_class: 'nowrap' if _isNowrap(key)
row_content.push col_raw
return Mustache.render ROW, cols: row_content.join(''), id: data.id
sendRequest: (params, callback) ->
@$container
.closest('div')
.addClass 'loading'
_get @url, params, (result) =>
@renderAll result
$('.adjustable .cells').resizable handles: 'e'
callback?()
@$container
.closest('div').removeClass 'loading'
@$container.trigger 'refresh_filter', [params]
filterParams: (params) ->
params = _.pick params, @params_white_list
changeState: (params, callback) ->
params = @filterParams params
unless params['page']? then UrlPath.remove('page')
_.each params, (value, key) ->
UrlPath.update key, value
do UrlPath.route
|
[
{
"context": "###\nCopyright 2016 Balena\n\nLicensed under the Apache License, Version 2.0 (",
"end": 25,
"score": 0.9938544034957886,
"start": 19,
"tag": "NAME",
"value": "Balena"
},
{
"context": " = (options) ->\n\n\t_.defaults options,\n\t\tnetmask: '255.255.255.0'\n\n\tconfig = '... | lib/settings.coffee | balena-io-modules/resin-device-config | 2 | ###
Copyright 2016 Balena
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
_ = require('lodash')
###*
# @summary Main network settings
# @constant
# @protected
# @type {String}
###
exports.main = '''
[global]
OfflineMode=false
TimeUpdates=manual
[WiFi]
Enable=true
Tethering=false
[Wired]
Enable=true
Tethering=false
[Bluetooth]
Enable=true
Tethering=false
'''
###*
# @summary Get ethernet/wifi network settings
# @function
# @protected
#
# @param {Object} options - options
# @param {String} [options.wifiSsid] - wifi ssid
# @param {String} [options.wifiKey] - wifi key
# @param {Boolean} [options.staticIp] - whether to use a static ip
# @param {String} [options.ip] - static ip address
# @param {String} [options.netmask] - static ip netmask
# @param {String} [options.gateway] - static ip gateway
#
# @returns {String} Network configuration.
#
# @example
# networkSettings = settings.getHomeSettings
# wifiSsid: 'foobar'
# wifiKey: 'hello'
###
exports.getHomeSettings = (options) ->
_.defaults options,
netmask: '255.255.255.0'
config = '''
[service_home_ethernet]
Type = ethernet
Nameservers = 8.8.8.8,8.8.4.4
'''
if options.ip?
if not options.gateway?
throw new Error('Missing network gateway')
staticIpConfiguration = "\nIPv4 = #{options.ip}/#{options.netmask}/#{options.gateway}"
config += staticIpConfiguration
if not _.isEmpty(options.wifiSsid?.trim())
config += """\n
[service_home_wifi]
Hidden = true
Type = wifi
Name = #{options.wifiSsid}
"""
if options.wifiKey
config += "\nPassphrase = #{options.wifiKey}"
config += '\nNameservers = 8.8.8.8,8.8.4.4'
if staticIpConfiguration?
config += staticIpConfiguration
return config
| 124488 | ###
Copyright 2016 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
_ = require('lodash')
###*
# @summary Main network settings
# @constant
# @protected
# @type {String}
###
exports.main = '''
[global]
OfflineMode=false
TimeUpdates=manual
[WiFi]
Enable=true
Tethering=false
[Wired]
Enable=true
Tethering=false
[Bluetooth]
Enable=true
Tethering=false
'''
###*
# @summary Get ethernet/wifi network settings
# @function
# @protected
#
# @param {Object} options - options
# @param {String} [options.wifiSsid] - wifi ssid
# @param {String} [options.wifiKey] - wifi key
# @param {Boolean} [options.staticIp] - whether to use a static ip
# @param {String} [options.ip] - static ip address
# @param {String} [options.netmask] - static ip netmask
# @param {String} [options.gateway] - static ip gateway
#
# @returns {String} Network configuration.
#
# @example
# networkSettings = settings.getHomeSettings
# wifiSsid: 'foobar'
# wifiKey: 'hello'
###
exports.getHomeSettings = (options) ->
_.defaults options,
netmask: '255.255.255.0'
config = '''
[service_home_ethernet]
Type = ethernet
Nameservers = 8.8.8.8,8.8.4.4
'''
if options.ip?
if not options.gateway?
throw new Error('Missing network gateway')
staticIpConfiguration = "\nIPv4 = #{options.ip}/#{options.netmask}/#{options.gateway}"
config += staticIpConfiguration
if not _.isEmpty(options.wifiSsid?.trim())
config += """\n
[service_home_wifi]
Hidden = true
Type = wifi
Name = #{options.wifiSsid}
"""
if options.wifiKey
config += "\nPassphrase = #{options.wifiKey}"
config += '\nNameservers = 8.8.8.8,8.8.4.4'
if staticIpConfiguration?
config += staticIpConfiguration
return config
| true | ###
Copyright 2016 PI:NAME:<NAME>END_PI
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
_ = require('lodash')
###*
# @summary Main network settings
# @constant
# @protected
# @type {String}
###
exports.main = '''
[global]
OfflineMode=false
TimeUpdates=manual
[WiFi]
Enable=true
Tethering=false
[Wired]
Enable=true
Tethering=false
[Bluetooth]
Enable=true
Tethering=false
'''
###*
# @summary Get ethernet/wifi network settings
# @function
# @protected
#
# @param {Object} options - options
# @param {String} [options.wifiSsid] - wifi ssid
# @param {String} [options.wifiKey] - wifi key
# @param {Boolean} [options.staticIp] - whether to use a static ip
# @param {String} [options.ip] - static ip address
# @param {String} [options.netmask] - static ip netmask
# @param {String} [options.gateway] - static ip gateway
#
# @returns {String} Network configuration.
#
# @example
# networkSettings = settings.getHomeSettings
# wifiSsid: 'foobar'
# wifiKey: 'hello'
###
exports.getHomeSettings = (options) ->
_.defaults options,
netmask: '255.255.255.0'
config = '''
[service_home_ethernet]
Type = ethernet
Nameservers = 8.8.8.8,8.8.4.4
'''
if options.ip?
if not options.gateway?
throw new Error('Missing network gateway')
staticIpConfiguration = "\nIPv4 = #{options.ip}/#{options.netmask}/#{options.gateway}"
config += staticIpConfiguration
if not _.isEmpty(options.wifiSsid?.trim())
config += """\n
[service_home_wifi]
Hidden = true
Type = wifi
Name = #{options.wifiSsid}
"""
if options.wifiKey
config += "\nPassphrase = #{options.wifiKey}"
config += '\nNameservers = 8.8.8.8,8.8.4.4'
if staticIpConfiguration?
config += staticIpConfiguration
return config
|
[
{
"context": "ata: \"fullName()\", title: \"Name\"}\n {data: \"firstName\", title: \"First Name\"}\n {data: \"lastName\",",
"end": 1160,
"score": 0.9973204731941223,
"start": 1151,
"tag": "NAME",
"value": "firstName"
},
{
"context": "itle: \"Name\"}\n {data: \"fi... | common/tabulartables.coffee | drobbins/kassebaum | 0 | TabularTables = {}
if Meteor.isClient then Template.registerHelper "TabularTables", TabularTables
TabularTables.LogEntries = new Tabular.Table
name: "LogEntries"
collection: Logs.collection
columns: [
{data: "timestamp", title: "Time", render: (val) -> moment(val).format(Session.get("momentLogDateFormat")) }
{data: "level", title: "Level" }
{data: "data.user.username", title: "User" }
{data: "message", title: "Message" }
]
extraFields: ['data']
order: [[0, 'desc']]
TabularTables.Patients = new Tabular.Table
name: "Patients"
collection: Patients
responsive: true
autoWidth: false
columns: [
{
tmpl: Meteor.isClient && Template.patientListSelector
className: "text-center"
width: "1px" # actual width will be greater - this just minimizes it
}
# {data: "added", title: "Added", render: (val) -> moment(val).format(Session.get("momentDateFormat")) }
{data: "shortId", title: "Short ID", width: "100px"}
{data: "mrn", title: "MRN"}
# {data: "fullName()", title: "Name"}
{data: "firstName", title: "First Name"}
{data: "lastName", title: "Last Name"}
{
tmpl: Meteor.isClient && Template.instanceOfProcurementDates
title: "Procurement Dates"
}
{
tmpl: Meteor.isClient && Template.patientRowButtons
className: "text-center"
}
]
extraFields: ['instancesOfProcurement', 'firstName', 'lastName', 'deleted']
order: [[1, 'desc']]
TabularTables.APITokens = new Tabular.Table
name: "APITokens"
collection: apiTokens
columns: [
{data: "added", title: "Date Added", render: (val) -> moment(val).format(Session.get("momentLogDateFormat")) }
{data: "system", title: "System"}
{data: "token", title: "Token"}
{data: "revoked", title: "Revoked?"}
{
tmpl: Meteor.isClient && Template.apiTokenRowButtons
className: "text-center"
}
]
| 39025 | TabularTables = {}
if Meteor.isClient then Template.registerHelper "TabularTables", TabularTables
TabularTables.LogEntries = new Tabular.Table
name: "LogEntries"
collection: Logs.collection
columns: [
{data: "timestamp", title: "Time", render: (val) -> moment(val).format(Session.get("momentLogDateFormat")) }
{data: "level", title: "Level" }
{data: "data.user.username", title: "User" }
{data: "message", title: "Message" }
]
extraFields: ['data']
order: [[0, 'desc']]
TabularTables.Patients = new Tabular.Table
name: "Patients"
collection: Patients
responsive: true
autoWidth: false
columns: [
{
tmpl: Meteor.isClient && Template.patientListSelector
className: "text-center"
width: "1px" # actual width will be greater - this just minimizes it
}
# {data: "added", title: "Added", render: (val) -> moment(val).format(Session.get("momentDateFormat")) }
{data: "shortId", title: "Short ID", width: "100px"}
{data: "mrn", title: "MRN"}
# {data: "fullName()", title: "Name"}
{data: "<NAME>", title: "<NAME>"}
{data: "<NAME>", title: "<NAME>"}
{
tmpl: Meteor.isClient && Template.instanceOfProcurementDates
title: "Procurement Dates"
}
{
tmpl: Meteor.isClient && Template.patientRowButtons
className: "text-center"
}
]
extraFields: ['instancesOfProcurement', '<NAME>', '<NAME>', 'deleted']
order: [[1, 'desc']]
TabularTables.APITokens = new Tabular.Table
name: "APITokens"
collection: apiTokens
columns: [
{data: "added", title: "Date Added", render: (val) -> moment(val).format(Session.get("momentLogDateFormat")) }
{data: "system", title: "System"}
{data: "token", title: "Token"}
{data: "revoked", title: "Revoked?"}
{
tmpl: Meteor.isClient && Template.apiTokenRowButtons
className: "text-center"
}
]
| true | TabularTables = {}
if Meteor.isClient then Template.registerHelper "TabularTables", TabularTables
TabularTables.LogEntries = new Tabular.Table
name: "LogEntries"
collection: Logs.collection
columns: [
{data: "timestamp", title: "Time", render: (val) -> moment(val).format(Session.get("momentLogDateFormat")) }
{data: "level", title: "Level" }
{data: "data.user.username", title: "User" }
{data: "message", title: "Message" }
]
extraFields: ['data']
order: [[0, 'desc']]
TabularTables.Patients = new Tabular.Table
name: "Patients"
collection: Patients
responsive: true
autoWidth: false
columns: [
{
tmpl: Meteor.isClient && Template.patientListSelector
className: "text-center"
width: "1px" # actual width will be greater - this just minimizes it
}
# {data: "added", title: "Added", render: (val) -> moment(val).format(Session.get("momentDateFormat")) }
{data: "shortId", title: "Short ID", width: "100px"}
{data: "mrn", title: "MRN"}
# {data: "fullName()", title: "Name"}
{data: "PI:NAME:<NAME>END_PI", title: "PI:NAME:<NAME>END_PI"}
{data: "PI:NAME:<NAME>END_PI", title: "PI:NAME:<NAME>END_PI"}
{
tmpl: Meteor.isClient && Template.instanceOfProcurementDates
title: "Procurement Dates"
}
{
tmpl: Meteor.isClient && Template.patientRowButtons
className: "text-center"
}
]
extraFields: ['instancesOfProcurement', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'deleted']
order: [[1, 'desc']]
TabularTables.APITokens = new Tabular.Table
name: "APITokens"
collection: apiTokens
columns: [
{data: "added", title: "Date Added", render: (val) -> moment(val).format(Session.get("momentLogDateFormat")) }
{data: "system", title: "System"}
{data: "token", title: "Token"}
{data: "revoked", title: "Revoked?"}
{
tmpl: Meteor.isClient && Template.apiTokenRowButtons
className: "text-center"
}
]
|
[
{
"context": " = @sut.getFromAnywhere headers: {authorization: 'Bearer Z3JlZW5pc2gteWVsbG93OmJsdWUtYS1sb3QK'}\n\n it ",
"end": 327,
"score": 0.7055783271789551,
"start": 321,
"tag": "KEY",
"value": "Bearer"
},
{
"context": "t.getFromAnywhere headers: {authorization: 'Bearer Z3Jl... | node_modules/express-meshblu-auth/test/meshblu-auth-express-spec.coffee | ratokeshi/endo-google-cloud-platform | 0 | MeshbluAuthExpress = require '../src/meshblu-auth-express'
describe 'MeshbluAuthExpress', ->
describe '->getFromAnywhere', ->
beforeEach ->
@sut = new MeshbluAuthExpress
describe '2nd to worst case (bearer token)', ->
beforeEach ->
@result = @sut.getFromAnywhere headers: {authorization: 'Bearer Z3JlZW5pc2gteWVsbG93OmJsdWUtYS1sb3QK'}
it 'should return the auth', ->
expect(@result).to.deep.equal uuid: 'greenish-yellow', token: 'blue-a-lot'
describe 'worst case (invalid bearer token)', ->
beforeEach ->
@result = @sut.getFromAnywhere headers: {authorization: 'Bearer zpwaW5raXNoLBAD'}
it 'should return null', ->
expect(@result).to.be.null
describe '->getFromBearerToken', ->
beforeEach ->
@sut = new MeshbluAuthExpress
describe 'with a valid bearer token', ->
beforeEach ->
@result = @sut.getFromBearerToken headers: {authorization: 'Bearer Z3JlZW5pc2gteWVsbG93OmJsdWUtYS1sb3QK'}
it 'should return the auth', ->
expect(@result).to.deep.equal uuid: 'greenish-yellow', token: 'blue-a-lot'
describe 'with a different valid bearer token', ->
beforeEach ->
@result = @sut.getFromBearerToken headers: {authorization: 'Bearer c3VwZXItcGluazpwaW5raXNoLXB1cnBsZWlzaAo='}
it 'should return the auth', ->
expect(@result).to.deep.equal uuid: 'super-pink', token: 'pinkish-purpleish'
describe 'with an invalid bearer token', ->
beforeEach ->
@result = @sut.getFromBearerToken headers: {authorization: 'Bearer zpwaW5raXNoLBAD'}
it 'should return null', ->
expect(@result).to.be.null
describe 'with an invalid header', ->
beforeEach ->
@result = @sut.getFromBearerToken {}
it 'should return null', ->
expect(@result).to.be.null
describe 'with a different authorization scheme', ->
beforeEach ->
@result = @sut.getFromBearerToken headers: {authorization: 'Basic'}
it 'should return null', ->
expect(@result).to.not.exist
describe '->getFromBasicAuth', ->
beforeEach ->
@sut = new MeshbluAuthExpress
describe 'with a valid basic auth', ->
beforeEach ->
@result = @sut.getFromBasicAuth headers: {authorization: 'Basic Z3JlZW5pc2gteWVsbG93OmJsdWUtYS1sb3QK'}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'greenish-yellow', token: 'blue-a-lot'
describe 'with a different valid basic auth', ->
beforeEach ->
@result = @sut.getFromBasicAuth headers: {authorization: 'Basic c3VwZXItcGluazpwaW5raXNoLXB1cnBsZWlzaAo='}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'super-pink', token: 'pinkish-purpleish'
describe 'with a invalid basic auth', ->
beforeEach ->
@result = @sut.getFromBasicAuth headers: {authorization: 'Basic zpwaW5raXNoLBAD'}
it 'should return null', ->
expect(@result).to.be.null
describe 'with a invalid header', ->
beforeEach ->
@result = @sut.getFromBasicAuth {}
it 'should return null', ->
expect(@result).to.be.null
describe 'with a different authorization scheme', ->
beforeEach ->
@result = @sut.getFromBasicAuth headers: {authorization: 'Bearer c3VwZXItcGluazpwaW5raXNoLXB1cnBsZWlzaAo='}
it 'should return null', ->
expect(@result).to.be.null
describe '->getFromCookies', ->
beforeEach ->
@sut = new MeshbluAuthExpress
describe 'with a valid cookie', ->
beforeEach ->
@result = @sut.getFromCookies {
cookies:
meshblu_auth_uuid: 'greenish-yellow'
meshblu_auth_token: 'blue-a-lot'
}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'greenish-yellow', token: 'blue-a-lot'
describe 'with a valid bearer cookie', ->
beforeEach ->
bearer = Buffer('i-can-barely-stand:erik', 'utf8').toString('base64')
@result = @sut.getFromCookies cookies: {meshblu_auth_bearer: bearer}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'i-can-barely-stand', token: 'erik'
describe 'with a different valid cookie', ->
beforeEach ->
@result = @sut.getFromCookies {
cookies:
meshblu_auth_uuid: 'super-pink'
meshblu_auth_token: 'pinkish-purpleish'
}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'super-pink', token: 'pinkish-purpleish'
describe 'with invalid cookies', ->
beforeEach ->
@result = @sut.getFromCookies cookies: {}
it 'should return null', ->
expect(@result).to.be.null
describe 'with a invalid header', ->
beforeEach ->
@result = @sut.getFromCookies {}
it 'should return null', ->
expect(@result).to.be.null
describe '->getFromSkynetHeaders', ->
beforeEach ->
@sut = new MeshbluAuthExpress
describe 'with a valid auth', ->
beforeEach ->
@result = @sut.getFromXMeshbluHeaders {
headers:
'X-Meshblu-UUID': 'greenish-yellow'
'X-Meshblu-Token': 'blue-a-lot'
}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'greenish-yellow', token: 'blue-a-lot'
describe 'with a crazy case', ->
beforeEach ->
@result = @sut.getFromXMeshbluHeaders {
headers:
'x-meshBLU-uuID': 'greenish-yellow'
'X-meshblu-token': 'blue-a-lot'
}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'greenish-yellow', token: 'blue-a-lot'
describe '->getFromSkynetHeaders', ->
beforeEach ->
@sut = new MeshbluAuthExpress
describe 'with a valid auth', ->
beforeEach ->
@result = @sut.getFromSkynetHeaders {
headers:
skynet_auth_uuid: 'greenish-yellow'
skynet_auth_token: 'blue-a-lot'
}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'greenish-yellow', token: 'blue-a-lot'
describe '->getFromHeaders', ->
beforeEach ->
@sut = new MeshbluAuthExpress
describe 'with a valid basic auth', ->
beforeEach ->
@result = @sut.getFromHeaders {
headers:
meshblu_auth_uuid: 'greenish-yellow'
meshblu_auth_token: 'blue-a-lot'
}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'greenish-yellow', token: 'blue-a-lot'
describe 'with a different valid bearer token', ->
beforeEach ->
@result = @sut.getFromHeaders {
headers:
meshblu_auth_uuid: 'super-pink'
meshblu_auth_token: 'pinkish-purpleish'
}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'super-pink', token: 'pinkish-purpleish'
describe 'with invalid headers', ->
beforeEach ->
@result = @sut.getFromHeaders headers: {}
it 'should return null', ->
expect(@result).to.be.null
describe 'with a invalid header', ->
beforeEach ->
@result = @sut.getFromHeaders {}
it 'should set meshbluAuth on the request', ->
expect(@result).to.be.null
describe 'when instantiated with meshblu configuration', ->
beforeEach ->
@meshbluHttp =
authenticate: sinon.stub()
@MeshbluHttp = sinon.spy => @meshbluHttp
dependencies = MeshbluHttp: @MeshbluHttp
options =
server: 'yellow-mellow'
port: 'greeeeeeennn'
@sut = new MeshbluAuthExpress options, dependencies
describe 'when called with uuid and token', ->
beforeEach ->
@sut.authDeviceWithMeshblu 'blackened', 'bluened', (@error, @result) =>
it 'should be instantiated', ->
expect(@MeshbluHttp).to.be.calledWithNew
it 'should be instantiated with the correct options', ->
expect(@MeshbluHttp).to.be.calledWith {
server: 'yellow-mellow'
port: 'greeeeeeennn'
uuid: 'blackened'
token: 'bluened'
}
it 'should call meshbluHttp.device with correct url and options', ->
expect(@meshbluHttp.authenticate).to.have.been.called
describe 'when MeshbluHttp yields a device', ->
beforeEach ->
@meshbluHttp.authenticate.yield null, {uuid: 'blackened', foo: 'bar'}
it 'should yields without an error', ->
expect(@error).not.to.exist
it 'should yield the credentials, bearerToken, server info', ->
expect(@result).to.deep.equal {
server: 'yellow-mellow'
port: 'greeeeeeennn'
uuid: 'blackened'
token: 'bluened'
bearerToken: new Buffer('blackened:bluened').toString 'base64'
}
describe 'when MeshbluHttp yields an error with no code', ->
beforeEach ->
@meshbluHttp.authenticate.yield new Error('Generic Error')
it 'should yields with an error', ->
expect(=> throw @error).to.throw 'Generic Error'
describe 'when MeshbluHttp yields an error with a 401', ->
beforeEach ->
error = new Error('Unauthorized')
error.code = 401
@meshbluHttp.authenticate.yield error
it 'should yield nulls', ->
expect(@error).to.be.null
expect(@result).to.be.null
describe 'when MeshbluHttp yields an error with a 500', ->
beforeEach ->
error = new Error('Internal Server Error')
error.code = 500
@meshbluHttp.authenticate.yield error
it 'should yields with an error', ->
expect(=> throw @error).to.throw 'Internal Server Error'
| 189434 | MeshbluAuthExpress = require '../src/meshblu-auth-express'
describe 'MeshbluAuthExpress', ->
describe '->getFromAnywhere', ->
beforeEach ->
@sut = new MeshbluAuthExpress
describe '2nd to worst case (bearer token)', ->
beforeEach ->
@result = @sut.getFromAnywhere headers: {authorization: '<KEY> <KEY>'}
it 'should return the auth', ->
expect(@result).to.deep.equal uuid: 'greenish-yellow', token: '<PASSWORD>'
describe 'worst case (invalid bearer token)', ->
beforeEach ->
@result = @sut.getFromAnywhere headers: {authorization: 'Bearer zpwaW5raXNoLBAD'}
it 'should return null', ->
expect(@result).to.be.null
describe '->getFromBearerToken', ->
beforeEach ->
@sut = new MeshbluAuthExpress
describe 'with a valid bearer token', ->
beforeEach ->
@result = @sut.getFromBearerToken headers: {authorization: '<KEY> <KEY>'}
it 'should return the auth', ->
expect(@result).to.deep.equal uuid: 'greenish-yellow', token: '<PASSWORD>'
describe 'with a different valid bearer token', ->
beforeEach ->
@result = @sut.getFromBearerToken headers: {authorization: 'Bearer c<KEY>}
it 'should return the auth', ->
expect(@result).to.deep.equal uuid: 'super-pink', token: '<PASSWORD>'
describe 'with an invalid bearer token', ->
beforeEach ->
@result = @sut.getFromBearerToken headers: {authorization: 'Bearer zpwaW5raXNoLBAD'}
it 'should return null', ->
expect(@result).to.be.null
describe 'with an invalid header', ->
beforeEach ->
@result = @sut.getFromBearerToken {}
it 'should return null', ->
expect(@result).to.be.null
describe 'with a different authorization scheme', ->
beforeEach ->
@result = @sut.getFromBearerToken headers: {authorization: 'Basic'}
it 'should return null', ->
expect(@result).to.not.exist
describe '->getFromBasicAuth', ->
beforeEach ->
@sut = new MeshbluAuthExpress
describe 'with a valid basic auth', ->
beforeEach ->
@result = @sut.getFromBasicAuth headers: {authorization: 'Basic Z3JlZW5pc2gteWVsbG93OmJsdWUtYS1sb3QK'}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'greenish-yellow', token: '<PASSWORD>'
describe 'with a different valid basic auth', ->
beforeEach ->
@result = @sut.getFromBasicAuth headers: {authorization: 'Basic c<KEY>='}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'super-pink', token: '<PASSWORD>'
describe 'with a invalid basic auth', ->
beforeEach ->
@result = @sut.getFromBasicAuth headers: {authorization: 'Basic zpwaW5raXNoLBAD'}
it 'should return null', ->
expect(@result).to.be.null
describe 'with a invalid header', ->
beforeEach ->
@result = @sut.getFromBasicAuth {}
it 'should return null', ->
expect(@result).to.be.null
describe 'with a different authorization scheme', ->
beforeEach ->
@result = @sut.getFromBasicAuth headers: {authorization: 'Bearer <KEY>}
it 'should return null', ->
expect(@result).to.be.null
describe '->getFromCookies', ->
beforeEach ->
@sut = new MeshbluAuthExpress
describe 'with a valid cookie', ->
beforeEach ->
@result = @sut.getFromCookies {
cookies:
meshblu_auth_uuid: 'greenish-yellow'
meshblu_auth_token: '<PASSWORD>'
}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'greenish-yellow', token: '<PASSWORD>'
describe 'with a valid bearer cookie', ->
beforeEach ->
bearer = Buffer('i-can-barely-stand:erik', 'utf8').toString('base64')
@result = @sut.getFromCookies cookies: {meshblu_auth_bearer: bearer}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'i-can-barely-stand', token: '<PASSWORD>'
describe 'with a different valid cookie', ->
beforeEach ->
@result = @sut.getFromCookies {
cookies:
meshblu_auth_uuid: 'super-pink'
meshblu_auth_token: '<PASSWORD>'
}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'super-pink', token: '<PASSWORD>'
describe 'with invalid cookies', ->
beforeEach ->
@result = @sut.getFromCookies cookies: {}
it 'should return null', ->
expect(@result).to.be.null
describe 'with a invalid header', ->
beforeEach ->
@result = @sut.getFromCookies {}
it 'should return null', ->
expect(@result).to.be.null
describe '->getFromSkynetHeaders', ->
beforeEach ->
@sut = new MeshbluAuthExpress
describe 'with a valid auth', ->
beforeEach ->
@result = @sut.getFromXMeshbluHeaders {
headers:
'X-Meshblu-UUID': 'greenish-yellow'
'X-Meshblu-Token': '<PASSWORD>'
}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'greenish-yellow', token: '<PASSWORD>'
describe 'with a crazy case', ->
beforeEach ->
@result = @sut.getFromXMeshbluHeaders {
headers:
'x-meshBLU-uuID': 'green<PASSWORD>-yellow'
'X-meshblu-token': '<PASSWORD>'
}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'greenish-yellow', token: '<PASSWORD>'
describe '->getFromSkynetHeaders', ->
beforeEach ->
@sut = new MeshbluAuthExpress
describe 'with a valid auth', ->
beforeEach ->
@result = @sut.getFromSkynetHeaders {
headers:
skynet_auth_uuid: 'greenish-yellow'
skynet_auth_token: '<PASSWORD>'
}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'greenish-yellow', token: '<PASSWORD>'
describe '->getFromHeaders', ->
beforeEach ->
@sut = new MeshbluAuthExpress
describe 'with a valid basic auth', ->
beforeEach ->
@result = @sut.getFromHeaders {
headers:
meshblu_auth_uuid: 'greenish-yellow'
meshblu_auth_token: '<PASSWORD>'
}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'greenish-yellow', token: '<PASSWORD>'
describe 'with a different valid bearer token', ->
beforeEach ->
@result = @sut.getFromHeaders {
headers:
meshblu_auth_uuid: 'super-pink'
meshblu_auth_token: '<PASSWORD>'
}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'super-pink', token: '<PASSWORD>'
describe 'with invalid headers', ->
beforeEach ->
@result = @sut.getFromHeaders headers: {}
it 'should return null', ->
expect(@result).to.be.null
describe 'with a invalid header', ->
beforeEach ->
@result = @sut.getFromHeaders {}
it 'should set meshbluAuth on the request', ->
expect(@result).to.be.null
describe 'when instantiated with meshblu configuration', ->
beforeEach ->
@meshbluHttp =
authenticate: sinon.stub()
@MeshbluHttp = sinon.spy => @meshbluHttp
dependencies = MeshbluHttp: @MeshbluHttp
options =
server: 'yellow-mellow'
port: 'greeeeeeennn'
@sut = new MeshbluAuthExpress options, dependencies
describe 'when called with uuid and token', ->
beforeEach ->
@sut.authDeviceWithMeshblu 'blackened', 'bluened', (@error, @result) =>
it 'should be instantiated', ->
expect(@MeshbluHttp).to.be.calledWithNew
it 'should be instantiated with the correct options', ->
expect(@MeshbluHttp).to.be.calledWith {
server: 'yellow-mellow'
port: 'greeeeeeennn'
uuid: 'blackened'
token: '<PASSWORD>'
}
it 'should call meshbluHttp.device with correct url and options', ->
expect(@meshbluHttp.authenticate).to.have.been.called
describe 'when MeshbluHttp yields a device', ->
beforeEach ->
@meshbluHttp.authenticate.yield null, {uuid: 'blackened', foo: 'bar'}
it 'should yields without an error', ->
expect(@error).not.to.exist
it 'should yield the credentials, bearerToken, server info', ->
expect(@result).to.deep.equal {
server: 'yellow-mellow'
port: 'greeeeeeennn'
uuid: 'blackened'
token: '<PASSWORD>'
bearerToken: new Buffer('<PASSWORD>').toString 'base6<KEY>'
}
describe 'when MeshbluHttp yields an error with no code', ->
beforeEach ->
@meshbluHttp.authenticate.yield new Error('Generic Error')
it 'should yields with an error', ->
expect(=> throw @error).to.throw 'Generic Error'
describe 'when MeshbluHttp yields an error with a 401', ->
beforeEach ->
error = new Error('Unauthorized')
error.code = 401
@meshbluHttp.authenticate.yield error
it 'should yield nulls', ->
expect(@error).to.be.null
expect(@result).to.be.null
describe 'when MeshbluHttp yields an error with a 500', ->
beforeEach ->
error = new Error('Internal Server Error')
error.code = 500
@meshbluHttp.authenticate.yield error
it 'should yields with an error', ->
expect(=> throw @error).to.throw 'Internal Server Error'
| true | MeshbluAuthExpress = require '../src/meshblu-auth-express'
describe 'MeshbluAuthExpress', ->
describe '->getFromAnywhere', ->
beforeEach ->
@sut = new MeshbluAuthExpress
describe '2nd to worst case (bearer token)', ->
beforeEach ->
@result = @sut.getFromAnywhere headers: {authorization: 'PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI'}
it 'should return the auth', ->
expect(@result).to.deep.equal uuid: 'greenish-yellow', token: 'PI:PASSWORD:<PASSWORD>END_PI'
describe 'worst case (invalid bearer token)', ->
beforeEach ->
@result = @sut.getFromAnywhere headers: {authorization: 'Bearer zpwaW5raXNoLBAD'}
it 'should return null', ->
expect(@result).to.be.null
describe '->getFromBearerToken', ->
beforeEach ->
@sut = new MeshbluAuthExpress
describe 'with a valid bearer token', ->
beforeEach ->
@result = @sut.getFromBearerToken headers: {authorization: 'PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI'}
it 'should return the auth', ->
expect(@result).to.deep.equal uuid: 'greenish-yellow', token: 'PI:PASSWORD:<PASSWORD>END_PI'
describe 'with a different valid bearer token', ->
beforeEach ->
@result = @sut.getFromBearerToken headers: {authorization: 'Bearer cPI:KEY:<KEY>END_PI}
it 'should return the auth', ->
expect(@result).to.deep.equal uuid: 'super-pink', token: 'PI:PASSWORD:<PASSWORD>END_PI'
describe 'with an invalid bearer token', ->
beforeEach ->
@result = @sut.getFromBearerToken headers: {authorization: 'Bearer zpwaW5raXNoLBAD'}
it 'should return null', ->
expect(@result).to.be.null
describe 'with an invalid header', ->
beforeEach ->
@result = @sut.getFromBearerToken {}
it 'should return null', ->
expect(@result).to.be.null
describe 'with a different authorization scheme', ->
beforeEach ->
@result = @sut.getFromBearerToken headers: {authorization: 'Basic'}
it 'should return null', ->
expect(@result).to.not.exist
describe '->getFromBasicAuth', ->
beforeEach ->
@sut = new MeshbluAuthExpress
describe 'with a valid basic auth', ->
beforeEach ->
@result = @sut.getFromBasicAuth headers: {authorization: 'Basic Z3JlZW5pc2gteWVsbG93OmJsdWUtYS1sb3QK'}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'greenish-yellow', token: 'PI:PASSWORD:<PASSWORD>END_PI'
describe 'with a different valid basic auth', ->
beforeEach ->
@result = @sut.getFromBasicAuth headers: {authorization: 'Basic cPI:KEY:<KEY>END_PI='}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'super-pink', token: 'PI:PASSWORD:<PASSWORD>END_PI'
describe 'with a invalid basic auth', ->
beforeEach ->
@result = @sut.getFromBasicAuth headers: {authorization: 'Basic zpwaW5raXNoLBAD'}
it 'should return null', ->
expect(@result).to.be.null
describe 'with a invalid header', ->
beforeEach ->
@result = @sut.getFromBasicAuth {}
it 'should return null', ->
expect(@result).to.be.null
describe 'with a different authorization scheme', ->
beforeEach ->
@result = @sut.getFromBasicAuth headers: {authorization: 'Bearer PI:KEY:<KEY>END_PI}
it 'should return null', ->
expect(@result).to.be.null
describe '->getFromCookies', ->
beforeEach ->
@sut = new MeshbluAuthExpress
describe 'with a valid cookie', ->
beforeEach ->
@result = @sut.getFromCookies {
cookies:
meshblu_auth_uuid: 'greenish-yellow'
meshblu_auth_token: 'PI:PASSWORD:<PASSWORD>END_PI'
}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'greenish-yellow', token: 'PI:PASSWORD:<PASSWORD>END_PI'
describe 'with a valid bearer cookie', ->
beforeEach ->
bearer = Buffer('i-can-barely-stand:erik', 'utf8').toString('base64')
@result = @sut.getFromCookies cookies: {meshblu_auth_bearer: bearer}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'i-can-barely-stand', token: 'PI:PASSWORD:<PASSWORD>END_PI'
describe 'with a different valid cookie', ->
beforeEach ->
@result = @sut.getFromCookies {
cookies:
meshblu_auth_uuid: 'super-pink'
meshblu_auth_token: 'PI:PASSWORD:<PASSWORD>END_PI'
}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'super-pink', token: 'PI:PASSWORD:<PASSWORD>END_PI'
describe 'with invalid cookies', ->
beforeEach ->
@result = @sut.getFromCookies cookies: {}
it 'should return null', ->
expect(@result).to.be.null
describe 'with a invalid header', ->
beforeEach ->
@result = @sut.getFromCookies {}
it 'should return null', ->
expect(@result).to.be.null
describe '->getFromSkynetHeaders', ->
beforeEach ->
@sut = new MeshbluAuthExpress
describe 'with a valid auth', ->
beforeEach ->
@result = @sut.getFromXMeshbluHeaders {
headers:
'X-Meshblu-UUID': 'greenish-yellow'
'X-Meshblu-Token': 'PI:PASSWORD:<PASSWORD>END_PI'
}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'greenish-yellow', token: 'PI:PASSWORD:<PASSWORD>END_PI'
describe 'with a crazy case', ->
beforeEach ->
@result = @sut.getFromXMeshbluHeaders {
headers:
'x-meshBLU-uuID': 'greenPI:PASSWORD:<PASSWORD>END_PI-yellow'
'X-meshblu-token': 'PI:PASSWORD:<PASSWORD>END_PI'
}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'greenish-yellow', token: 'PI:PASSWORD:<PASSWORD>END_PI'
describe '->getFromSkynetHeaders', ->
beforeEach ->
@sut = new MeshbluAuthExpress
describe 'with a valid auth', ->
beforeEach ->
@result = @sut.getFromSkynetHeaders {
headers:
skynet_auth_uuid: 'greenish-yellow'
skynet_auth_token: 'PI:PASSWORD:<PASSWORD>END_PI'
}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'greenish-yellow', token: 'PI:PASSWORD:<PASSWORD>END_PI'
describe '->getFromHeaders', ->
beforeEach ->
@sut = new MeshbluAuthExpress
describe 'with a valid basic auth', ->
beforeEach ->
@result = @sut.getFromHeaders {
headers:
meshblu_auth_uuid: 'greenish-yellow'
meshblu_auth_token: 'PI:PASSWORD:<PASSWORD>END_PI'
}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'greenish-yellow', token: 'PI:PASSWORD:<PASSWORD>END_PI'
describe 'with a different valid bearer token', ->
beforeEach ->
@result = @sut.getFromHeaders {
headers:
meshblu_auth_uuid: 'super-pink'
meshblu_auth_token: 'PI:PASSWORD:<PASSWORD>END_PI'
}
it 'should return the uuid and token', ->
expect(@result).to.deep.equal uuid: 'super-pink', token: 'PI:PASSWORD:<PASSWORD>END_PI'
describe 'with invalid headers', ->
beforeEach ->
@result = @sut.getFromHeaders headers: {}
it 'should return null', ->
expect(@result).to.be.null
describe 'with a invalid header', ->
beforeEach ->
@result = @sut.getFromHeaders {}
it 'should set meshbluAuth on the request', ->
expect(@result).to.be.null
describe 'when instantiated with meshblu configuration', ->
beforeEach ->
@meshbluHttp =
authenticate: sinon.stub()
@MeshbluHttp = sinon.spy => @meshbluHttp
dependencies = MeshbluHttp: @MeshbluHttp
options =
server: 'yellow-mellow'
port: 'greeeeeeennn'
@sut = new MeshbluAuthExpress options, dependencies
describe 'when called with uuid and token', ->
beforeEach ->
@sut.authDeviceWithMeshblu 'blackened', 'bluened', (@error, @result) =>
it 'should be instantiated', ->
expect(@MeshbluHttp).to.be.calledWithNew
it 'should be instantiated with the correct options', ->
expect(@MeshbluHttp).to.be.calledWith {
server: 'yellow-mellow'
port: 'greeeeeeennn'
uuid: 'blackened'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
}
it 'should call meshbluHttp.device with correct url and options', ->
expect(@meshbluHttp.authenticate).to.have.been.called
describe 'when MeshbluHttp yields a device', ->
beforeEach ->
@meshbluHttp.authenticate.yield null, {uuid: 'blackened', foo: 'bar'}
it 'should yields without an error', ->
expect(@error).not.to.exist
it 'should yield the credentials, bearerToken, server info', ->
expect(@result).to.deep.equal {
server: 'yellow-mellow'
port: 'greeeeeeennn'
uuid: 'blackened'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
bearerToken: new Buffer('PI:PASSWORD:<PASSWORD>END_PI').toString 'base6PI:KEY:<KEY>END_PI'
}
describe 'when MeshbluHttp yields an error with no code', ->
beforeEach ->
@meshbluHttp.authenticate.yield new Error('Generic Error')
it 'should yields with an error', ->
expect(=> throw @error).to.throw 'Generic Error'
describe 'when MeshbluHttp yields an error with a 401', ->
beforeEach ->
error = new Error('Unauthorized')
error.code = 401
@meshbluHttp.authenticate.yield error
it 'should yield nulls', ->
expect(@error).to.be.null
expect(@result).to.be.null
describe 'when MeshbluHttp yields an error with a 500', ->
beforeEach ->
error = new Error('Internal Server Error')
error.code = 500
@meshbluHttp.authenticate.yield error
it 'should yields with an error', ->
expect(=> throw @error).to.throw 'Internal Server Error'
|
[
{
"context": "4, cost: 16000, duration: {days: 2}},\n {name: \"Dexterity IV\", level: 50, members: 4, cost: 25000, duration: {",
"end": 2958,
"score": 0.8737130165100098,
"start": 2946,
"tag": "NAME",
"value": "Dexterity IV"
},
{
"context": "000, duration: {days: 2, hours: 12}},\n... | src/character/guildBuffs/GuildDexterity.coffee | sadbear-/IdleLands | 0 |
GuildBuff = require "../base/GuildBuff"
`/**
* The Dexterity I guild buff increases Dexterity.
*
* @name Dexterity I
* @requirement {gold} 4000
* @requirement {guild level} 20
* @requirement {guild members} 1
* @effect +5% DEX
* @duration 1 day
* @category Dexterity
* @package GuildBuffs
*/`
`/**
* The Dexterity II guild buff increases Dexterity.
*
* @name Dexterity II
* @requirement {gold} 9000
* @requirement {guild level} 30
* @requirement {guild members} 1
* @effect +10% DEX
* @duration 1 day, 12 hours
* @category Dexterity
* @package GuildBuffs
*/`
`/**
* The Dexterity III guild buff increases Dexterity.
*
* @name Dexterity III
* @requirement {gold} 16000
* @requirement {guild level} 40
* @requirement {guild members} 4
* @effect +15% DEX
* @duration 2 days
* @category Dexterity
* @package GuildBuffs
*/`
`/**
* The Dexterity IV guild buff increases Dexterity.
*
* @name Dexterity IV
* @requirement {gold} 25000
* @requirement {guild level} 50
* @requirement {guild members} 4
* @effect +20% DEX
* @duration 2 days, 12 hours
* @category Dexterity
* @package GuildBuffs
*/`
`/**
* The Dexterity V guild buff increases Dexterity.
*
* @name Dexterity V
* @requirement {gold} 36000
* @requirement {guild level} 60
* @requirement {guild members} 9
* @effect +25% DEX
* @duration 3 days
* @category Dexterity
* @package GuildBuffs
*/`
`/**
* The Dexterity VI guild buff increases Dexterity.
*
* @name Dexterity VI
* @requirement {gold} 49000
* @requirement {guild level} 80
* @requirement {guild members} 9
* @effect +30% DEX
* @duration 3 days, 12 hours
* @category Dexterity
* @package GuildBuffs
*/`
`/**
* The Dexterity VII guild buff increases Dexterity.
*
* @name Dexterity VII
* @requirement {gold} 64000
* @requirement {guild level} 80
* @requirement {guild members} 15
* @effect +35% DEX
* @duration 4 days
* @category Dexterity
* @package GuildBuffs
*/`
`/**
* The Dexterity VIII guild buff increases Dexterity.
*
* @name Dexterity VIII
* @requirement {gold} 81000
* @requirement {guild level} 90
* @requirement {guild members} 15
* @effect +40% DEX
* @duration 4 days, 12 hours
* @category Dexterity
* @package GuildBuffs
*/`
`/**
* The Dexterity IX guild buff increases Dexterity.
*
* @name Dexterity IX
* @requirement {gold} 100000
* @requirement {guild level} 100
* @requirement {guild members} 20
* @effect +45% DEX
* @duration 5 days
* @category Dexterity
* @package GuildBuffs
*/`
class GuildDexterity extends GuildBuff
@tiers = GuildDexterity::tiers = [null,
{name: "Dexterity I", level: 20, members: 1, cost: 4000, duration: {days: 1}},
{name: "Dexterity II", level: 30, members: 1, cost: 9000, duration: {days: 1, hours: 12}},
{name: "Dexterity III", level: 40, members: 4, cost: 16000, duration: {days: 2}},
{name: "Dexterity IV", level: 50, members: 4, cost: 25000, duration: {days: 2, hours: 12}},
{name: "Dexterity V", level: 60, members: 9, cost: 36000, duration: {days: 3}},
{name: "Dexterity VI", level: 70, members: 9, cost: 49000, duration: {days: 3, hours: 12}},
{name: "Dexterity VII", level: 80, members: 15, cost: 64000, duration: {days: 4}},
{name: "Dexterity VIII", level: 90, members: 15, cost: 81000, duration: {days: 4, hours: 12}},
{name: "Dexterity IX", level: 100, members: 20, cost: 100000, duration: {days: 5}}
]
constructor: (@tier = 1) ->
@type = 'Dexterity'
super()
dexPercent: -> @tier*5
module.exports = exports = GuildDexterity | 147647 |
GuildBuff = require "../base/GuildBuff"
`/**
* The Dexterity I guild buff increases Dexterity.
*
* @name Dexterity I
* @requirement {gold} 4000
* @requirement {guild level} 20
* @requirement {guild members} 1
* @effect +5% DEX
* @duration 1 day
* @category Dexterity
* @package GuildBuffs
*/`
`/**
* The Dexterity II guild buff increases Dexterity.
*
* @name Dexterity II
* @requirement {gold} 9000
* @requirement {guild level} 30
* @requirement {guild members} 1
* @effect +10% DEX
* @duration 1 day, 12 hours
* @category Dexterity
* @package GuildBuffs
*/`
`/**
* The Dexterity III guild buff increases Dexterity.
*
* @name Dexterity III
* @requirement {gold} 16000
* @requirement {guild level} 40
* @requirement {guild members} 4
* @effect +15% DEX
* @duration 2 days
* @category Dexterity
* @package GuildBuffs
*/`
`/**
* The Dexterity IV guild buff increases Dexterity.
*
* @name Dexterity IV
* @requirement {gold} 25000
* @requirement {guild level} 50
* @requirement {guild members} 4
* @effect +20% DEX
* @duration 2 days, 12 hours
* @category Dexterity
* @package GuildBuffs
*/`
`/**
* The Dexterity V guild buff increases Dexterity.
*
* @name Dexterity V
* @requirement {gold} 36000
* @requirement {guild level} 60
* @requirement {guild members} 9
* @effect +25% DEX
* @duration 3 days
* @category Dexterity
* @package GuildBuffs
*/`
`/**
* The Dexterity VI guild buff increases Dexterity.
*
* @name Dexterity VI
* @requirement {gold} 49000
* @requirement {guild level} 80
* @requirement {guild members} 9
* @effect +30% DEX
* @duration 3 days, 12 hours
* @category Dexterity
* @package GuildBuffs
*/`
`/**
* The Dexterity VII guild buff increases Dexterity.
*
* @name Dexterity VII
* @requirement {gold} 64000
* @requirement {guild level} 80
* @requirement {guild members} 15
* @effect +35% DEX
* @duration 4 days
* @category Dexterity
* @package GuildBuffs
*/`
`/**
* The Dexterity VIII guild buff increases Dexterity.
*
* @name Dexterity VIII
* @requirement {gold} 81000
* @requirement {guild level} 90
* @requirement {guild members} 15
* @effect +40% DEX
* @duration 4 days, 12 hours
* @category Dexterity
* @package GuildBuffs
*/`
`/**
* The Dexterity IX guild buff increases Dexterity.
*
* @name Dexterity IX
* @requirement {gold} 100000
* @requirement {guild level} 100
* @requirement {guild members} 20
* @effect +45% DEX
* @duration 5 days
* @category Dexterity
* @package GuildBuffs
*/`
class GuildDexterity extends GuildBuff
@tiers = GuildDexterity::tiers = [null,
{name: "Dexterity I", level: 20, members: 1, cost: 4000, duration: {days: 1}},
{name: "Dexterity II", level: 30, members: 1, cost: 9000, duration: {days: 1, hours: 12}},
{name: "Dexterity III", level: 40, members: 4, cost: 16000, duration: {days: 2}},
{name: "<NAME>", level: 50, members: 4, cost: 25000, duration: {days: 2, hours: 12}},
{name: "<NAME>", level: 60, members: 9, cost: 36000, duration: {days: 3}},
{name: "<NAME>", level: 70, members: 9, cost: 49000, duration: {days: 3, hours: 12}},
{name: "<NAME>II", level: 80, members: 15, cost: 64000, duration: {days: 4}},
{name: "<NAME>III", level: 90, members: 15, cost: 81000, duration: {days: 4, hours: 12}},
{name: "<NAME> IX", level: 100, members: 20, cost: 100000, duration: {days: 5}}
]
constructor: (@tier = 1) ->
@type = 'Dexterity'
super()
dexPercent: -> @tier*5
module.exports = exports = GuildDexterity | true |
GuildBuff = require "../base/GuildBuff"
`/**
* The Dexterity I guild buff increases Dexterity.
*
* @name Dexterity I
* @requirement {gold} 4000
* @requirement {guild level} 20
* @requirement {guild members} 1
* @effect +5% DEX
* @duration 1 day
* @category Dexterity
* @package GuildBuffs
*/`
`/**
* The Dexterity II guild buff increases Dexterity.
*
* @name Dexterity II
* @requirement {gold} 9000
* @requirement {guild level} 30
* @requirement {guild members} 1
* @effect +10% DEX
* @duration 1 day, 12 hours
* @category Dexterity
* @package GuildBuffs
*/`
`/**
* The Dexterity III guild buff increases Dexterity.
*
* @name Dexterity III
* @requirement {gold} 16000
* @requirement {guild level} 40
* @requirement {guild members} 4
* @effect +15% DEX
* @duration 2 days
* @category Dexterity
* @package GuildBuffs
*/`
`/**
* The Dexterity IV guild buff increases Dexterity.
*
* @name Dexterity IV
* @requirement {gold} 25000
* @requirement {guild level} 50
* @requirement {guild members} 4
* @effect +20% DEX
* @duration 2 days, 12 hours
* @category Dexterity
* @package GuildBuffs
*/`
`/**
* The Dexterity V guild buff increases Dexterity.
*
* @name Dexterity V
* @requirement {gold} 36000
* @requirement {guild level} 60
* @requirement {guild members} 9
* @effect +25% DEX
* @duration 3 days
* @category Dexterity
* @package GuildBuffs
*/`
`/**
* The Dexterity VI guild buff increases Dexterity.
*
* @name Dexterity VI
* @requirement {gold} 49000
* @requirement {guild level} 80
* @requirement {guild members} 9
* @effect +30% DEX
* @duration 3 days, 12 hours
* @category Dexterity
* @package GuildBuffs
*/`
`/**
* The Dexterity VII guild buff increases Dexterity.
*
* @name Dexterity VII
* @requirement {gold} 64000
* @requirement {guild level} 80
* @requirement {guild members} 15
* @effect +35% DEX
* @duration 4 days
* @category Dexterity
* @package GuildBuffs
*/`
`/**
* The Dexterity VIII guild buff increases Dexterity.
*
* @name Dexterity VIII
* @requirement {gold} 81000
* @requirement {guild level} 90
* @requirement {guild members} 15
* @effect +40% DEX
* @duration 4 days, 12 hours
* @category Dexterity
* @package GuildBuffs
*/`
`/**
* The Dexterity IX guild buff increases Dexterity.
*
* @name Dexterity IX
* @requirement {gold} 100000
* @requirement {guild level} 100
* @requirement {guild members} 20
* @effect +45% DEX
* @duration 5 days
* @category Dexterity
* @package GuildBuffs
*/`
class GuildDexterity extends GuildBuff
@tiers = GuildDexterity::tiers = [null,
{name: "Dexterity I", level: 20, members: 1, cost: 4000, duration: {days: 1}},
{name: "Dexterity II", level: 30, members: 1, cost: 9000, duration: {days: 1, hours: 12}},
{name: "Dexterity III", level: 40, members: 4, cost: 16000, duration: {days: 2}},
{name: "PI:NAME:<NAME>END_PI", level: 50, members: 4, cost: 25000, duration: {days: 2, hours: 12}},
{name: "PI:NAME:<NAME>END_PI", level: 60, members: 9, cost: 36000, duration: {days: 3}},
{name: "PI:NAME:<NAME>END_PI", level: 70, members: 9, cost: 49000, duration: {days: 3, hours: 12}},
{name: "PI:NAME:<NAME>END_PIII", level: 80, members: 15, cost: 64000, duration: {days: 4}},
{name: "PI:NAME:<NAME>END_PIIII", level: 90, members: 15, cost: 81000, duration: {days: 4, hours: 12}},
{name: "PI:NAME:<NAME>END_PI IX", level: 100, members: 20, cost: 100000, duration: {days: 5}}
]
constructor: (@tier = 1) ->
@type = 'Dexterity'
super()
dexPercent: -> @tier*5
module.exports = exports = GuildDexterity |
[
{
"context": "scopeName: \"source.danmakufu\"\nname: \"Danmakufu\"\nfileTypes: [\n \"dnh\"\n]\nfirstLineMatch: \"^\\\\s*(#T",
"end": 46,
"score": 0.537645697593689,
"start": 43,
"tag": "NAME",
"value": "ufu"
}
] | grammars/danmakufu.cson | drakeirving/atom-language-danmakufu | 0 | scopeName: "source.danmakufu"
name: "Danmakufu"
fileTypes: [
"dnh"
]
firstLineMatch: "^\\s*(#TouhouDanmakufu|script_|#include).*"
patterns: [
{
match: "//.*$\\n?"
name: "comment.line.double-slash.danmakufu"
}
{
begin: "/\\*"
end: "\\*/"
name: "comment.block.danmakufu"
}
{
match: "\\b\\d+\\.?\\d*\\b"
name: "constant.numeric.danmakufu"
}
{
match: "\\b(true|false|pi)\\b"
name: "constant.language.danmakufu"
}
{
match: "\\b(EV)_[\\w_]+\\b"
name: "constant.other.enum.event.danmakufu"
}
{
match: "\\b(ID_INVALID|KEY_INVALID|OBJ_[\\w_]+|TYPE_[\\w_]+|ITEM_[\\w_]+|STATE_[\\w_]+)\\b"
name: "constant.other.enum.other.danmakufu"
}
{
match: "\\b(BLEND_ALPHA|BLEND_ADD_RGB|BLEND_ADD_ARGB|BLEND_MULTIPLY|BLEND_SUBTRACT|BLEND_INV_DESTRGB)\\b"
name: "constant.other.enum.blendtype.danmakufu"
}
{
match: "\\b(INFO_SCRIPT_TYPE|INFO_SCRIPT_PATH|INFO_SCRIPT_ID|INFO_SCRIPT_TITLE|INFO_SCRIPT_TEXT|INFO_SCRIPT_IMAGE|INFO_SCRIPT_REPLAY_NAME|INFO_LIFE|INFO_DAMAGE_RATE_SHOT|INFO_DAMAGE_RATE_SPELL|INFO_SHOT_HIT_COUNT|INFO_IS_SPELL|INFO_IS_LAST_SPELL|INFO_IS_DURABLE_SPELL|INFO_IS_LAST_STEP|INFO_TIMER|INFO_TIMERF|INFO_ORGTIMERF|INFO_SPELL_SCORE|INFO_REMAIN_STEP_COUNT|INFO_ACTIVE_STEP_LIFE_COUNT|INFO_ACTIVE_STEP_TOTAL_MAX_LIFE|INFO_ACTIVE_STEP_TOTAL_LIFE|INFO_PLAYER_SHOOTDOWN_COUNT|INFO_PLAYER_SPELL_COUNT|INFO_ACTIVE_STEP_LIFE_RATE_LIST|INFO_CURRENT_LIFE|INFO_CURRENT_LIFE_MAX|INFO_RECT|INFO_DELAY_COLOR|INFO_BLEND|INFO_COLLISION|INFO_COLLISION_LIST|INFO_ITEM_SCORE|REPLAY_FILE_PATH|REPLAY_DATE_TIME|REPLAY_USER_NAME|REPLAY_TOTAL_SCORE|REPLAY_FPS_AVERAGE|REPLAY_PLAYER_NAME|REPLAY_STAGE_INDEX_LIST|REPLAY_STAGE_START_SCORE_LIST|REPLAY_STAGE_LAST_SCORE_LIST|REPLAY_COMMENT)\\b"
name: "constant.other.enum.infotype.danmakufu"
}
{
match: "\\b(VK_[\\w_]+|KEY_[\\w_]+|MOUSE_(LEFT|RIGHT|MIDDLE))\\b"
name: "constant.other.enum.input.danmakufu"
}
{
match: "\\b(alternative|ascent|break|case|descent|else|if|in|local|loop|return|others|times|while|yield)\\b"
name: "keyword.control.flow.danmakufu"
}
{
match: "^\\s*#(TouhouDanmakufu|ScriptVersion|ID|Title|Text|Image|System|Background|BGM|Player|ReplayName)\\b"
name: "keyword.control.header.danmakufu"
}
{
match: "^\\s*#include\\b"
name: "keyword.control.include.danmakufu"
}
{
match: "\\b(add|append|concatenate|divide|erase|index|length|multiply|not|negative|power|predecessor|remainder|result|slice|successor|subtract)\\b"
name: "keyword.operator.textual.danmakufu"
}
{
match: "==|!=|<=|>=|<|>|\\|\\||&&|~|!"
name: "keyword.operator.logical.danmakufu"
}
{
match: "\\+=|\\+|-=|-|\\*=|\\*|/=|/|%|\\^|\\(\\||\\|\\)"
name: "keyword.operator.symbol.danmakufu"
}
{
match: "^\\s*(let|real|char|boolean)\\b"
name: "storage.type.variable.danmakufu"
}
{
begin: "'"
end: "'"
name: "string.quoted.single.danmakufu"
}
{
begin: "(?<!\\\\)\""
end: "(?<!\\\\)\""
name: "string.quoted.double.danmakufu"
}
{
match: "^\\s*@(Initialize|Loading|Event|MainLoop|Finalize)\\b"
name: "entity.name.function.predefined.danmakufu"
comment: "The @ prefix can be used to define any subroutine, but this should be considered bad style."
}
{
begin: "^\\s*(function|sub|task)\\b"
beginCaptures:
"1":
name: "storage.type.function.danmakufu"
end: "\\{"
name: "meta.function.danmakufu"
patterns: [
{
begin: "([A-Za-z_]\\w*)\\s*\\("
beginCaptures:
"1":
name: "entity.name.function.danmakufu"
end: "\\)"
name: "meta.function.identifier.danmakufu"
patterns: [
{
match: "\\b[A-Za-z_]\\w*\\b"
name: "variable.parameter.danmakufu"
}
]
}
{
match: "[A-Za-z_]\\w*\\s*"
name: "entity.name.function.danmakufu"
}
]
}
{
match: ":"
name: "invalid.danmakufu"
}
]
| 160025 | scopeName: "source.danmakufu"
name: "Danmak<NAME>"
fileTypes: [
"dnh"
]
firstLineMatch: "^\\s*(#TouhouDanmakufu|script_|#include).*"
patterns: [
{
match: "//.*$\\n?"
name: "comment.line.double-slash.danmakufu"
}
{
begin: "/\\*"
end: "\\*/"
name: "comment.block.danmakufu"
}
{
match: "\\b\\d+\\.?\\d*\\b"
name: "constant.numeric.danmakufu"
}
{
match: "\\b(true|false|pi)\\b"
name: "constant.language.danmakufu"
}
{
match: "\\b(EV)_[\\w_]+\\b"
name: "constant.other.enum.event.danmakufu"
}
{
match: "\\b(ID_INVALID|KEY_INVALID|OBJ_[\\w_]+|TYPE_[\\w_]+|ITEM_[\\w_]+|STATE_[\\w_]+)\\b"
name: "constant.other.enum.other.danmakufu"
}
{
match: "\\b(BLEND_ALPHA|BLEND_ADD_RGB|BLEND_ADD_ARGB|BLEND_MULTIPLY|BLEND_SUBTRACT|BLEND_INV_DESTRGB)\\b"
name: "constant.other.enum.blendtype.danmakufu"
}
{
match: "\\b(INFO_SCRIPT_TYPE|INFO_SCRIPT_PATH|INFO_SCRIPT_ID|INFO_SCRIPT_TITLE|INFO_SCRIPT_TEXT|INFO_SCRIPT_IMAGE|INFO_SCRIPT_REPLAY_NAME|INFO_LIFE|INFO_DAMAGE_RATE_SHOT|INFO_DAMAGE_RATE_SPELL|INFO_SHOT_HIT_COUNT|INFO_IS_SPELL|INFO_IS_LAST_SPELL|INFO_IS_DURABLE_SPELL|INFO_IS_LAST_STEP|INFO_TIMER|INFO_TIMERF|INFO_ORGTIMERF|INFO_SPELL_SCORE|INFO_REMAIN_STEP_COUNT|INFO_ACTIVE_STEP_LIFE_COUNT|INFO_ACTIVE_STEP_TOTAL_MAX_LIFE|INFO_ACTIVE_STEP_TOTAL_LIFE|INFO_PLAYER_SHOOTDOWN_COUNT|INFO_PLAYER_SPELL_COUNT|INFO_ACTIVE_STEP_LIFE_RATE_LIST|INFO_CURRENT_LIFE|INFO_CURRENT_LIFE_MAX|INFO_RECT|INFO_DELAY_COLOR|INFO_BLEND|INFO_COLLISION|INFO_COLLISION_LIST|INFO_ITEM_SCORE|REPLAY_FILE_PATH|REPLAY_DATE_TIME|REPLAY_USER_NAME|REPLAY_TOTAL_SCORE|REPLAY_FPS_AVERAGE|REPLAY_PLAYER_NAME|REPLAY_STAGE_INDEX_LIST|REPLAY_STAGE_START_SCORE_LIST|REPLAY_STAGE_LAST_SCORE_LIST|REPLAY_COMMENT)\\b"
name: "constant.other.enum.infotype.danmakufu"
}
{
match: "\\b(VK_[\\w_]+|KEY_[\\w_]+|MOUSE_(LEFT|RIGHT|MIDDLE))\\b"
name: "constant.other.enum.input.danmakufu"
}
{
match: "\\b(alternative|ascent|break|case|descent|else|if|in|local|loop|return|others|times|while|yield)\\b"
name: "keyword.control.flow.danmakufu"
}
{
match: "^\\s*#(TouhouDanmakufu|ScriptVersion|ID|Title|Text|Image|System|Background|BGM|Player|ReplayName)\\b"
name: "keyword.control.header.danmakufu"
}
{
match: "^\\s*#include\\b"
name: "keyword.control.include.danmakufu"
}
{
match: "\\b(add|append|concatenate|divide|erase|index|length|multiply|not|negative|power|predecessor|remainder|result|slice|successor|subtract)\\b"
name: "keyword.operator.textual.danmakufu"
}
{
match: "==|!=|<=|>=|<|>|\\|\\||&&|~|!"
name: "keyword.operator.logical.danmakufu"
}
{
match: "\\+=|\\+|-=|-|\\*=|\\*|/=|/|%|\\^|\\(\\||\\|\\)"
name: "keyword.operator.symbol.danmakufu"
}
{
match: "^\\s*(let|real|char|boolean)\\b"
name: "storage.type.variable.danmakufu"
}
{
begin: "'"
end: "'"
name: "string.quoted.single.danmakufu"
}
{
begin: "(?<!\\\\)\""
end: "(?<!\\\\)\""
name: "string.quoted.double.danmakufu"
}
{
match: "^\\s*@(Initialize|Loading|Event|MainLoop|Finalize)\\b"
name: "entity.name.function.predefined.danmakufu"
comment: "The @ prefix can be used to define any subroutine, but this should be considered bad style."
}
{
begin: "^\\s*(function|sub|task)\\b"
beginCaptures:
"1":
name: "storage.type.function.danmakufu"
end: "\\{"
name: "meta.function.danmakufu"
patterns: [
{
begin: "([A-Za-z_]\\w*)\\s*\\("
beginCaptures:
"1":
name: "entity.name.function.danmakufu"
end: "\\)"
name: "meta.function.identifier.danmakufu"
patterns: [
{
match: "\\b[A-Za-z_]\\w*\\b"
name: "variable.parameter.danmakufu"
}
]
}
{
match: "[A-Za-z_]\\w*\\s*"
name: "entity.name.function.danmakufu"
}
]
}
{
match: ":"
name: "invalid.danmakufu"
}
]
| true | scopeName: "source.danmakufu"
name: "DanmakPI:NAME:<NAME>END_PI"
fileTypes: [
"dnh"
]
firstLineMatch: "^\\s*(#TouhouDanmakufu|script_|#include).*"
patterns: [
{
match: "//.*$\\n?"
name: "comment.line.double-slash.danmakufu"
}
{
begin: "/\\*"
end: "\\*/"
name: "comment.block.danmakufu"
}
{
match: "\\b\\d+\\.?\\d*\\b"
name: "constant.numeric.danmakufu"
}
{
match: "\\b(true|false|pi)\\b"
name: "constant.language.danmakufu"
}
{
match: "\\b(EV)_[\\w_]+\\b"
name: "constant.other.enum.event.danmakufu"
}
{
match: "\\b(ID_INVALID|KEY_INVALID|OBJ_[\\w_]+|TYPE_[\\w_]+|ITEM_[\\w_]+|STATE_[\\w_]+)\\b"
name: "constant.other.enum.other.danmakufu"
}
{
match: "\\b(BLEND_ALPHA|BLEND_ADD_RGB|BLEND_ADD_ARGB|BLEND_MULTIPLY|BLEND_SUBTRACT|BLEND_INV_DESTRGB)\\b"
name: "constant.other.enum.blendtype.danmakufu"
}
{
match: "\\b(INFO_SCRIPT_TYPE|INFO_SCRIPT_PATH|INFO_SCRIPT_ID|INFO_SCRIPT_TITLE|INFO_SCRIPT_TEXT|INFO_SCRIPT_IMAGE|INFO_SCRIPT_REPLAY_NAME|INFO_LIFE|INFO_DAMAGE_RATE_SHOT|INFO_DAMAGE_RATE_SPELL|INFO_SHOT_HIT_COUNT|INFO_IS_SPELL|INFO_IS_LAST_SPELL|INFO_IS_DURABLE_SPELL|INFO_IS_LAST_STEP|INFO_TIMER|INFO_TIMERF|INFO_ORGTIMERF|INFO_SPELL_SCORE|INFO_REMAIN_STEP_COUNT|INFO_ACTIVE_STEP_LIFE_COUNT|INFO_ACTIVE_STEP_TOTAL_MAX_LIFE|INFO_ACTIVE_STEP_TOTAL_LIFE|INFO_PLAYER_SHOOTDOWN_COUNT|INFO_PLAYER_SPELL_COUNT|INFO_ACTIVE_STEP_LIFE_RATE_LIST|INFO_CURRENT_LIFE|INFO_CURRENT_LIFE_MAX|INFO_RECT|INFO_DELAY_COLOR|INFO_BLEND|INFO_COLLISION|INFO_COLLISION_LIST|INFO_ITEM_SCORE|REPLAY_FILE_PATH|REPLAY_DATE_TIME|REPLAY_USER_NAME|REPLAY_TOTAL_SCORE|REPLAY_FPS_AVERAGE|REPLAY_PLAYER_NAME|REPLAY_STAGE_INDEX_LIST|REPLAY_STAGE_START_SCORE_LIST|REPLAY_STAGE_LAST_SCORE_LIST|REPLAY_COMMENT)\\b"
name: "constant.other.enum.infotype.danmakufu"
}
{
match: "\\b(VK_[\\w_]+|KEY_[\\w_]+|MOUSE_(LEFT|RIGHT|MIDDLE))\\b"
name: "constant.other.enum.input.danmakufu"
}
{
match: "\\b(alternative|ascent|break|case|descent|else|if|in|local|loop|return|others|times|while|yield)\\b"
name: "keyword.control.flow.danmakufu"
}
{
match: "^\\s*#(TouhouDanmakufu|ScriptVersion|ID|Title|Text|Image|System|Background|BGM|Player|ReplayName)\\b"
name: "keyword.control.header.danmakufu"
}
{
match: "^\\s*#include\\b"
name: "keyword.control.include.danmakufu"
}
{
match: "\\b(add|append|concatenate|divide|erase|index|length|multiply|not|negative|power|predecessor|remainder|result|slice|successor|subtract)\\b"
name: "keyword.operator.textual.danmakufu"
}
{
match: "==|!=|<=|>=|<|>|\\|\\||&&|~|!"
name: "keyword.operator.logical.danmakufu"
}
{
match: "\\+=|\\+|-=|-|\\*=|\\*|/=|/|%|\\^|\\(\\||\\|\\)"
name: "keyword.operator.symbol.danmakufu"
}
{
match: "^\\s*(let|real|char|boolean)\\b"
name: "storage.type.variable.danmakufu"
}
{
begin: "'"
end: "'"
name: "string.quoted.single.danmakufu"
}
{
begin: "(?<!\\\\)\""
end: "(?<!\\\\)\""
name: "string.quoted.double.danmakufu"
}
{
match: "^\\s*@(Initialize|Loading|Event|MainLoop|Finalize)\\b"
name: "entity.name.function.predefined.danmakufu"
comment: "The @ prefix can be used to define any subroutine, but this should be considered bad style."
}
{
begin: "^\\s*(function|sub|task)\\b"
beginCaptures:
"1":
name: "storage.type.function.danmakufu"
end: "\\{"
name: "meta.function.danmakufu"
patterns: [
{
begin: "([A-Za-z_]\\w*)\\s*\\("
beginCaptures:
"1":
name: "entity.name.function.danmakufu"
end: "\\)"
name: "meta.function.identifier.danmakufu"
patterns: [
{
match: "\\b[A-Za-z_]\\w*\\b"
name: "variable.parameter.danmakufu"
}
]
}
{
match: "[A-Za-z_]\\w*\\s*"
name: "entity.name.function.danmakufu"
}
]
}
{
match: ":"
name: "invalid.danmakufu"
}
]
|
[
{
"context": " file are taken from the extrordinary work done by Chris Wilson (https://github.com/cwilso/PitchDetect/blob/maste",
"end": 88,
"score": 0.9997807145118713,
"start": 76,
"tag": "NAME",
"value": "Chris Wilson"
},
{
"context": "ary work done by Chris Wilson (https://github... | public/src/waveform-0.1.coffee | Sulcalibur/pi-voice-server | 0 | ###
Large parts of this file are taken from the extrordinary work done by Chris Wilson (https://github.com/cwilso/PitchDetect/blob/master/js/pitchdetect.js):
Copyright (c) 2014 Chris Wilson
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.
###
root = exports ? this
# Organise globals
requestAnimationFrame = this.requestAnimationFrame or this.webkitRequestAnimationFrame
getUserMedia = (dictionary, callback, error) =>
@navigator.getUserMedia = @navigator.getUserMedia or @navigator.webkitGetUserMedia
@navigator.getUserMedia(dictionary, callback, error)
# Organise client
class WaveformClient
buffer = new Float32Array(1024)
jqCanvas = null
canvas = null
canvasContext = null
mediaStreamSource = null
analyser = null
audioContext = null
constructor: (opts) ->
jqCanvas = opts.canvas
jqCanvas.css(opacity: 0)
canvas = jqCanvas.get(0)
canvas.width = window.innerWidth * 0.8
canvasContext = canvas.getContext("2d")
audioContext = new AudioContext()
getUserMedia(
audio:
mandatory:
googEchoCancellation: false
googAutoGainControl: false
googNoiseSuppression: false
googHighpassFilter: false
optional: []
, (stream) =>
mediaStreamSource = audioContext.createMediaStreamSource(stream)
analyser = audioContext.createAnalyser()
analyser.fftSize = 2048
mediaStreamSource.connect(analyser)
@update()
, (ex) ->
console.log "getUserMedia threw exception: #{ex}"
)
update: ->
analyser.getFloatTimeDomainData(buffer)
@autoCorrelate(buffer, audioContext.sampleRate)
@paintCanvas()
autoCorrelate: (buffer, sampleRate) ->
SIZE = buffer.length
MIN_SAMPLES = 0
MAX_SAMPLES = Math.floor(SIZE/2)
best_offset = -1
best_correlation = 0
rms = 0
foundGoodCorrelation = false
correlations = new Array(MAX_SAMPLES)
for num in [0..SIZE]
val = buffer[num]
rms += val*val
rms = Math.sqrt(rms/SIZE)
if rms < 0.01
return -1
else
lastCorrelation = 1
for offset in [MIN_SAMPLES..MAX_SAMPLES]
correlation = 0
for num in [0..MAX_SAMPLES]
correlation += Math.abs((buffer[num])-(buffer[num + offset]))
correlation = 1 - (correlation/MAX_SAMPLES)
correlations[offset] = correlation
if correlation > 0.9 and correlation > lastCorrelation
foundGoodCorrelation = true
if correlation > best_correlation
best_correlation = correlation
best_offset = offset
else if foundGoodCorrelation
shift = (correlations[best_offset + 1] - correlations[best_offset - 1]) / correlations[best_offset]
return sampleRate / (best_offset + (8 * shift))
lastCorrelation = correlation
if best_correlation > 0.01
return sampleRate / best_offset
return -1
paintCanvas: ->
part = 100
base = (Math.PI/2) / part
zoom = 1
volumeDupe = 100
dist = canvas.width / 512
mid = canvas.height / 2
canvasContext.clearRect(0, 0, canvas.width, canvas.height)
canvasContext.beginPath()
canvasContext.lineTo(0, canvas.height / 2)
# bottom
for num in [0..512]
if num < part
zoom = Math.sin(base * num)
else if num > 512 - part
zoom = Math.sin(base * Math.abs(num - 512))
else
zoom = 1
canvasContext.lineTo(dist * num, mid + (zoom * (Math.abs(buffer[num] * volumeDupe))))
# top
for num in [0..512]
if num < part
zoom = Math.sin(base * num)
else if num > 512 - part
zoom = Math.sin(base * Math.abs(num - 512))
else
zoom = 1
canvasContext.lineTo(dist * num, mid + (0 - (zoom * (Math.abs(buffer[num] * volumeDupe)))))
canvasContext.lineTo(canvas.width, mid)
canvasContext.fillStyle = "rgba(255,255,255,0.8)"
canvasContext.fill()
requestAnimationFrame =>
@update()
show: ->
jqCanvas.stop()
jqCanvas.animate(opacity: 1, 500)
hide: ->
jqCanvas.stop().css(opacity: 0)
root.WaveformClient = WaveformClient | 146478 | ###
Large parts of this file are taken from the extrordinary work done by <NAME> (https://github.com/cwilso/PitchDetect/blob/master/js/pitchdetect.js):
Copyright (c) 2014 <NAME>
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.
###
root = exports ? this
# Organise globals
requestAnimationFrame = this.requestAnimationFrame or this.webkitRequestAnimationFrame
getUserMedia = (dictionary, callback, error) =>
@navigator.getUserMedia = @navigator.getUserMedia or @navigator.webkitGetUserMedia
@navigator.getUserMedia(dictionary, callback, error)
# Organise client
class WaveformClient
buffer = new Float32Array(1024)
jqCanvas = null
canvas = null
canvasContext = null
mediaStreamSource = null
analyser = null
audioContext = null
constructor: (opts) ->
jqCanvas = opts.canvas
jqCanvas.css(opacity: 0)
canvas = jqCanvas.get(0)
canvas.width = window.innerWidth * 0.8
canvasContext = canvas.getContext("2d")
audioContext = new AudioContext()
getUserMedia(
audio:
mandatory:
googEchoCancellation: false
googAutoGainControl: false
googNoiseSuppression: false
googHighpassFilter: false
optional: []
, (stream) =>
mediaStreamSource = audioContext.createMediaStreamSource(stream)
analyser = audioContext.createAnalyser()
analyser.fftSize = 2048
mediaStreamSource.connect(analyser)
@update()
, (ex) ->
console.log "getUserMedia threw exception: #{ex}"
)
update: ->
analyser.getFloatTimeDomainData(buffer)
@autoCorrelate(buffer, audioContext.sampleRate)
@paintCanvas()
autoCorrelate: (buffer, sampleRate) ->
SIZE = buffer.length
MIN_SAMPLES = 0
MAX_SAMPLES = Math.floor(SIZE/2)
best_offset = -1
best_correlation = 0
rms = 0
foundGoodCorrelation = false
correlations = new Array(MAX_SAMPLES)
for num in [0..SIZE]
val = buffer[num]
rms += val*val
rms = Math.sqrt(rms/SIZE)
if rms < 0.01
return -1
else
lastCorrelation = 1
for offset in [MIN_SAMPLES..MAX_SAMPLES]
correlation = 0
for num in [0..MAX_SAMPLES]
correlation += Math.abs((buffer[num])-(buffer[num + offset]))
correlation = 1 - (correlation/MAX_SAMPLES)
correlations[offset] = correlation
if correlation > 0.9 and correlation > lastCorrelation
foundGoodCorrelation = true
if correlation > best_correlation
best_correlation = correlation
best_offset = offset
else if foundGoodCorrelation
shift = (correlations[best_offset + 1] - correlations[best_offset - 1]) / correlations[best_offset]
return sampleRate / (best_offset + (8 * shift))
lastCorrelation = correlation
if best_correlation > 0.01
return sampleRate / best_offset
return -1
paintCanvas: ->
part = 100
base = (Math.PI/2) / part
zoom = 1
volumeDupe = 100
dist = canvas.width / 512
mid = canvas.height / 2
canvasContext.clearRect(0, 0, canvas.width, canvas.height)
canvasContext.beginPath()
canvasContext.lineTo(0, canvas.height / 2)
# bottom
for num in [0..512]
if num < part
zoom = Math.sin(base * num)
else if num > 512 - part
zoom = Math.sin(base * Math.abs(num - 512))
else
zoom = 1
canvasContext.lineTo(dist * num, mid + (zoom * (Math.abs(buffer[num] * volumeDupe))))
# top
for num in [0..512]
if num < part
zoom = Math.sin(base * num)
else if num > 512 - part
zoom = Math.sin(base * Math.abs(num - 512))
else
zoom = 1
canvasContext.lineTo(dist * num, mid + (0 - (zoom * (Math.abs(buffer[num] * volumeDupe)))))
canvasContext.lineTo(canvas.width, mid)
canvasContext.fillStyle = "rgba(255,255,255,0.8)"
canvasContext.fill()
requestAnimationFrame =>
@update()
show: ->
jqCanvas.stop()
jqCanvas.animate(opacity: 1, 500)
hide: ->
jqCanvas.stop().css(opacity: 0)
root.WaveformClient = WaveformClient | true | ###
Large parts of this file are taken from the extrordinary work done by PI:NAME:<NAME>END_PI (https://github.com/cwilso/PitchDetect/blob/master/js/pitchdetect.js):
Copyright (c) 2014 PI:NAME:<NAME>END_PI
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.
###
root = exports ? this
# Organise globals
requestAnimationFrame = this.requestAnimationFrame or this.webkitRequestAnimationFrame
getUserMedia = (dictionary, callback, error) =>
@navigator.getUserMedia = @navigator.getUserMedia or @navigator.webkitGetUserMedia
@navigator.getUserMedia(dictionary, callback, error)
# Organise client
class WaveformClient
buffer = new Float32Array(1024)
jqCanvas = null
canvas = null
canvasContext = null
mediaStreamSource = null
analyser = null
audioContext = null
constructor: (opts) ->
jqCanvas = opts.canvas
jqCanvas.css(opacity: 0)
canvas = jqCanvas.get(0)
canvas.width = window.innerWidth * 0.8
canvasContext = canvas.getContext("2d")
audioContext = new AudioContext()
getUserMedia(
audio:
mandatory:
googEchoCancellation: false
googAutoGainControl: false
googNoiseSuppression: false
googHighpassFilter: false
optional: []
, (stream) =>
mediaStreamSource = audioContext.createMediaStreamSource(stream)
analyser = audioContext.createAnalyser()
analyser.fftSize = 2048
mediaStreamSource.connect(analyser)
@update()
, (ex) ->
console.log "getUserMedia threw exception: #{ex}"
)
update: ->
analyser.getFloatTimeDomainData(buffer)
@autoCorrelate(buffer, audioContext.sampleRate)
@paintCanvas()
autoCorrelate: (buffer, sampleRate) ->
SIZE = buffer.length
MIN_SAMPLES = 0
MAX_SAMPLES = Math.floor(SIZE/2)
best_offset = -1
best_correlation = 0
rms = 0
foundGoodCorrelation = false
correlations = new Array(MAX_SAMPLES)
for num in [0..SIZE]
val = buffer[num]
rms += val*val
rms = Math.sqrt(rms/SIZE)
if rms < 0.01
return -1
else
lastCorrelation = 1
for offset in [MIN_SAMPLES..MAX_SAMPLES]
correlation = 0
for num in [0..MAX_SAMPLES]
correlation += Math.abs((buffer[num])-(buffer[num + offset]))
correlation = 1 - (correlation/MAX_SAMPLES)
correlations[offset] = correlation
if correlation > 0.9 and correlation > lastCorrelation
foundGoodCorrelation = true
if correlation > best_correlation
best_correlation = correlation
best_offset = offset
else if foundGoodCorrelation
shift = (correlations[best_offset + 1] - correlations[best_offset - 1]) / correlations[best_offset]
return sampleRate / (best_offset + (8 * shift))
lastCorrelation = correlation
if best_correlation > 0.01
return sampleRate / best_offset
return -1
paintCanvas: ->
part = 100
base = (Math.PI/2) / part
zoom = 1
volumeDupe = 100
dist = canvas.width / 512
mid = canvas.height / 2
canvasContext.clearRect(0, 0, canvas.width, canvas.height)
canvasContext.beginPath()
canvasContext.lineTo(0, canvas.height / 2)
# bottom
for num in [0..512]
if num < part
zoom = Math.sin(base * num)
else if num > 512 - part
zoom = Math.sin(base * Math.abs(num - 512))
else
zoom = 1
canvasContext.lineTo(dist * num, mid + (zoom * (Math.abs(buffer[num] * volumeDupe))))
# top
for num in [0..512]
if num < part
zoom = Math.sin(base * num)
else if num > 512 - part
zoom = Math.sin(base * Math.abs(num - 512))
else
zoom = 1
canvasContext.lineTo(dist * num, mid + (0 - (zoom * (Math.abs(buffer[num] * volumeDupe)))))
canvasContext.lineTo(canvas.width, mid)
canvasContext.fillStyle = "rgba(255,255,255,0.8)"
canvasContext.fill()
requestAnimationFrame =>
@update()
show: ->
jqCanvas.stop()
jqCanvas.animate(opacity: 1, 500)
hide: ->
jqCanvas.stop().css(opacity: 0)
root.WaveformClient = WaveformClient |
[
{
"context": "---------------------------------------------\n# @: The Anh\n# d: 150328\n# f: init app\n# ---------------------",
"end": 86,
"score": 0.999620258808136,
"start": 79,
"tag": "NAME",
"value": "The Anh"
}
] | app/assets/javascripts/init.coffee | theanh/96b0e903c0b3889b355a821204fb7dcf | 31 | 'use strict'
# ----------------------------------------------------------
# @: The Anh
# d: 150328
# f: init app
# ----------------------------------------------------------
((angular) ->
angular.module('AppSurvey', [
# 'angular-data.DSCacheFactory'
'pascalprecht.translate'
'ui.bootstrap'
'highcharts-ng'
'ValidateService'
'ModalModule'
'ngRoute'
])
.config [
'$provide',
'$httpProvider',
'$translateProvider',
'$rails',
($provide, $httpProvider, $translateProvider, $rails) ->
# CSFR token
$httpProvider.defaults.headers.common['X-CSRF-Token'] = angular.element(document.querySelector('meta[name=csrf-token]')).attr('content')
# # Template cache
# if $rails.env != 'development'
# $provide.service '$templateCache', ['$cacheFactory', ($cacheFactory) ->
# $cacheFactory('templateCache', {
# maxAge: 3600000 * 24 * 7,
# storageMode: 'localStorage',
# recycleFreq: 60000
# })
# ]
# # Angular translate
# $translateProvider.useStaticFilesLoader({
# prefix: 'locales/',
# suffix: '.json'
# })
# $translateProvider.preferredLanguage($rails.locale)
# Assets interceptor
$provide.factory 'railsAssetsInterceptor', [
'$location',
'$rootScope',
'$q',
($location, $rootScope, $q) ->
request: (config) ->
if assetUrl = $rails.templates[config.url]
config.url = assetUrl
config
]
$httpProvider.interceptors.push 'railsAssetsInterceptor'
return
]
) window.angular
| 185828 | 'use strict'
# ----------------------------------------------------------
# @: <NAME>
# d: 150328
# f: init app
# ----------------------------------------------------------
((angular) ->
angular.module('AppSurvey', [
# 'angular-data.DSCacheFactory'
'pascalprecht.translate'
'ui.bootstrap'
'highcharts-ng'
'ValidateService'
'ModalModule'
'ngRoute'
])
.config [
'$provide',
'$httpProvider',
'$translateProvider',
'$rails',
($provide, $httpProvider, $translateProvider, $rails) ->
# CSFR token
$httpProvider.defaults.headers.common['X-CSRF-Token'] = angular.element(document.querySelector('meta[name=csrf-token]')).attr('content')
# # Template cache
# if $rails.env != 'development'
# $provide.service '$templateCache', ['$cacheFactory', ($cacheFactory) ->
# $cacheFactory('templateCache', {
# maxAge: 3600000 * 24 * 7,
# storageMode: 'localStorage',
# recycleFreq: 60000
# })
# ]
# # Angular translate
# $translateProvider.useStaticFilesLoader({
# prefix: 'locales/',
# suffix: '.json'
# })
# $translateProvider.preferredLanguage($rails.locale)
# Assets interceptor
$provide.factory 'railsAssetsInterceptor', [
'$location',
'$rootScope',
'$q',
($location, $rootScope, $q) ->
request: (config) ->
if assetUrl = $rails.templates[config.url]
config.url = assetUrl
config
]
$httpProvider.interceptors.push 'railsAssetsInterceptor'
return
]
) window.angular
| true | 'use strict'
# ----------------------------------------------------------
# @: PI:NAME:<NAME>END_PI
# d: 150328
# f: init app
# ----------------------------------------------------------
((angular) ->
angular.module('AppSurvey', [
# 'angular-data.DSCacheFactory'
'pascalprecht.translate'
'ui.bootstrap'
'highcharts-ng'
'ValidateService'
'ModalModule'
'ngRoute'
])
.config [
'$provide',
'$httpProvider',
'$translateProvider',
'$rails',
($provide, $httpProvider, $translateProvider, $rails) ->
# CSFR token
$httpProvider.defaults.headers.common['X-CSRF-Token'] = angular.element(document.querySelector('meta[name=csrf-token]')).attr('content')
# # Template cache
# if $rails.env != 'development'
# $provide.service '$templateCache', ['$cacheFactory', ($cacheFactory) ->
# $cacheFactory('templateCache', {
# maxAge: 3600000 * 24 * 7,
# storageMode: 'localStorage',
# recycleFreq: 60000
# })
# ]
# # Angular translate
# $translateProvider.useStaticFilesLoader({
# prefix: 'locales/',
# suffix: '.json'
# })
# $translateProvider.preferredLanguage($rails.locale)
# Assets interceptor
$provide.factory 'railsAssetsInterceptor', [
'$location',
'$rootScope',
'$q',
($location, $rootScope, $q) ->
request: (config) ->
if assetUrl = $rails.templates[config.url]
config.url = assetUrl
config
]
$httpProvider.interceptors.push 'railsAssetsInterceptor'
return
]
) window.angular
|
[
{
"context": " config.headers['X-PhpDraft-DraftPassword'] = \"#{$sessionStorage.draft_password}\"\n\n config\n\nangul",
"end": 277,
"score": 0.7813090682029724,
"start": 277,
"tag": "PASSWORD",
"value": ""
},
{
"context": "raftPassword'] = \"#{$sessionStorage.draft_password}\... | app/coffee/config/add_draft_password_header.coffee | justinpyvis/phpdraft | 0 | angular.module('app').factory 'draftPasswordHttpRequestInterceptor', ($sessionStorage) ->
request: (config) ->
if $sessionStorage.draft_password? and $sessionStorage.draft_password != undefined
config.headers ?= {}
config.headers['X-PhpDraft-DraftPassword'] = "#{$sessionStorage.draft_password}"
config
angular.module('app').config ($httpProvider) ->
$httpProvider.interceptors.push('draftPasswordHttpRequestInterceptor'); | 198909 | angular.module('app').factory 'draftPasswordHttpRequestInterceptor', ($sessionStorage) ->
request: (config) ->
if $sessionStorage.draft_password? and $sessionStorage.draft_password != undefined
config.headers ?= {}
config.headers['X-PhpDraft-DraftPassword'] =<PASSWORD> "#{$sessionStorage.draft_password<PASSWORD>}"
config
angular.module('app').config ($httpProvider) ->
$httpProvider.interceptors.push('draftPasswordHttpRequestInterceptor'); | true | angular.module('app').factory 'draftPasswordHttpRequestInterceptor', ($sessionStorage) ->
request: (config) ->
if $sessionStorage.draft_password? and $sessionStorage.draft_password != undefined
config.headers ?= {}
config.headers['X-PhpDraft-DraftPassword'] =PI:PASSWORD:<PASSWORD>END_PI "#{$sessionStorage.draft_passwordPI:PASSWORD:<PASSWORD>END_PI}"
config
angular.module('app').config ($httpProvider) ->
$httpProvider.interceptors.push('draftPasswordHttpRequestInterceptor'); |
[
{
"context": "ssage', => done()\n @sut.send 'message', 'Minerva Walters'\n\n it 'should call socket.emit', ->\n ",
"end": 4579,
"score": 0.9998452067375183,
"start": 4564,
"tag": "NAME",
"value": "Minerva Walters"
}
] | test/src/srv-socket-spec.coffee | octoblu/npm | 3 | {beforeEach, describe, it} = global
{expect} = require 'chai'
sinon = require 'sinon'
{EventEmitter} = require 'events'
SrvSocket = require '../../src/srv-socket'
AsymetricSocket = require '../asymmetric-socket'
describe 'SrvSocket spec', ->
describe '->connect', ->
describe 'when constructed with resolveSrv and secure true', ->
beforeEach ->
@dns = resolveSrv: sinon.stub()
@socket = new AsymetricSocket
@socketIoClient = sinon.spy(=> @socket)
options = resolveSrv: true, service: 'meshblu', domain: 'octoblu.com', secure: true
dependencies = {@dns, @socketIoClient}
@sut = new SrvSocket options, dependencies
describe 'when connect is called', ->
beforeEach 'making the request', ->
@dns.resolveSrv.withArgs('_meshblu._socket-io-wss.octoblu.com').yields null, [{
name: 'mesh.biz'
port: 34
priority: 1
weight: 100
}]
@sut.connect()
@socket.incoming.emit 'connect'
it 'should call request with the resolved url', ->
expect(@socketIoClient).to.have.been.calledWith 'wss://mesh.biz:34'
describe 'when constructed with resolveSrv and secure false', ->
beforeEach ->
@dns = resolveSrv: sinon.stub()
@socket = new EventEmitter
@socketIoClient = sinon.spy(=> @socket)
options = resolveSrv: true, service: 'meshblu', domain: 'octoblu.com', secure: false
dependencies = {@dns, @socketIoClient}
@sut = new SrvSocket options, dependencies
describe 'when connect is called', ->
beforeEach 'making the request', ->
@dns.resolveSrv.withArgs('_meshblu._socket-io-ws.octoblu.com').yields null, [{
name: 'insecure.xxx'
port: 80
priority: 1
weight: 100
}]
@sut.connect()
@socket.emit 'connect'
it 'should call request with the resolved url', ->
expect(@socketIoClient).to.have.been.calledWith 'ws://insecure.xxx:80'
describe 'when constructed without resolveSrv', ->
beforeEach ->
@socket = new EventEmitter
@socketIoClient = sinon.spy(=> @socket)
options = resolveSrv: false, protocol: 'wss', hostname: 'thug.biz', port: 123
dependencies = {@socketIoClient}
@sut = new SrvSocket options, dependencies
describe 'when connect is called', ->
beforeEach 'making the request', ->
@sut.connect()
@socket.emit 'connect'
it 'should call request with the formatted url', ->
expect(@socketIoClient).to.have.been.calledWith 'wss://thug.biz:123'
describe 'when constructed socketIO options', ->
beforeEach ->
@socket = new EventEmitter
@socketIoClient = sinon.spy(=> @socket)
options = {
resolveSrv: false
protocol: 'wss'
hostname: 'thug.biz'
port: 123
socketIoOptions: {some_option: true}
}
dependencies = {@socketIoClient}
@sut = new SrvSocket options, dependencies
describe 'when connect is called', ->
beforeEach 'making the request', ->
@sut.connect()
@socket.emit 'connect'
it 'should call request with the formatted url', ->
expect(@socketIoClient).to.have.been.calledWith 'wss://thug.biz:123', {
some_option: true
forceNew: true
reconnection: false
}
describe 'with a connected socket', ->
beforeEach ->
@dns = resolveSrv: sinon.stub().yields null, [{
name: 'secure.bikes'
port: 443
priority: 1
weight: 100
}]
@socket = new AsymetricSocket
@socket.close = sinon.spy()
@socketIoClient = sinon.spy(=> @socket)
options = resolveSrv: true, service: 'meshblu', domain: 'octoblu.com', secure: true
dependencies = {@dns, @socketIoClient}
@sut = new SrvSocket options, dependencies
@sut.connect()
@socket.incoming.emit 'connect'
describe '->close', ->
describe 'when called', ->
beforeEach (done) ->
@sut.close done
@socket.incoming.emit 'disconnect'
it 'should call close on the socket', ->
expect(@socket.close).to.have.been.called
describe '->send', ->
describe 'when called', ->
beforeEach (done) ->
sinon.spy @socket, 'emit'
@socket.outgoing.on 'message', => done()
@sut.send 'message', 'Minerva Walters'
it 'should call socket.emit', ->
expect(@socket.emit).to.have.been.called
| 26672 | {beforeEach, describe, it} = global
{expect} = require 'chai'
sinon = require 'sinon'
{EventEmitter} = require 'events'
SrvSocket = require '../../src/srv-socket'
AsymetricSocket = require '../asymmetric-socket'
describe 'SrvSocket spec', ->
describe '->connect', ->
describe 'when constructed with resolveSrv and secure true', ->
beforeEach ->
@dns = resolveSrv: sinon.stub()
@socket = new AsymetricSocket
@socketIoClient = sinon.spy(=> @socket)
options = resolveSrv: true, service: 'meshblu', domain: 'octoblu.com', secure: true
dependencies = {@dns, @socketIoClient}
@sut = new SrvSocket options, dependencies
describe 'when connect is called', ->
beforeEach 'making the request', ->
@dns.resolveSrv.withArgs('_meshblu._socket-io-wss.octoblu.com').yields null, [{
name: 'mesh.biz'
port: 34
priority: 1
weight: 100
}]
@sut.connect()
@socket.incoming.emit 'connect'
it 'should call request with the resolved url', ->
expect(@socketIoClient).to.have.been.calledWith 'wss://mesh.biz:34'
describe 'when constructed with resolveSrv and secure false', ->
beforeEach ->
@dns = resolveSrv: sinon.stub()
@socket = new EventEmitter
@socketIoClient = sinon.spy(=> @socket)
options = resolveSrv: true, service: 'meshblu', domain: 'octoblu.com', secure: false
dependencies = {@dns, @socketIoClient}
@sut = new SrvSocket options, dependencies
describe 'when connect is called', ->
beforeEach 'making the request', ->
@dns.resolveSrv.withArgs('_meshblu._socket-io-ws.octoblu.com').yields null, [{
name: 'insecure.xxx'
port: 80
priority: 1
weight: 100
}]
@sut.connect()
@socket.emit 'connect'
it 'should call request with the resolved url', ->
expect(@socketIoClient).to.have.been.calledWith 'ws://insecure.xxx:80'
describe 'when constructed without resolveSrv', ->
beforeEach ->
@socket = new EventEmitter
@socketIoClient = sinon.spy(=> @socket)
options = resolveSrv: false, protocol: 'wss', hostname: 'thug.biz', port: 123
dependencies = {@socketIoClient}
@sut = new SrvSocket options, dependencies
describe 'when connect is called', ->
beforeEach 'making the request', ->
@sut.connect()
@socket.emit 'connect'
it 'should call request with the formatted url', ->
expect(@socketIoClient).to.have.been.calledWith 'wss://thug.biz:123'
describe 'when constructed socketIO options', ->
beforeEach ->
@socket = new EventEmitter
@socketIoClient = sinon.spy(=> @socket)
options = {
resolveSrv: false
protocol: 'wss'
hostname: 'thug.biz'
port: 123
socketIoOptions: {some_option: true}
}
dependencies = {@socketIoClient}
@sut = new SrvSocket options, dependencies
describe 'when connect is called', ->
beforeEach 'making the request', ->
@sut.connect()
@socket.emit 'connect'
it 'should call request with the formatted url', ->
expect(@socketIoClient).to.have.been.calledWith 'wss://thug.biz:123', {
some_option: true
forceNew: true
reconnection: false
}
describe 'with a connected socket', ->
beforeEach ->
@dns = resolveSrv: sinon.stub().yields null, [{
name: 'secure.bikes'
port: 443
priority: 1
weight: 100
}]
@socket = new AsymetricSocket
@socket.close = sinon.spy()
@socketIoClient = sinon.spy(=> @socket)
options = resolveSrv: true, service: 'meshblu', domain: 'octoblu.com', secure: true
dependencies = {@dns, @socketIoClient}
@sut = new SrvSocket options, dependencies
@sut.connect()
@socket.incoming.emit 'connect'
describe '->close', ->
describe 'when called', ->
beforeEach (done) ->
@sut.close done
@socket.incoming.emit 'disconnect'
it 'should call close on the socket', ->
expect(@socket.close).to.have.been.called
describe '->send', ->
describe 'when called', ->
beforeEach (done) ->
sinon.spy @socket, 'emit'
@socket.outgoing.on 'message', => done()
@sut.send 'message', '<NAME>'
it 'should call socket.emit', ->
expect(@socket.emit).to.have.been.called
| true | {beforeEach, describe, it} = global
{expect} = require 'chai'
sinon = require 'sinon'
{EventEmitter} = require 'events'
SrvSocket = require '../../src/srv-socket'
AsymetricSocket = require '../asymmetric-socket'
describe 'SrvSocket spec', ->
describe '->connect', ->
describe 'when constructed with resolveSrv and secure true', ->
beforeEach ->
@dns = resolveSrv: sinon.stub()
@socket = new AsymetricSocket
@socketIoClient = sinon.spy(=> @socket)
options = resolveSrv: true, service: 'meshblu', domain: 'octoblu.com', secure: true
dependencies = {@dns, @socketIoClient}
@sut = new SrvSocket options, dependencies
describe 'when connect is called', ->
beforeEach 'making the request', ->
@dns.resolveSrv.withArgs('_meshblu._socket-io-wss.octoblu.com').yields null, [{
name: 'mesh.biz'
port: 34
priority: 1
weight: 100
}]
@sut.connect()
@socket.incoming.emit 'connect'
it 'should call request with the resolved url', ->
expect(@socketIoClient).to.have.been.calledWith 'wss://mesh.biz:34'
describe 'when constructed with resolveSrv and secure false', ->
beforeEach ->
@dns = resolveSrv: sinon.stub()
@socket = new EventEmitter
@socketIoClient = sinon.spy(=> @socket)
options = resolveSrv: true, service: 'meshblu', domain: 'octoblu.com', secure: false
dependencies = {@dns, @socketIoClient}
@sut = new SrvSocket options, dependencies
describe 'when connect is called', ->
beforeEach 'making the request', ->
@dns.resolveSrv.withArgs('_meshblu._socket-io-ws.octoblu.com').yields null, [{
name: 'insecure.xxx'
port: 80
priority: 1
weight: 100
}]
@sut.connect()
@socket.emit 'connect'
it 'should call request with the resolved url', ->
expect(@socketIoClient).to.have.been.calledWith 'ws://insecure.xxx:80'
describe 'when constructed without resolveSrv', ->
beforeEach ->
@socket = new EventEmitter
@socketIoClient = sinon.spy(=> @socket)
options = resolveSrv: false, protocol: 'wss', hostname: 'thug.biz', port: 123
dependencies = {@socketIoClient}
@sut = new SrvSocket options, dependencies
describe 'when connect is called', ->
beforeEach 'making the request', ->
@sut.connect()
@socket.emit 'connect'
it 'should call request with the formatted url', ->
expect(@socketIoClient).to.have.been.calledWith 'wss://thug.biz:123'
describe 'when constructed socketIO options', ->
beforeEach ->
@socket = new EventEmitter
@socketIoClient = sinon.spy(=> @socket)
options = {
resolveSrv: false
protocol: 'wss'
hostname: 'thug.biz'
port: 123
socketIoOptions: {some_option: true}
}
dependencies = {@socketIoClient}
@sut = new SrvSocket options, dependencies
describe 'when connect is called', ->
beforeEach 'making the request', ->
@sut.connect()
@socket.emit 'connect'
it 'should call request with the formatted url', ->
expect(@socketIoClient).to.have.been.calledWith 'wss://thug.biz:123', {
some_option: true
forceNew: true
reconnection: false
}
describe 'with a connected socket', ->
beforeEach ->
@dns = resolveSrv: sinon.stub().yields null, [{
name: 'secure.bikes'
port: 443
priority: 1
weight: 100
}]
@socket = new AsymetricSocket
@socket.close = sinon.spy()
@socketIoClient = sinon.spy(=> @socket)
options = resolveSrv: true, service: 'meshblu', domain: 'octoblu.com', secure: true
dependencies = {@dns, @socketIoClient}
@sut = new SrvSocket options, dependencies
@sut.connect()
@socket.incoming.emit 'connect'
describe '->close', ->
describe 'when called', ->
beforeEach (done) ->
@sut.close done
@socket.incoming.emit 'disconnect'
it 'should call close on the socket', ->
expect(@socket.close).to.have.been.called
describe '->send', ->
describe 'when called', ->
beforeEach (done) ->
sinon.spy @socket, 'emit'
@socket.outgoing.on 'message', => done()
@sut.send 'message', 'PI:NAME:<NAME>END_PI'
it 'should call socket.emit', ->
expect(@socket.emit).to.have.been.called
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999107122421265,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/react/beatmap-discussions/new-reply.coffee | osu-katakuna/osu-katakuna-web | 5 | # Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import { MessageLengthCounter } from './message-length-counter'
import { BigButton } from 'big-button'
import * as React from 'react'
import { button, div, form, input, label, span, i } from 'react-dom-factories'
import { UserAvatar } from 'user-avatar'
el = React.createElement
bn = 'beatmap-discussion-post'
export class NewReply extends React.PureComponent
ACTION_ICONS =
reply_resolve: 'fas fa-check'
reply_reopen: 'fas fa-exclamation-circle'
reply: 'fas fa-reply'
constructor: (props) ->
super props
@box = React.createRef()
@throttledPost = _.throttle @post, 1000
@handleKeyDown = InputHandler.textarea @handleKeyDownCallback
@state =
editing: false
message: ''
posting: null
componentWillUnmount: =>
@throttledPost.cancel()
@postXhr?.abort()
render: =>
if @state.editing
@renderBox()
else
@renderPlaceholder()
renderBox: =>
div
className: "#{bn} #{bn}--reply #{bn}--new-reply"
div
className: "#{bn}__content"
div className: "#{bn}__avatar",
el UserAvatar, user: @props.currentUser, modifiers: ['full-rounded']
@renderCancelButton()
div className: "#{bn}__message-container",
el TextareaAutosize,
disabled: @state.posting?
className: "#{bn}__message #{bn}__message--editor"
value: @state.message
onChange: @setMessage
onKeyDown: @handleKeyDown
placeholder: osu.trans 'beatmaps.discussions.reply_placeholder'
ref: @box
div
className: "#{bn}__footer #{bn}__footer--notice"
osu.trans 'beatmaps.discussions.reply_notice'
el MessageLengthCounter, message: @state.message, isTimeline: @isTimeline()
div
className: "#{bn}__footer"
div className: "#{bn}__actions",
div className: "#{bn}__actions-group",
if @canResolve() && !@props.discussion.resolved
@renderReplyButton 'reply_resolve'
if @canReopen() && @props.discussion.resolved
@renderReplyButton 'reply_reopen'
@renderReplyButton 'reply'
renderCancelButton: =>
button
className: "#{bn}__action #{bn}__action--cancel"
disabled: @state.posting?
onClick: => @setState editing: false
i className: 'fas fa-times'
renderPlaceholder: =>
[text, icon] =
if @props.currentUser.id?
[osu.trans('beatmap_discussions.reply.open.user'), 'fas fa-reply']
else
[osu.trans('beatmap_discussions.reply.open.guest'), 'fas fa-sign-in-alt']
div
className: "#{bn} #{bn}--reply #{bn}--new-reply #{bn}--new-reply-placeholder"
el BigButton,
text: text
icon: icon
modifiers: ['beatmap-discussion-reply-open']
props:
onClick: @editStart
renderReplyButton: (action) =>
div className: "#{bn}__action",
el BigButton,
text: osu.trans("common.buttons.#{action}")
icon: ACTION_ICONS[action]
isBusy: @state.posting == action
props:
disabled: !@validPost() || @state.posting?
onClick: @throttledPost
'data-action': action
canReopen: =>
@props.discussion.can_be_resolved && @props.discussion.current_user_attributes.can_reopen
canResolve: =>
@props.discussion.can_be_resolved && @props.discussion.current_user_attributes.can_resolve
editStart: =>
if !@props.currentUser.id?
userLogin.show()
return
@setState editing: true, =>
@box.current?.focus()
handleKeyDownCallback: (type, event) =>
switch type
when InputHandler.CANCEL
@setState editing: false
when InputHandler.SUBMIT
@throttledPost(event)
isTimeline: =>
@props.discussion.timestamp?
post: (event) =>
return if !@validPost()
LoadingOverlay.show()
@postXhr?.abort()
# in case the event came from input box, do 'reply'.
action = event.currentTarget.dataset.action ? 'reply'
@setState posting: action
resolved = switch action
when 'reply_resolve' then true
when 'reply_reopen' then false
else null
@postXhr = $.ajax laroute.route('beatmap-discussion-posts.store'),
method: 'POST'
data:
beatmap_discussion_id: @props.discussion.id
beatmap_discussion:
# Only add resolved flag to beatmap_discussion if there was an
# explicit change (resolve/reopen).
if resolved?
resolved: resolved
else
{}
beatmap_discussion_post:
message: @state.message
.done (data) =>
@setState
message: ''
editing: false
$.publish 'beatmapDiscussionPost:markRead', id: data.beatmap_discussion_post_ids
$.publish 'beatmapsetDiscussions:update', beatmapset: data.beatmapset
.fail osu.ajaxError
.always =>
LoadingOverlay.hide()
@setState posting: null
setMessage: (e) =>
@setState message: e.target.value
validPost: =>
BeatmapDiscussionHelper.validMessageLength(@state.message, @isTimeline())
| 99619 | # Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import { MessageLengthCounter } from './message-length-counter'
import { BigButton } from 'big-button'
import * as React from 'react'
import { button, div, form, input, label, span, i } from 'react-dom-factories'
import { UserAvatar } from 'user-avatar'
el = React.createElement
bn = 'beatmap-discussion-post'
export class NewReply extends React.PureComponent
ACTION_ICONS =
reply_resolve: 'fas fa-check'
reply_reopen: 'fas fa-exclamation-circle'
reply: 'fas fa-reply'
constructor: (props) ->
super props
@box = React.createRef()
@throttledPost = _.throttle @post, 1000
@handleKeyDown = InputHandler.textarea @handleKeyDownCallback
@state =
editing: false
message: ''
posting: null
componentWillUnmount: =>
@throttledPost.cancel()
@postXhr?.abort()
render: =>
if @state.editing
@renderBox()
else
@renderPlaceholder()
renderBox: =>
div
className: "#{bn} #{bn}--reply #{bn}--new-reply"
div
className: "#{bn}__content"
div className: "#{bn}__avatar",
el UserAvatar, user: @props.currentUser, modifiers: ['full-rounded']
@renderCancelButton()
div className: "#{bn}__message-container",
el TextareaAutosize,
disabled: @state.posting?
className: "#{bn}__message #{bn}__message--editor"
value: @state.message
onChange: @setMessage
onKeyDown: @handleKeyDown
placeholder: osu.trans 'beatmaps.discussions.reply_placeholder'
ref: @box
div
className: "#{bn}__footer #{bn}__footer--notice"
osu.trans 'beatmaps.discussions.reply_notice'
el MessageLengthCounter, message: @state.message, isTimeline: @isTimeline()
div
className: "#{bn}__footer"
div className: "#{bn}__actions",
div className: "#{bn}__actions-group",
if @canResolve() && !@props.discussion.resolved
@renderReplyButton 'reply_resolve'
if @canReopen() && @props.discussion.resolved
@renderReplyButton 'reply_reopen'
@renderReplyButton 'reply'
renderCancelButton: =>
button
className: "#{bn}__action #{bn}__action--cancel"
disabled: @state.posting?
onClick: => @setState editing: false
i className: 'fas fa-times'
renderPlaceholder: =>
[text, icon] =
if @props.currentUser.id?
[osu.trans('beatmap_discussions.reply.open.user'), 'fas fa-reply']
else
[osu.trans('beatmap_discussions.reply.open.guest'), 'fas fa-sign-in-alt']
div
className: "#{bn} #{bn}--reply #{bn}--new-reply #{bn}--new-reply-placeholder"
el BigButton,
text: text
icon: icon
modifiers: ['beatmap-discussion-reply-open']
props:
onClick: @editStart
renderReplyButton: (action) =>
div className: "#{bn}__action",
el BigButton,
text: osu.trans("common.buttons.#{action}")
icon: ACTION_ICONS[action]
isBusy: @state.posting == action
props:
disabled: !@validPost() || @state.posting?
onClick: @throttledPost
'data-action': action
canReopen: =>
@props.discussion.can_be_resolved && @props.discussion.current_user_attributes.can_reopen
canResolve: =>
@props.discussion.can_be_resolved && @props.discussion.current_user_attributes.can_resolve
editStart: =>
if !@props.currentUser.id?
userLogin.show()
return
@setState editing: true, =>
@box.current?.focus()
handleKeyDownCallback: (type, event) =>
switch type
when InputHandler.CANCEL
@setState editing: false
when InputHandler.SUBMIT
@throttledPost(event)
isTimeline: =>
@props.discussion.timestamp?
post: (event) =>
return if !@validPost()
LoadingOverlay.show()
@postXhr?.abort()
# in case the event came from input box, do 'reply'.
action = event.currentTarget.dataset.action ? 'reply'
@setState posting: action
resolved = switch action
when 'reply_resolve' then true
when 'reply_reopen' then false
else null
@postXhr = $.ajax laroute.route('beatmap-discussion-posts.store'),
method: 'POST'
data:
beatmap_discussion_id: @props.discussion.id
beatmap_discussion:
# Only add resolved flag to beatmap_discussion if there was an
# explicit change (resolve/reopen).
if resolved?
resolved: resolved
else
{}
beatmap_discussion_post:
message: @state.message
.done (data) =>
@setState
message: ''
editing: false
$.publish 'beatmapDiscussionPost:markRead', id: data.beatmap_discussion_post_ids
$.publish 'beatmapsetDiscussions:update', beatmapset: data.beatmapset
.fail osu.ajaxError
.always =>
LoadingOverlay.hide()
@setState posting: null
setMessage: (e) =>
@setState message: e.target.value
validPost: =>
BeatmapDiscussionHelper.validMessageLength(@state.message, @isTimeline())
| true | # Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import { MessageLengthCounter } from './message-length-counter'
import { BigButton } from 'big-button'
import * as React from 'react'
import { button, div, form, input, label, span, i } from 'react-dom-factories'
import { UserAvatar } from 'user-avatar'
el = React.createElement
bn = 'beatmap-discussion-post'
export class NewReply extends React.PureComponent
ACTION_ICONS =
reply_resolve: 'fas fa-check'
reply_reopen: 'fas fa-exclamation-circle'
reply: 'fas fa-reply'
constructor: (props) ->
super props
@box = React.createRef()
@throttledPost = _.throttle @post, 1000
@handleKeyDown = InputHandler.textarea @handleKeyDownCallback
@state =
editing: false
message: ''
posting: null
componentWillUnmount: =>
@throttledPost.cancel()
@postXhr?.abort()
render: =>
if @state.editing
@renderBox()
else
@renderPlaceholder()
renderBox: =>
div
className: "#{bn} #{bn}--reply #{bn}--new-reply"
div
className: "#{bn}__content"
div className: "#{bn}__avatar",
el UserAvatar, user: @props.currentUser, modifiers: ['full-rounded']
@renderCancelButton()
div className: "#{bn}__message-container",
el TextareaAutosize,
disabled: @state.posting?
className: "#{bn}__message #{bn}__message--editor"
value: @state.message
onChange: @setMessage
onKeyDown: @handleKeyDown
placeholder: osu.trans 'beatmaps.discussions.reply_placeholder'
ref: @box
div
className: "#{bn}__footer #{bn}__footer--notice"
osu.trans 'beatmaps.discussions.reply_notice'
el MessageLengthCounter, message: @state.message, isTimeline: @isTimeline()
div
className: "#{bn}__footer"
div className: "#{bn}__actions",
div className: "#{bn}__actions-group",
if @canResolve() && !@props.discussion.resolved
@renderReplyButton 'reply_resolve'
if @canReopen() && @props.discussion.resolved
@renderReplyButton 'reply_reopen'
@renderReplyButton 'reply'
renderCancelButton: =>
button
className: "#{bn}__action #{bn}__action--cancel"
disabled: @state.posting?
onClick: => @setState editing: false
i className: 'fas fa-times'
renderPlaceholder: =>
[text, icon] =
if @props.currentUser.id?
[osu.trans('beatmap_discussions.reply.open.user'), 'fas fa-reply']
else
[osu.trans('beatmap_discussions.reply.open.guest'), 'fas fa-sign-in-alt']
div
className: "#{bn} #{bn}--reply #{bn}--new-reply #{bn}--new-reply-placeholder"
el BigButton,
text: text
icon: icon
modifiers: ['beatmap-discussion-reply-open']
props:
onClick: @editStart
renderReplyButton: (action) =>
div className: "#{bn}__action",
el BigButton,
text: osu.trans("common.buttons.#{action}")
icon: ACTION_ICONS[action]
isBusy: @state.posting == action
props:
disabled: !@validPost() || @state.posting?
onClick: @throttledPost
'data-action': action
canReopen: =>
@props.discussion.can_be_resolved && @props.discussion.current_user_attributes.can_reopen
canResolve: =>
@props.discussion.can_be_resolved && @props.discussion.current_user_attributes.can_resolve
editStart: =>
if !@props.currentUser.id?
userLogin.show()
return
@setState editing: true, =>
@box.current?.focus()
handleKeyDownCallback: (type, event) =>
switch type
when InputHandler.CANCEL
@setState editing: false
when InputHandler.SUBMIT
@throttledPost(event)
isTimeline: =>
@props.discussion.timestamp?
post: (event) =>
return if !@validPost()
LoadingOverlay.show()
@postXhr?.abort()
# in case the event came from input box, do 'reply'.
action = event.currentTarget.dataset.action ? 'reply'
@setState posting: action
resolved = switch action
when 'reply_resolve' then true
when 'reply_reopen' then false
else null
@postXhr = $.ajax laroute.route('beatmap-discussion-posts.store'),
method: 'POST'
data:
beatmap_discussion_id: @props.discussion.id
beatmap_discussion:
# Only add resolved flag to beatmap_discussion if there was an
# explicit change (resolve/reopen).
if resolved?
resolved: resolved
else
{}
beatmap_discussion_post:
message: @state.message
.done (data) =>
@setState
message: ''
editing: false
$.publish 'beatmapDiscussionPost:markRead', id: data.beatmap_discussion_post_ids
$.publish 'beatmapsetDiscussions:update', beatmapset: data.beatmapset
.fail osu.ajaxError
.always =>
LoadingOverlay.hide()
@setState posting: null
setMessage: (e) =>
@setState message: e.target.value
validPost: =>
BeatmapDiscussionHelper.validMessageLength(@state.message, @isTimeline())
|
[
{
"context": "xRequest\r\n \t\r\n Creates a new checklist.\r\n@author Nathan Klick\r\n@copyright QRef 2012\r\n###\r\nclass AircraftCheckli",
"end": 1000,
"score": 0.9998506307601929,
"start": 988,
"tag": "NAME",
"value": "Nathan Klick"
}
] | Workspace/QRef/NodeServer/src/router/routes/ajax/aircraft/AircraftChecklistsRoute.coffee | qrefdev/qref | 0 | AjaxRoute = require('../../../AjaxRoute')
AjaxResponse = require('../../../../serialization/AjaxResponse')
UserAuth = require('../../../../security/UserAuth')
QRefDatabase = require('../../../../db/QRefDatabase')
ChecklistManager = require('../../../../db/manager/ChecklistManager')
AircraftChecklistFilter = require('../../../../security/filters/AircraftChecklistFilter')
mongoose = require('mongoose')
ObjectId = mongoose.Types.ObjectId
###
Service route that allows the retrieval of all checklists and the creation of new checklists.
@example Service Methods (see {CreateAircraftChecklistAjaxRequest})
Request Format: application/json
Response Format: application/json
GET /services/ajax/aircraft/checklists?token=:token
:token - (Required) A valid authentication token.
Retrieves all checklists.
POST /services/ajax/aircraft/checklists
@BODY - (Required) CreateAircraftChecklistAjaxRequest
Creates a new checklist.
@author Nathan Klick
@copyright QRef 2012
###
class AircraftChecklistsRoute extends AjaxRoute
constructor: () ->
super [{ method: 'POST', path: '/checklists' }, { method: 'GET', path: '/checklists' }]
get: (req, res) =>
if not @.isValidRequest(req)
resp = new AjaxResponse()
resp.failure('Bad Request', 400)
res.json(resp, 200)
return
db = QRefDatabase.instance()
mgr = new ChecklistManager()
token = req.param('token')
filter = new AircraftChecklistFilter(token)
UserAuth.validateToken(token, (err, isTokenValid) ->
if err? or not isTokenValid == true
resp = new AjaxResponse()
resp.failure('Not Authorized', 403)
res.json(resp, 200)
return
filter.constrainQuery({}, (err, objQuery) ->
if err?
resp = new AjaxResponse()
resp.failure('Not Authorized', 403)
res.json(resp, 200)
return
if not objQuery?
resp = new AjaxResponse()
resp.failure('Not Authorized', 403)
res.json(resp, 200)
return
query = db.AircraftChecklist.find(objQuery)
if req.query?.pageSize? and req.query?.page?
query = query.skip(req.query.page * req.query.pageSize).limit(req.query.pageSize)
else if req.query?.pageSize? and not req.query?.page?
query = query.limit(req.query.pageSize)
else if not req.query?.pageSize? and req.query?.page?
query = query.skip(req.query.page * 25).limit(25)
query.exec((err, arrObjs) ->
if err?
resp = new AjaxResponse()
resp.failure('Internal Error', 500)
res.json(resp, 200)
return
db.AircraftChecklist.count((err, count) ->
if err?
resp = new AjaxResponse()
resp.failure('Internal Error', 500)
res.json(resp, 200)
return
#console.log('Expanding records.')
mgr.expandAll(arrObjs, (err, arrCheckLists) ->
if err?
resp = new AjaxResponse()
resp.failure('Internal Error', 500)
res.json(resp, 200)
return
#console.log('Returning expanded records.')
resp = new AjaxResponse()
resp.addRecords(arrCheckLists)
resp.setTotal(count)
res.json(resp, 200)
)
)
)
)
# Validate Admin Only Access
)
post: (req, res) =>
if not @.isValidRequest(req)
resp = new AjaxResponse()
resp.failure('Bad Request', 400)
res.json(resp, 200)
return
db = QRefDatabase.instance()
token = req.param('token')
filter = new AircraftChecklistFilter(token)
UserAuth.validateToken(token, (err, isTokenValid) ->
if err? or not isTokenValid == true
resp = new AjaxResponse()
resp.failure('Not Authorized', 403)
res.json(resp, 200)
return
filter.create((err, isAllowed) ->
if err?
resp = new AjaxResponse()
resp.failure('Not Authorized', 403)
res.json(resp, 200)
return
if not isAllowed
resp = new AjaxResponse()
resp.failure('Not Authorized', 403)
res.json(resp, 200)
return
newObj = new db.AircraftChecklist()
newObj.manufacturer = req.body.manufacturer
newObj.model = req.body.model
newObj.preflight = req.body.preflight
newObj.takeoff = req.body.takeoff
newObj.landing = req.body.landing
newObj.emergencies = req.body.emergencies
#newObj.modelYear = req.body.modelYear
if req.body?.tailNumber?
newObj.tailNumber = req.body.tailNumber
if req.body?.index?
newObj.index = req.body.index
if req.body?.user?
newObj.user = req.body.user
if req.body?.version?
newObj.version = req.body.version
else
newObj.version = 1
if req.body?.productIcon?
newObj.productIcon = req.body.productIcon
#if req.body?.coverImage?
# newObj.coverImage = req.body.coverImage
newObj.currentSerialNumber = 13956809037234
newObj.lastCheckpointSerialNumber = 13956809037234
newObj.knownSerialNumbers.push({ serialNumber: 13956809037234 , deviceName: 'SYSTEM', _id: new ObjectId() })
newObj.save((err) ->
if err?
resp = new AjaxResponse()
resp.failure(err, 500)
res.json(resp, 200)
return
resp = new AjaxResponse()
resp.setTotal(1)
resp.addRecord(newObj)
res.json(resp, 200)
)
)
# Validate Permissions Here
)
isValidRequest: (req) ->
if (req.query? and req.query?.token?) or
(req.body? and req.body?.token? and req.body?.model? and
req.body?.manufacturer? and req.body?.preflight? and req.body?.takeoff? and
req.body?.landing? and req.body?.emergencies? and
req.body?.mode? and req.body.mode == 'ajax')
true
else
false
module.exports = new AircraftChecklistsRoute() | 200638 | AjaxRoute = require('../../../AjaxRoute')
AjaxResponse = require('../../../../serialization/AjaxResponse')
UserAuth = require('../../../../security/UserAuth')
QRefDatabase = require('../../../../db/QRefDatabase')
ChecklistManager = require('../../../../db/manager/ChecklistManager')
AircraftChecklistFilter = require('../../../../security/filters/AircraftChecklistFilter')
mongoose = require('mongoose')
ObjectId = mongoose.Types.ObjectId
###
Service route that allows the retrieval of all checklists and the creation of new checklists.
@example Service Methods (see {CreateAircraftChecklistAjaxRequest})
Request Format: application/json
Response Format: application/json
GET /services/ajax/aircraft/checklists?token=:token
:token - (Required) A valid authentication token.
Retrieves all checklists.
POST /services/ajax/aircraft/checklists
@BODY - (Required) CreateAircraftChecklistAjaxRequest
Creates a new checklist.
@author <NAME>
@copyright QRef 2012
###
class AircraftChecklistsRoute extends AjaxRoute
constructor: () ->
super [{ method: 'POST', path: '/checklists' }, { method: 'GET', path: '/checklists' }]
get: (req, res) =>
if not @.isValidRequest(req)
resp = new AjaxResponse()
resp.failure('Bad Request', 400)
res.json(resp, 200)
return
db = QRefDatabase.instance()
mgr = new ChecklistManager()
token = req.param('token')
filter = new AircraftChecklistFilter(token)
UserAuth.validateToken(token, (err, isTokenValid) ->
if err? or not isTokenValid == true
resp = new AjaxResponse()
resp.failure('Not Authorized', 403)
res.json(resp, 200)
return
filter.constrainQuery({}, (err, objQuery) ->
if err?
resp = new AjaxResponse()
resp.failure('Not Authorized', 403)
res.json(resp, 200)
return
if not objQuery?
resp = new AjaxResponse()
resp.failure('Not Authorized', 403)
res.json(resp, 200)
return
query = db.AircraftChecklist.find(objQuery)
if req.query?.pageSize? and req.query?.page?
query = query.skip(req.query.page * req.query.pageSize).limit(req.query.pageSize)
else if req.query?.pageSize? and not req.query?.page?
query = query.limit(req.query.pageSize)
else if not req.query?.pageSize? and req.query?.page?
query = query.skip(req.query.page * 25).limit(25)
query.exec((err, arrObjs) ->
if err?
resp = new AjaxResponse()
resp.failure('Internal Error', 500)
res.json(resp, 200)
return
db.AircraftChecklist.count((err, count) ->
if err?
resp = new AjaxResponse()
resp.failure('Internal Error', 500)
res.json(resp, 200)
return
#console.log('Expanding records.')
mgr.expandAll(arrObjs, (err, arrCheckLists) ->
if err?
resp = new AjaxResponse()
resp.failure('Internal Error', 500)
res.json(resp, 200)
return
#console.log('Returning expanded records.')
resp = new AjaxResponse()
resp.addRecords(arrCheckLists)
resp.setTotal(count)
res.json(resp, 200)
)
)
)
)
# Validate Admin Only Access
)
post: (req, res) =>
if not @.isValidRequest(req)
resp = new AjaxResponse()
resp.failure('Bad Request', 400)
res.json(resp, 200)
return
db = QRefDatabase.instance()
token = req.param('token')
filter = new AircraftChecklistFilter(token)
UserAuth.validateToken(token, (err, isTokenValid) ->
if err? or not isTokenValid == true
resp = new AjaxResponse()
resp.failure('Not Authorized', 403)
res.json(resp, 200)
return
filter.create((err, isAllowed) ->
if err?
resp = new AjaxResponse()
resp.failure('Not Authorized', 403)
res.json(resp, 200)
return
if not isAllowed
resp = new AjaxResponse()
resp.failure('Not Authorized', 403)
res.json(resp, 200)
return
newObj = new db.AircraftChecklist()
newObj.manufacturer = req.body.manufacturer
newObj.model = req.body.model
newObj.preflight = req.body.preflight
newObj.takeoff = req.body.takeoff
newObj.landing = req.body.landing
newObj.emergencies = req.body.emergencies
#newObj.modelYear = req.body.modelYear
if req.body?.tailNumber?
newObj.tailNumber = req.body.tailNumber
if req.body?.index?
newObj.index = req.body.index
if req.body?.user?
newObj.user = req.body.user
if req.body?.version?
newObj.version = req.body.version
else
newObj.version = 1
if req.body?.productIcon?
newObj.productIcon = req.body.productIcon
#if req.body?.coverImage?
# newObj.coverImage = req.body.coverImage
newObj.currentSerialNumber = 13956809037234
newObj.lastCheckpointSerialNumber = 13956809037234
newObj.knownSerialNumbers.push({ serialNumber: 13956809037234 , deviceName: 'SYSTEM', _id: new ObjectId() })
newObj.save((err) ->
if err?
resp = new AjaxResponse()
resp.failure(err, 500)
res.json(resp, 200)
return
resp = new AjaxResponse()
resp.setTotal(1)
resp.addRecord(newObj)
res.json(resp, 200)
)
)
# Validate Permissions Here
)
isValidRequest: (req) ->
if (req.query? and req.query?.token?) or
(req.body? and req.body?.token? and req.body?.model? and
req.body?.manufacturer? and req.body?.preflight? and req.body?.takeoff? and
req.body?.landing? and req.body?.emergencies? and
req.body?.mode? and req.body.mode == 'ajax')
true
else
false
module.exports = new AircraftChecklistsRoute() | true | AjaxRoute = require('../../../AjaxRoute')
AjaxResponse = require('../../../../serialization/AjaxResponse')
UserAuth = require('../../../../security/UserAuth')
QRefDatabase = require('../../../../db/QRefDatabase')
ChecklistManager = require('../../../../db/manager/ChecklistManager')
AircraftChecklistFilter = require('../../../../security/filters/AircraftChecklistFilter')
mongoose = require('mongoose')
ObjectId = mongoose.Types.ObjectId
###
Service route that allows the retrieval of all checklists and the creation of new checklists.
@example Service Methods (see {CreateAircraftChecklistAjaxRequest})
Request Format: application/json
Response Format: application/json
GET /services/ajax/aircraft/checklists?token=:token
:token - (Required) A valid authentication token.
Retrieves all checklists.
POST /services/ajax/aircraft/checklists
@BODY - (Required) CreateAircraftChecklistAjaxRequest
Creates a new checklist.
@author PI:NAME:<NAME>END_PI
@copyright QRef 2012
###
class AircraftChecklistsRoute extends AjaxRoute
constructor: () ->
super [{ method: 'POST', path: '/checklists' }, { method: 'GET', path: '/checklists' }]
get: (req, res) =>
if not @.isValidRequest(req)
resp = new AjaxResponse()
resp.failure('Bad Request', 400)
res.json(resp, 200)
return
db = QRefDatabase.instance()
mgr = new ChecklistManager()
token = req.param('token')
filter = new AircraftChecklistFilter(token)
UserAuth.validateToken(token, (err, isTokenValid) ->
if err? or not isTokenValid == true
resp = new AjaxResponse()
resp.failure('Not Authorized', 403)
res.json(resp, 200)
return
filter.constrainQuery({}, (err, objQuery) ->
if err?
resp = new AjaxResponse()
resp.failure('Not Authorized', 403)
res.json(resp, 200)
return
if not objQuery?
resp = new AjaxResponse()
resp.failure('Not Authorized', 403)
res.json(resp, 200)
return
query = db.AircraftChecklist.find(objQuery)
if req.query?.pageSize? and req.query?.page?
query = query.skip(req.query.page * req.query.pageSize).limit(req.query.pageSize)
else if req.query?.pageSize? and not req.query?.page?
query = query.limit(req.query.pageSize)
else if not req.query?.pageSize? and req.query?.page?
query = query.skip(req.query.page * 25).limit(25)
query.exec((err, arrObjs) ->
if err?
resp = new AjaxResponse()
resp.failure('Internal Error', 500)
res.json(resp, 200)
return
db.AircraftChecklist.count((err, count) ->
if err?
resp = new AjaxResponse()
resp.failure('Internal Error', 500)
res.json(resp, 200)
return
#console.log('Expanding records.')
mgr.expandAll(arrObjs, (err, arrCheckLists) ->
if err?
resp = new AjaxResponse()
resp.failure('Internal Error', 500)
res.json(resp, 200)
return
#console.log('Returning expanded records.')
resp = new AjaxResponse()
resp.addRecords(arrCheckLists)
resp.setTotal(count)
res.json(resp, 200)
)
)
)
)
# Validate Admin Only Access
)
post: (req, res) =>
if not @.isValidRequest(req)
resp = new AjaxResponse()
resp.failure('Bad Request', 400)
res.json(resp, 200)
return
db = QRefDatabase.instance()
token = req.param('token')
filter = new AircraftChecklistFilter(token)
UserAuth.validateToken(token, (err, isTokenValid) ->
if err? or not isTokenValid == true
resp = new AjaxResponse()
resp.failure('Not Authorized', 403)
res.json(resp, 200)
return
filter.create((err, isAllowed) ->
if err?
resp = new AjaxResponse()
resp.failure('Not Authorized', 403)
res.json(resp, 200)
return
if not isAllowed
resp = new AjaxResponse()
resp.failure('Not Authorized', 403)
res.json(resp, 200)
return
newObj = new db.AircraftChecklist()
newObj.manufacturer = req.body.manufacturer
newObj.model = req.body.model
newObj.preflight = req.body.preflight
newObj.takeoff = req.body.takeoff
newObj.landing = req.body.landing
newObj.emergencies = req.body.emergencies
#newObj.modelYear = req.body.modelYear
if req.body?.tailNumber?
newObj.tailNumber = req.body.tailNumber
if req.body?.index?
newObj.index = req.body.index
if req.body?.user?
newObj.user = req.body.user
if req.body?.version?
newObj.version = req.body.version
else
newObj.version = 1
if req.body?.productIcon?
newObj.productIcon = req.body.productIcon
#if req.body?.coverImage?
# newObj.coverImage = req.body.coverImage
newObj.currentSerialNumber = 13956809037234
newObj.lastCheckpointSerialNumber = 13956809037234
newObj.knownSerialNumbers.push({ serialNumber: 13956809037234 , deviceName: 'SYSTEM', _id: new ObjectId() })
newObj.save((err) ->
if err?
resp = new AjaxResponse()
resp.failure(err, 500)
res.json(resp, 200)
return
resp = new AjaxResponse()
resp.setTotal(1)
resp.addRecord(newObj)
res.json(resp, 200)
)
)
# Validate Permissions Here
)
isValidRequest: (req) ->
if (req.query? and req.query?.token?) or
(req.body? and req.body?.token? and req.body?.model? and
req.body?.manufacturer? and req.body?.preflight? and req.body?.takeoff? and
req.body?.landing? and req.body?.emergencies? and
req.body?.mode? and req.body.mode == 'ajax')
true
else
false
module.exports = new AircraftChecklistsRoute() |
[
{
"context": "=========================================\n# Autor: Esteve Lladó (Fundació Bit), 2016\n# ==========================",
"end": 65,
"score": 0.9998823404312134,
"start": 53,
"tag": "NAME",
"value": "Esteve Lladó"
}
] | source/coffee/data_availability.coffee | Fundacio-Bit/twitter-intranet | 0 | # =========================================
# Autor: Esteve Lladó (Fundació Bit), 2016
# =========================================
# -----------------------------------------------------------
# Extrae disponibilidad de datos de la 'data admin' API REST
# -----------------------------------------------------------
getAvailableData = ->
leadZero = (number) -> ('0' + number).slice(-2) # helper para poner 0 delante del mes
date = new Date()
current_day = date.getDate()
current_month = date.getMonth() + 1 # importante sumar 1
current_year = date.getFullYear()
if current_day is 1
current_month -= 1
if current_month is 0
current_month = 12
current_year -= 1
year_month = "#{current_year}-#{leadZero(current_month)}"
request = "/rest_data_admin/availability/year_month/#{year_month}"
$.ajax({url: request, type: "GET"})
.done (data) ->
if data.error?
$('#availabilityPanel').html '<br>' + MyApp.templates.commonsRestApiError {message: data.error}
else
html_content = MyApp.templates.availDataTable {availGroups: data.results, year_month: data.year_month.toUpperCase()}
$('#availabilityPanel').html html_content
# ----------------------
# Ejecuciones al inicio
# ----------------------
(($) ->
$('#availabilityPanel').html '<br><br><br><p align="center">Bienvenido a la intranet de ESCOLTA ACTIVA / TWITTER</p>'
) jQuery
| 3349 | # =========================================
# Autor: <NAME> (Fundació Bit), 2016
# =========================================
# -----------------------------------------------------------
# Extrae disponibilidad de datos de la 'data admin' API REST
# -----------------------------------------------------------
getAvailableData = ->
leadZero = (number) -> ('0' + number).slice(-2) # helper para poner 0 delante del mes
date = new Date()
current_day = date.getDate()
current_month = date.getMonth() + 1 # importante sumar 1
current_year = date.getFullYear()
if current_day is 1
current_month -= 1
if current_month is 0
current_month = 12
current_year -= 1
year_month = "#{current_year}-#{leadZero(current_month)}"
request = "/rest_data_admin/availability/year_month/#{year_month}"
$.ajax({url: request, type: "GET"})
.done (data) ->
if data.error?
$('#availabilityPanel').html '<br>' + MyApp.templates.commonsRestApiError {message: data.error}
else
html_content = MyApp.templates.availDataTable {availGroups: data.results, year_month: data.year_month.toUpperCase()}
$('#availabilityPanel').html html_content
# ----------------------
# Ejecuciones al inicio
# ----------------------
(($) ->
$('#availabilityPanel').html '<br><br><br><p align="center">Bienvenido a la intranet de ESCOLTA ACTIVA / TWITTER</p>'
) jQuery
| true | # =========================================
# Autor: PI:NAME:<NAME>END_PI (Fundació Bit), 2016
# =========================================
# -----------------------------------------------------------
# Extrae disponibilidad de datos de la 'data admin' API REST
# -----------------------------------------------------------
getAvailableData = ->
leadZero = (number) -> ('0' + number).slice(-2) # helper para poner 0 delante del mes
date = new Date()
current_day = date.getDate()
current_month = date.getMonth() + 1 # importante sumar 1
current_year = date.getFullYear()
if current_day is 1
current_month -= 1
if current_month is 0
current_month = 12
current_year -= 1
year_month = "#{current_year}-#{leadZero(current_month)}"
request = "/rest_data_admin/availability/year_month/#{year_month}"
$.ajax({url: request, type: "GET"})
.done (data) ->
if data.error?
$('#availabilityPanel').html '<br>' + MyApp.templates.commonsRestApiError {message: data.error}
else
html_content = MyApp.templates.availDataTable {availGroups: data.results, year_month: data.year_month.toUpperCase()}
$('#availabilityPanel').html html_content
# ----------------------
# Ejecuciones al inicio
# ----------------------
(($) ->
$('#availabilityPanel').html '<br><br><br><p align="center">Bienvenido a la intranet de ESCOLTA ACTIVA / TWITTER</p>'
) jQuery
|
[
{
"context": " user = {\n id: 1,\n name: \"username\"\n }\n\n ctrl.searchUser(user)\n\n ",
"end": 2371,
"score": 0.9657618999481201,
"start": 2363,
"tag": "USERNAME",
"value": "username"
},
{
"context": " user = {\n id: 1,\n ... | app/modules/projects/create/import-project-members/import-project-members.controller.spec.coffee | threefoldtech/Threefold-Circles-front | 0 | ###
# Copyright (C) 2014-2018 Taiga Agile LLC
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: projects/create/import-project-members/import-project-members.controller.spec.coffee
###
describe "ImportProjectMembersCtrl", ->
$provide = null
$controller = null
mocks = {}
_mockCurrentUserService = ->
mocks.currentUserService = {
getUser: sinon.stub().returns(Immutable.fromJS({
id: 1
})),
canAddMembersPrivateProject: sinon.stub(),
canAddMembersPublicProject: sinon.stub()
}
$provide.value("tgCurrentUserService", mocks.currentUserService)
_mockUserService = ->
mocks.userService = {
getContacts: sinon.stub()
}
$provide.value("tgUserService", mocks.userService)
_inject = ->
inject (_$controller_) ->
$controller = _$controller_
_mocks = ->
module (_$provide_) ->
$provide = _$provide_
_mockCurrentUserService()
_mockUserService()
return null
_setup = ->
_mocks()
_inject()
beforeEach ->
module "taigaProjects"
_setup()
it "fetch user info", (done) ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.refreshSelectableUsers = sinon.spy()
mocks.userService.getContacts.withArgs(1).promise().resolve('contacts')
ctrl.fetchUser().then () ->
expect(ctrl.userContacts).to.be.equal('contacts')
expect(ctrl.refreshSelectableUsers).have.been.called
done()
it "search user", () ->
ctrl = $controller("ImportProjectMembersCtrl")
user = {
id: 1,
name: "username"
}
ctrl.searchUser(user)
expect(ctrl.selectImportUserLightbox).to.be.true
expect(ctrl.searchingUser).to.be.equal(user)
it "prepare submit users, warning if needed", () ->
ctrl = $controller("ImportProjectMembersCtrl")
user = {
id: 1,
name: "username"
}
ctrl.selectedUsers = Immutable.fromJS([
{id: 1},
{id: 2}
])
ctrl.members = Immutable.fromJS([
{id: 1}
])
ctrl.beforeSubmitUsers()
expect(ctrl.warningImportUsers).to.be.true
it "prepare submit users, submit", () ->
ctrl = $controller("ImportProjectMembersCtrl")
user = {
id: 1,
name: "username"
}
ctrl.selectedUsers = Immutable.fromJS([
{id: 1}
])
ctrl.members = Immutable.fromJS([
{id: 1}
])
ctrl.submit = sinon.spy()
ctrl.beforeSubmitUsers()
expect(ctrl.warningImportUsers).to.be.false
expect(ctrl.submit).have.been.called
it "confirm user", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.discardSuggestedUser = sinon.spy()
ctrl.refreshSelectableUsers = sinon.spy()
ctrl.confirmUser('user', 'taiga-user')
expect(ctrl.selectedUsers.size).to.be.equal(1)
expect(ctrl.selectedUsers.get(0).get('user')).to.be.equal('user')
expect(ctrl.selectedUsers.get(0).get('taigaUser')).to.be.equal('taiga-user')
expect(ctrl.discardSuggestedUser).have.been.called
expect(ctrl.refreshSelectableUsers).have.been.called
it "discard suggested user", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.discardSuggestedUser(Immutable.fromJS({
id: 3
}))
expect(ctrl.cancelledUsers.get(0)).to.be.equal(3)
it "clean member selection", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.refreshSelectableUsers = sinon.spy()
ctrl.selectedUsers = Immutable.fromJS([
{
user: {
id: 1
}
},
{
user: {
id: 2
}
}
])
ctrl.unselectUser(Immutable.fromJS({
id: 2
}))
expect(ctrl.selectedUsers.size).to.be.equal(1)
expect(ctrl.refreshSelectableUsers).have.been.called
it "get a selected member", () ->
ctrl = $controller("ImportProjectMembersCtrl")
member = Immutable.fromJS({
id: 3
})
ctrl.selectedUsers = ctrl.selectedUsers.push(Immutable.fromJS({
user: {
id: 3
}
}))
user = ctrl.getSelectedMember(member)
expect(user.getIn(['user', 'id'])).to.be.equal(3)
it "submit", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.selectedUsers = ctrl.selectedUsers.push(Immutable.fromJS({
user: {
id: 3
},
taigaUser: {
id: 2
}
}))
ctrl.selectedUsers = ctrl.selectedUsers.push(Immutable.fromJS({
user: {
id: 3
},
taigaUser: "xx@yy.com"
}))
ctrl.onSubmit = sinon.stub()
ctrl.submit()
user = Immutable.Map()
user = user.set(3, 2)
expect(ctrl.onSubmit).have.been.called
expect(ctrl.warningImportUsers).to.be.false
it "show suggested match", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.isMemberSelected = sinon.stub().returns(false)
ctrl.cancelledUsers = [
3
]
member = Immutable.fromJS({
id: 1,
user: {
id: 10
}
})
expect(ctrl.showSuggestedMatch(member)).to.be.true
it "doesn't show suggested match", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.isMemberSelected = sinon.stub().returns(false)
ctrl.cancelledUsers = [
3
]
member = Immutable.fromJS({
id: 3,
user: {
id: 10
}
})
expect(ctrl.showSuggestedMatch(member)).to.be.false
it "check users limit", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.members = Immutable.fromJS([
1, 2, 3
])
mocks.currentUserService.canAddMembersPrivateProject.withArgs(4).returns('xx')
mocks.currentUserService.canAddMembersPublicProject.withArgs(4).returns('yy')
ctrl.checkUsersLimit()
expect(ctrl.limitMembersPrivateProject).to.be.equal('xx')
expect(ctrl.limitMembersPublicProject).to.be.equal('yy')
it "get distict select taiga users excluding the current user", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.selectedUsers = Immutable.fromJS([
{
taigaUser: {
id: 1
}
},
{
taigaUser: {
id: 1
}
},
{
taigaUser: {
id: 3
}
},
{
taigaUser: {
id: 5
}
}
])
ctrl.currentUser = Immutable.fromJS({
id: 5
})
users = ctrl.getDistinctSelectedTaigaUsers()
expect(users.size).to.be.equal(2)
it "refresh selectable users array with all users available", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.isImportMoreUsersDisabled = sinon.stub().returns(false)
ctrl.displayEmailSelector = false
ctrl.userContacts = Immutable.fromJS([1])
ctrl.currentUser = 2
ctrl.refreshSelectableUsers()
expect(ctrl.selectableUsers.toJS()).to.be.eql([1, 2])
expect(ctrl.displayEmailSelector).to.be.true
it "refresh selectable users array with the selected ones", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.getDistinctSelectedTaigaUsers = sinon.stub().returns(Immutable.fromJS([
{taigaUser: 1}
]))
ctrl.displayEmailSelector = false
ctrl.isImportMoreUsersDisabled = sinon.stub().returns(true)
ctrl.userContacts = Immutable.fromJS([1])
ctrl.currentUser = 2
ctrl.refreshSelectableUsers()
expect(ctrl.selectableUsers.toJS()).to.be.eql([1, 2])
expect(ctrl.displayEmailSelector).to.be.false
it "import more user disable in private project", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.project = Immutable.fromJS({
is_private: true
})
ctrl.getDistinctSelectedTaigaUsers = sinon.stub().returns(Immutable.fromJS([1,2,3]))
mocks.currentUserService.canAddMembersPrivateProject.withArgs(5).returns({valid: true})
expect(ctrl.isImportMoreUsersDisabled()).to.be.false
it "import more user disable in public project", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.project = Immutable.fromJS({
is_private: false
})
ctrl.getDistinctSelectedTaigaUsers = sinon.stub().returns(Immutable.fromJS([1,2,3]))
mocks.currentUserService.canAddMembersPublicProject.withArgs(5).returns({valid: true})
expect(ctrl.isImportMoreUsersDisabled()).to.be.false
| 225986 | ###
# Copyright (C) 2014-2018 Taiga Agile LLC
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: projects/create/import-project-members/import-project-members.controller.spec.coffee
###
describe "ImportProjectMembersCtrl", ->
$provide = null
$controller = null
mocks = {}
_mockCurrentUserService = ->
mocks.currentUserService = {
getUser: sinon.stub().returns(Immutable.fromJS({
id: 1
})),
canAddMembersPrivateProject: sinon.stub(),
canAddMembersPublicProject: sinon.stub()
}
$provide.value("tgCurrentUserService", mocks.currentUserService)
_mockUserService = ->
mocks.userService = {
getContacts: sinon.stub()
}
$provide.value("tgUserService", mocks.userService)
_inject = ->
inject (_$controller_) ->
$controller = _$controller_
_mocks = ->
module (_$provide_) ->
$provide = _$provide_
_mockCurrentUserService()
_mockUserService()
return null
_setup = ->
_mocks()
_inject()
beforeEach ->
module "taigaProjects"
_setup()
it "fetch user info", (done) ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.refreshSelectableUsers = sinon.spy()
mocks.userService.getContacts.withArgs(1).promise().resolve('contacts')
ctrl.fetchUser().then () ->
expect(ctrl.userContacts).to.be.equal('contacts')
expect(ctrl.refreshSelectableUsers).have.been.called
done()
it "search user", () ->
ctrl = $controller("ImportProjectMembersCtrl")
user = {
id: 1,
name: "username"
}
ctrl.searchUser(user)
expect(ctrl.selectImportUserLightbox).to.be.true
expect(ctrl.searchingUser).to.be.equal(user)
it "prepare submit users, warning if needed", () ->
ctrl = $controller("ImportProjectMembersCtrl")
user = {
id: 1,
name: "username"
}
ctrl.selectedUsers = Immutable.fromJS([
{id: 1},
{id: 2}
])
ctrl.members = Immutable.fromJS([
{id: 1}
])
ctrl.beforeSubmitUsers()
expect(ctrl.warningImportUsers).to.be.true
it "prepare submit users, submit", () ->
ctrl = $controller("ImportProjectMembersCtrl")
user = {
id: 1,
name: "username"
}
ctrl.selectedUsers = Immutable.fromJS([
{id: 1}
])
ctrl.members = Immutable.fromJS([
{id: 1}
])
ctrl.submit = sinon.spy()
ctrl.beforeSubmitUsers()
expect(ctrl.warningImportUsers).to.be.false
expect(ctrl.submit).have.been.called
it "confirm user", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.discardSuggestedUser = sinon.spy()
ctrl.refreshSelectableUsers = sinon.spy()
ctrl.confirmUser('user', 'taiga-user')
expect(ctrl.selectedUsers.size).to.be.equal(1)
expect(ctrl.selectedUsers.get(0).get('user')).to.be.equal('user')
expect(ctrl.selectedUsers.get(0).get('taigaUser')).to.be.equal('taiga-user')
expect(ctrl.discardSuggestedUser).have.been.called
expect(ctrl.refreshSelectableUsers).have.been.called
it "discard suggested user", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.discardSuggestedUser(Immutable.fromJS({
id: 3
}))
expect(ctrl.cancelledUsers.get(0)).to.be.equal(3)
it "clean member selection", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.refreshSelectableUsers = sinon.spy()
ctrl.selectedUsers = Immutable.fromJS([
{
user: {
id: 1
}
},
{
user: {
id: 2
}
}
])
ctrl.unselectUser(Immutable.fromJS({
id: 2
}))
expect(ctrl.selectedUsers.size).to.be.equal(1)
expect(ctrl.refreshSelectableUsers).have.been.called
it "get a selected member", () ->
ctrl = $controller("ImportProjectMembersCtrl")
member = Immutable.fromJS({
id: 3
})
ctrl.selectedUsers = ctrl.selectedUsers.push(Immutable.fromJS({
user: {
id: 3
}
}))
user = ctrl.getSelectedMember(member)
expect(user.getIn(['user', 'id'])).to.be.equal(3)
it "submit", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.selectedUsers = ctrl.selectedUsers.push(Immutable.fromJS({
user: {
id: 3
},
taigaUser: {
id: 2
}
}))
ctrl.selectedUsers = ctrl.selectedUsers.push(Immutable.fromJS({
user: {
id: 3
},
taigaUser: "<EMAIL>"
}))
ctrl.onSubmit = sinon.stub()
ctrl.submit()
user = Immutable.Map()
user = user.set(3, 2)
expect(ctrl.onSubmit).have.been.called
expect(ctrl.warningImportUsers).to.be.false
it "show suggested match", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.isMemberSelected = sinon.stub().returns(false)
ctrl.cancelledUsers = [
3
]
member = Immutable.fromJS({
id: 1,
user: {
id: 10
}
})
expect(ctrl.showSuggestedMatch(member)).to.be.true
it "doesn't show suggested match", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.isMemberSelected = sinon.stub().returns(false)
ctrl.cancelledUsers = [
3
]
member = Immutable.fromJS({
id: 3,
user: {
id: 10
}
})
expect(ctrl.showSuggestedMatch(member)).to.be.false
it "check users limit", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.members = Immutable.fromJS([
1, 2, 3
])
mocks.currentUserService.canAddMembersPrivateProject.withArgs(4).returns('xx')
mocks.currentUserService.canAddMembersPublicProject.withArgs(4).returns('yy')
ctrl.checkUsersLimit()
expect(ctrl.limitMembersPrivateProject).to.be.equal('xx')
expect(ctrl.limitMembersPublicProject).to.be.equal('yy')
it "get distict select taiga users excluding the current user", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.selectedUsers = Immutable.fromJS([
{
taigaUser: {
id: 1
}
},
{
taigaUser: {
id: 1
}
},
{
taigaUser: {
id: 3
}
},
{
taigaUser: {
id: 5
}
}
])
ctrl.currentUser = Immutable.fromJS({
id: 5
})
users = ctrl.getDistinctSelectedTaigaUsers()
expect(users.size).to.be.equal(2)
it "refresh selectable users array with all users available", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.isImportMoreUsersDisabled = sinon.stub().returns(false)
ctrl.displayEmailSelector = false
ctrl.userContacts = Immutable.fromJS([1])
ctrl.currentUser = 2
ctrl.refreshSelectableUsers()
expect(ctrl.selectableUsers.toJS()).to.be.eql([1, 2])
expect(ctrl.displayEmailSelector).to.be.true
it "refresh selectable users array with the selected ones", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.getDistinctSelectedTaigaUsers = sinon.stub().returns(Immutable.fromJS([
{taigaUser: 1}
]))
ctrl.displayEmailSelector = false
ctrl.isImportMoreUsersDisabled = sinon.stub().returns(true)
ctrl.userContacts = Immutable.fromJS([1])
ctrl.currentUser = 2
ctrl.refreshSelectableUsers()
expect(ctrl.selectableUsers.toJS()).to.be.eql([1, 2])
expect(ctrl.displayEmailSelector).to.be.false
it "import more user disable in private project", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.project = Immutable.fromJS({
is_private: true
})
ctrl.getDistinctSelectedTaigaUsers = sinon.stub().returns(Immutable.fromJS([1,2,3]))
mocks.currentUserService.canAddMembersPrivateProject.withArgs(5).returns({valid: true})
expect(ctrl.isImportMoreUsersDisabled()).to.be.false
it "import more user disable in public project", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.project = Immutable.fromJS({
is_private: false
})
ctrl.getDistinctSelectedTaigaUsers = sinon.stub().returns(Immutable.fromJS([1,2,3]))
mocks.currentUserService.canAddMembersPublicProject.withArgs(5).returns({valid: true})
expect(ctrl.isImportMoreUsersDisabled()).to.be.false
| true | ###
# Copyright (C) 2014-2018 Taiga Agile LLC
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: projects/create/import-project-members/import-project-members.controller.spec.coffee
###
describe "ImportProjectMembersCtrl", ->
$provide = null
$controller = null
mocks = {}
_mockCurrentUserService = ->
mocks.currentUserService = {
getUser: sinon.stub().returns(Immutable.fromJS({
id: 1
})),
canAddMembersPrivateProject: sinon.stub(),
canAddMembersPublicProject: sinon.stub()
}
$provide.value("tgCurrentUserService", mocks.currentUserService)
_mockUserService = ->
mocks.userService = {
getContacts: sinon.stub()
}
$provide.value("tgUserService", mocks.userService)
_inject = ->
inject (_$controller_) ->
$controller = _$controller_
_mocks = ->
module (_$provide_) ->
$provide = _$provide_
_mockCurrentUserService()
_mockUserService()
return null
_setup = ->
_mocks()
_inject()
beforeEach ->
module "taigaProjects"
_setup()
it "fetch user info", (done) ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.refreshSelectableUsers = sinon.spy()
mocks.userService.getContacts.withArgs(1).promise().resolve('contacts')
ctrl.fetchUser().then () ->
expect(ctrl.userContacts).to.be.equal('contacts')
expect(ctrl.refreshSelectableUsers).have.been.called
done()
it "search user", () ->
ctrl = $controller("ImportProjectMembersCtrl")
user = {
id: 1,
name: "username"
}
ctrl.searchUser(user)
expect(ctrl.selectImportUserLightbox).to.be.true
expect(ctrl.searchingUser).to.be.equal(user)
it "prepare submit users, warning if needed", () ->
ctrl = $controller("ImportProjectMembersCtrl")
user = {
id: 1,
name: "username"
}
ctrl.selectedUsers = Immutable.fromJS([
{id: 1},
{id: 2}
])
ctrl.members = Immutable.fromJS([
{id: 1}
])
ctrl.beforeSubmitUsers()
expect(ctrl.warningImportUsers).to.be.true
it "prepare submit users, submit", () ->
ctrl = $controller("ImportProjectMembersCtrl")
user = {
id: 1,
name: "username"
}
ctrl.selectedUsers = Immutable.fromJS([
{id: 1}
])
ctrl.members = Immutable.fromJS([
{id: 1}
])
ctrl.submit = sinon.spy()
ctrl.beforeSubmitUsers()
expect(ctrl.warningImportUsers).to.be.false
expect(ctrl.submit).have.been.called
it "confirm user", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.discardSuggestedUser = sinon.spy()
ctrl.refreshSelectableUsers = sinon.spy()
ctrl.confirmUser('user', 'taiga-user')
expect(ctrl.selectedUsers.size).to.be.equal(1)
expect(ctrl.selectedUsers.get(0).get('user')).to.be.equal('user')
expect(ctrl.selectedUsers.get(0).get('taigaUser')).to.be.equal('taiga-user')
expect(ctrl.discardSuggestedUser).have.been.called
expect(ctrl.refreshSelectableUsers).have.been.called
it "discard suggested user", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.discardSuggestedUser(Immutable.fromJS({
id: 3
}))
expect(ctrl.cancelledUsers.get(0)).to.be.equal(3)
it "clean member selection", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.refreshSelectableUsers = sinon.spy()
ctrl.selectedUsers = Immutable.fromJS([
{
user: {
id: 1
}
},
{
user: {
id: 2
}
}
])
ctrl.unselectUser(Immutable.fromJS({
id: 2
}))
expect(ctrl.selectedUsers.size).to.be.equal(1)
expect(ctrl.refreshSelectableUsers).have.been.called
it "get a selected member", () ->
ctrl = $controller("ImportProjectMembersCtrl")
member = Immutable.fromJS({
id: 3
})
ctrl.selectedUsers = ctrl.selectedUsers.push(Immutable.fromJS({
user: {
id: 3
}
}))
user = ctrl.getSelectedMember(member)
expect(user.getIn(['user', 'id'])).to.be.equal(3)
it "submit", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.selectedUsers = ctrl.selectedUsers.push(Immutable.fromJS({
user: {
id: 3
},
taigaUser: {
id: 2
}
}))
ctrl.selectedUsers = ctrl.selectedUsers.push(Immutable.fromJS({
user: {
id: 3
},
taigaUser: "PI:EMAIL:<EMAIL>END_PI"
}))
ctrl.onSubmit = sinon.stub()
ctrl.submit()
user = Immutable.Map()
user = user.set(3, 2)
expect(ctrl.onSubmit).have.been.called
expect(ctrl.warningImportUsers).to.be.false
it "show suggested match", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.isMemberSelected = sinon.stub().returns(false)
ctrl.cancelledUsers = [
3
]
member = Immutable.fromJS({
id: 1,
user: {
id: 10
}
})
expect(ctrl.showSuggestedMatch(member)).to.be.true
it "doesn't show suggested match", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.isMemberSelected = sinon.stub().returns(false)
ctrl.cancelledUsers = [
3
]
member = Immutable.fromJS({
id: 3,
user: {
id: 10
}
})
expect(ctrl.showSuggestedMatch(member)).to.be.false
it "check users limit", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.members = Immutable.fromJS([
1, 2, 3
])
mocks.currentUserService.canAddMembersPrivateProject.withArgs(4).returns('xx')
mocks.currentUserService.canAddMembersPublicProject.withArgs(4).returns('yy')
ctrl.checkUsersLimit()
expect(ctrl.limitMembersPrivateProject).to.be.equal('xx')
expect(ctrl.limitMembersPublicProject).to.be.equal('yy')
it "get distict select taiga users excluding the current user", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.selectedUsers = Immutable.fromJS([
{
taigaUser: {
id: 1
}
},
{
taigaUser: {
id: 1
}
},
{
taigaUser: {
id: 3
}
},
{
taigaUser: {
id: 5
}
}
])
ctrl.currentUser = Immutable.fromJS({
id: 5
})
users = ctrl.getDistinctSelectedTaigaUsers()
expect(users.size).to.be.equal(2)
it "refresh selectable users array with all users available", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.isImportMoreUsersDisabled = sinon.stub().returns(false)
ctrl.displayEmailSelector = false
ctrl.userContacts = Immutable.fromJS([1])
ctrl.currentUser = 2
ctrl.refreshSelectableUsers()
expect(ctrl.selectableUsers.toJS()).to.be.eql([1, 2])
expect(ctrl.displayEmailSelector).to.be.true
it "refresh selectable users array with the selected ones", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.getDistinctSelectedTaigaUsers = sinon.stub().returns(Immutable.fromJS([
{taigaUser: 1}
]))
ctrl.displayEmailSelector = false
ctrl.isImportMoreUsersDisabled = sinon.stub().returns(true)
ctrl.userContacts = Immutable.fromJS([1])
ctrl.currentUser = 2
ctrl.refreshSelectableUsers()
expect(ctrl.selectableUsers.toJS()).to.be.eql([1, 2])
expect(ctrl.displayEmailSelector).to.be.false
it "import more user disable in private project", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.project = Immutable.fromJS({
is_private: true
})
ctrl.getDistinctSelectedTaigaUsers = sinon.stub().returns(Immutable.fromJS([1,2,3]))
mocks.currentUserService.canAddMembersPrivateProject.withArgs(5).returns({valid: true})
expect(ctrl.isImportMoreUsersDisabled()).to.be.false
it "import more user disable in public project", () ->
ctrl = $controller("ImportProjectMembersCtrl")
ctrl.project = Immutable.fromJS({
is_private: false
})
ctrl.getDistinctSelectedTaigaUsers = sinon.stub().returns(Immutable.fromJS([1,2,3]))
mocks.currentUserService.canAddMembersPublicProject.withArgs(5).returns({valid: true})
expect(ctrl.isImportMoreUsersDisabled()).to.be.false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.