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": "defined\", () ->\n user = {id: 1, name: \"fake1\"}\n\n currentUserService.setUser = sinon",
"end": 2368,
"score": 0.8567046523094177,
"start": 2363,
"tag": "USERNAME",
"value": "fake1"
},
{
"context": "->\n user = Immutable.fromJS({id: 1, na... | app/modules/services/current-user.service.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: services/current-user.service.spec.coffee
###
describe "tgCurrentUserService", ->
currentUserService = provide = null
mocks = {}
_mockTgStorage = () ->
mocks.storageService = {
get: sinon.stub()
}
provide.value "$tgStorage", mocks.storageService
_mockProjectsService = () ->
mocks.projectsService = {
getProjectsByUserId: sinon.stub()
getListProjectsByUserId: sinon.stub()
bulkUpdateProjectsOrder: sinon.stub()
}
provide.value "tgProjectsService", mocks.projectsService
_mockResources = () ->
mocks.resources = {
user: {
setUserStorage: sinon.stub(),
getUserStorage: sinon.stub(),
createUserStorage: sinon.stub()
}
}
provide.value "tgResources", mocks.resources
_inject = (callback) ->
inject (_tgCurrentUserService_) ->
currentUserService = _tgCurrentUserService_
callback() if callback
_mocks = () ->
module ($provide) ->
provide = $provide
_mockTgStorage()
_mockProjectsService()
_mockResources()
return null
_setup = ->
_mocks()
beforeEach ->
module "taigaCommon"
_setup()
_inject()
describe "get user", () ->
it "return the user if it is defined", () ->
currentUserService._user = 123
expect(currentUserService.getUser()).to.be.equal(123)
it "get user form storage if it is not defined", () ->
user = {id: 1, name: "fake1"}
currentUserService.setUser = sinon.spy()
mocks.storageService.get.withArgs("userInfo").returns(user)
_user = currentUserService.getUser()
expect(currentUserService.setUser).to.be.calledOnce
it "set user and load user info", (done) ->
user = Immutable.fromJS({id: 1, name: "fake1"})
projects = Immutable.fromJS([
{id: 1, name: "fake1"},
{id: 2, name: "fake2"},
{id: 3, name: "fake3"},
{id: 4, name: "fake4"},
{id: 5, name: "fake5"}
])
mocks.projectsService.getListProjectsByUserId = sinon.stub()
mocks.projectsService.getListProjectsByUserId.withArgs(user.get("id")).promise().resolve(projects)
currentUserService.setUser(user).then () ->
expect(currentUserService._user).to.be.equal(user)
expect(currentUserService.projects.get("all").size).to.be.equal(5)
expect(currentUserService.projects.get("recents").size).to.be.equal(5)
expect(currentUserService.projectsById.size).to.be.equal(5)
expect(currentUserService.projectsById.get("3").get("name")).to.be.equal("fake3")
done()
it "bulkUpdateProjectsOrder and reload projects", (done) ->
fakeData = [{id: 1, id: 2}]
currentUserService.loadProjects = sinon.stub()
mocks.projectsService.bulkUpdateProjectsOrder.withArgs(fakeData).promise().resolve()
currentUserService.bulkUpdateProjectsOrder(fakeData).then () ->
expect(currentUserService.loadProjects).to.be.callOnce
done()
it "loadProject and set it", (done) ->
user = Immutable.fromJS({id: 1, name: "fake1"})
project = Immutable.fromJS({id: 2, name: "fake2"})
currentUserService._user = user
currentUserService.setProjects = sinon.stub()
mocks.projectsService.getListProjectsByUserId.withArgs(1).promise().resolve(project)
currentUserService.loadProjectsList().then () ->
expect(currentUserService.setProjects).to.have.been.calledWith(project)
done()
it "setProject", () ->
projectsRaw = [
{id: 1, name: "fake1"},
{id: 2, name: "fake2"},
{id: 3, name: "fake3"},
{id: 4, name: "fake4"}
]
projectsRawById = {
1: {id: 1, name: "fake1"},
2: {id: 2, name: "fake2"},
3: {id: 3, name: "fake3"},
4: {id: 4, name: "fake4"}
}
projects = Immutable.fromJS(projectsRaw)
currentUserService.setProjects(projects)
expect(currentUserService.projects.get('all').toJS()).to.be.eql(projectsRaw)
expect(currentUserService.projects.get('recents').toJS()).to.be.eql(projectsRaw)
expect(currentUserService.projectsById.toJS()).to.be.eql(projectsRawById)
it "is authenticated", () ->
currentUserService.getUser = sinon.stub()
currentUserService.getUser.returns({})
expect(currentUserService.isAuthenticated()).to.be.true
currentUserService.getUser.returns(null)
expect(currentUserService.isAuthenticated()).to.be.false
it "remove user", () ->
currentUserService._user = true
currentUserService.removeUser()
expect(currentUserService._user).to.be.null
it "disable joyride for anon user", () ->
currentUserService.isAuthenticated = sinon.stub()
currentUserService.isAuthenticated.returns(false)
currentUserService.disableJoyRide()
expect(mocks.resources.user.setUserStorage).to.have.not.been.called
it "disable joyride for logged user", () ->
currentUserService.isAuthenticated = sinon.stub()
currentUserService.isAuthenticated.returns(true)
currentUserService.disableJoyRide()
expect(mocks.resources.user.setUserStorage).to.have.been.calledWith('joyride', {
backlog: false,
kanban: false,
dashboard: false
})
it "load joyride config", (done) ->
mocks.resources.user.getUserStorage.withArgs('joyride').promise().resolve(true)
currentUserService.loadJoyRideConfig().then (config) ->
expect(config).to.be.true
done()
it "create default joyride config", (done) ->
mocks.resources.user.getUserStorage.withArgs('joyride').promise().reject(new Error('error'))
currentUserService.loadJoyRideConfig().then (config) ->
joyride = {
backlog: true,
kanban: true,
dashboard: true
}
expect(mocks.resources.user.createUserStorage).to.have.been.calledWith('joyride', joyride)
expect(config).to.be.eql(joyride)
done()
it "the user can't create private projects if they reach the maximum number of private projects", () ->
user = Immutable.fromJS({
id: 1,
name: "fake1",
max_private_projects: 1,
total_private_projects: 1
})
currentUserService._user = user
result = currentUserService.canCreatePrivateProjects()
expect(result).to.be.eql({
valid: false,
reason: 'max_private_projects',
type: 'private_project',
current: 1,
max: 1
})
it "the user can create private projects", () ->
user = Immutable.fromJS({
id: 1,
name: "fake1",
max_private_projects: 10,
total_private_projects: 1,
max_memberships_private_projects: 20
})
currentUserService._user = user
result = currentUserService.canCreatePrivateProjects(10)
expect(result).to.be.eql({
valid: true
})
it "the user can't create public projects if they reach the maximum number of private projects", () ->
user = Immutable.fromJS({
id: 1,
name: "fake1",
max_public_projects: 1,
total_public_projects: 1
})
currentUserService._user = user
result = currentUserService.canCreatePublicProjects(0)
expect(result).to.be.eql({
valid: false,
reason: 'max_public_projects',
type: 'public_project',
current: 1,
max: 1
})
it "the user can create public projects", () ->
user = Immutable.fromJS({
id: 1,
name: "fake1",
max_public_projects: 10,
total_public_projects: 1,
max_memberships_public_projects: 20
})
currentUserService._user = user
result = currentUserService.canCreatePublicProjects(10)
expect(result).to.be.eql({
valid: true
})
it "the user can own public project", () ->
user = Immutable.fromJS({
id: 1,
name: "fake1",
max_public_projects: 10,
total_public_projects: 1,
max_memberships_public_projects: 20
})
currentUserService._user = user
project = Immutable.fromJS({
id: 2,
name: "fake2",
total_memberships: 5,
is_private: false
})
result = currentUserService.canOwnProject(project)
expect(result).to.be.eql({
valid: true
})
it "the user can't own public project because of max projects", () ->
user = Immutable.fromJS({
id: 1,
name: "fake1",
max_public_projects: 1,
total_public_projects: 1,
max_memberships_public_projects: 20
})
currentUserService._user = user
project = Immutable.fromJS({
id: 2,
name: "fake2",
total_memberships: 5,
is_private: false
})
result = currentUserService.canOwnProject(project)
expect(result).to.be.eql({
valid: false
reason: 'max_public_projects'
type: 'public_project',
current: 1,
max: 1
})
it "the user can't own public project because of max memberships", () ->
user = Immutable.fromJS({
id: 1,
name: "fake1",
max_public_projects: 5,
total_public_projects: 1,
max_memberships_public_projects: 4
})
currentUserService._user = user
project = Immutable.fromJS({
id: 2,
name: "fake2",
total_memberships: 5,
is_private: false
})
result = currentUserService.canOwnProject(project)
expect(result).to.be.eql({
valid: false
reason: 'max_members_public_projects'
type: 'public_project',
current: 5,
max: 4
})
it "the user can own private project", () ->
user = Immutable.fromJS({
id: 1,
name: "fake1",
max_private_projects: 10,
total_private_projects: 1,
max_memberships_private_projects: 20
})
currentUserService._user = user
project = Immutable.fromJS({
id: 2,
name: "fake2",
total_memberships: 5,
is_private: true
})
result = currentUserService.canOwnProject(project)
expect(result).to.be.eql({
valid: true
})
it "the user can't own private project because of max projects", () ->
user = Immutable.fromJS({
id: 1,
name: "fake1",
max_private_projects: 1,
total_private_projects: 1,
max_memberships_private_projects: 20
})
currentUserService._user = user
project = Immutable.fromJS({
id: 2,
name: "fake2",
total_memberships: 5,
is_private: true
})
result = currentUserService.canOwnProject(project)
expect(result).to.be.eql({
valid: false
reason: 'max_private_projects'
type: 'private_project',
current: 1,
max: 1
})
it "the user can't own private project because of max memberships", () ->
user = Immutable.fromJS({
id: 1,
name: "fake1",
max_private_projects: 10,
total_private_projects: 1,
max_memberships_private_projects: 4
})
currentUserService._user = user
project = Immutable.fromJS({
id: 2,
name: "fake2",
total_memberships: 5,
is_private: true
})
result = currentUserService.canOwnProject(project)
expect(result).to.be.eql({
valid: false
reason: 'max_members_private_projects'
type: 'private_project',
current: 5,
max: 4
})
| 37095 | ###
# 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: services/current-user.service.spec.coffee
###
describe "tgCurrentUserService", ->
currentUserService = provide = null
mocks = {}
_mockTgStorage = () ->
mocks.storageService = {
get: sinon.stub()
}
provide.value "$tgStorage", mocks.storageService
_mockProjectsService = () ->
mocks.projectsService = {
getProjectsByUserId: sinon.stub()
getListProjectsByUserId: sinon.stub()
bulkUpdateProjectsOrder: sinon.stub()
}
provide.value "tgProjectsService", mocks.projectsService
_mockResources = () ->
mocks.resources = {
user: {
setUserStorage: sinon.stub(),
getUserStorage: sinon.stub(),
createUserStorage: sinon.stub()
}
}
provide.value "tgResources", mocks.resources
_inject = (callback) ->
inject (_tgCurrentUserService_) ->
currentUserService = _tgCurrentUserService_
callback() if callback
_mocks = () ->
module ($provide) ->
provide = $provide
_mockTgStorage()
_mockProjectsService()
_mockResources()
return null
_setup = ->
_mocks()
beforeEach ->
module "taigaCommon"
_setup()
_inject()
describe "get user", () ->
it "return the user if it is defined", () ->
currentUserService._user = 123
expect(currentUserService.getUser()).to.be.equal(123)
it "get user form storage if it is not defined", () ->
user = {id: 1, name: "fake1"}
currentUserService.setUser = sinon.spy()
mocks.storageService.get.withArgs("userInfo").returns(user)
_user = currentUserService.getUser()
expect(currentUserService.setUser).to.be.calledOnce
it "set user and load user info", (done) ->
user = Immutable.fromJS({id: 1, name: "fake1"})
projects = Immutable.fromJS([
{id: 1, name: "<NAME>1"},
{id: 2, name: "<NAME>"},
{id: 3, name: "<NAME>3"},
{id: 4, name: "<NAME>4"},
{id: 5, name: "fake5"}
])
mocks.projectsService.getListProjectsByUserId = sinon.stub()
mocks.projectsService.getListProjectsByUserId.withArgs(user.get("id")).promise().resolve(projects)
currentUserService.setUser(user).then () ->
expect(currentUserService._user).to.be.equal(user)
expect(currentUserService.projects.get("all").size).to.be.equal(5)
expect(currentUserService.projects.get("recents").size).to.be.equal(5)
expect(currentUserService.projectsById.size).to.be.equal(5)
expect(currentUserService.projectsById.get("3").get("name")).to.be.equal("fake3")
done()
it "bulkUpdateProjectsOrder and reload projects", (done) ->
fakeData = [{id: 1, id: 2}]
currentUserService.loadProjects = sinon.stub()
mocks.projectsService.bulkUpdateProjectsOrder.withArgs(fakeData).promise().resolve()
currentUserService.bulkUpdateProjectsOrder(fakeData).then () ->
expect(currentUserService.loadProjects).to.be.callOnce
done()
it "loadProject and set it", (done) ->
user = Immutable.fromJS({id: 1, name: "fake1"})
project = Immutable.fromJS({id: 2, name: "fake2"})
currentUserService._user = user
currentUserService.setProjects = sinon.stub()
mocks.projectsService.getListProjectsByUserId.withArgs(1).promise().resolve(project)
currentUserService.loadProjectsList().then () ->
expect(currentUserService.setProjects).to.have.been.calledWith(project)
done()
it "setProject", () ->
projectsRaw = [
{id: 1, name: "fake1"},
{id: 2, name: "fake2"},
{id: 3, name: "fake3"},
{id: 4, name: "fake4"}
]
projectsRawById = {
1: {id: 1, name: "fake1"},
2: {id: 2, name: "fake2"},
3: {id: 3, name: "fake3"},
4: {id: 4, name: "fake4"}
}
projects = Immutable.fromJS(projectsRaw)
currentUserService.setProjects(projects)
expect(currentUserService.projects.get('all').toJS()).to.be.eql(projectsRaw)
expect(currentUserService.projects.get('recents').toJS()).to.be.eql(projectsRaw)
expect(currentUserService.projectsById.toJS()).to.be.eql(projectsRawById)
it "is authenticated", () ->
currentUserService.getUser = sinon.stub()
currentUserService.getUser.returns({})
expect(currentUserService.isAuthenticated()).to.be.true
currentUserService.getUser.returns(null)
expect(currentUserService.isAuthenticated()).to.be.false
it "remove user", () ->
currentUserService._user = true
currentUserService.removeUser()
expect(currentUserService._user).to.be.null
it "disable joyride for anon user", () ->
currentUserService.isAuthenticated = sinon.stub()
currentUserService.isAuthenticated.returns(false)
currentUserService.disableJoyRide()
expect(mocks.resources.user.setUserStorage).to.have.not.been.called
it "disable joyride for logged user", () ->
currentUserService.isAuthenticated = sinon.stub()
currentUserService.isAuthenticated.returns(true)
currentUserService.disableJoyRide()
expect(mocks.resources.user.setUserStorage).to.have.been.calledWith('joyride', {
backlog: false,
kanban: false,
dashboard: false
})
it "load joyride config", (done) ->
mocks.resources.user.getUserStorage.withArgs('joyride').promise().resolve(true)
currentUserService.loadJoyRideConfig().then (config) ->
expect(config).to.be.true
done()
it "create default joyride config", (done) ->
mocks.resources.user.getUserStorage.withArgs('joyride').promise().reject(new Error('error'))
currentUserService.loadJoyRideConfig().then (config) ->
joyride = {
backlog: true,
kanban: true,
dashboard: true
}
expect(mocks.resources.user.createUserStorage).to.have.been.calledWith('joyride', joyride)
expect(config).to.be.eql(joyride)
done()
it "the user can't create private projects if they reach the maximum number of private projects", () ->
user = Immutable.fromJS({
id: 1,
name: "<NAME>1",
max_private_projects: 1,
total_private_projects: 1
})
currentUserService._user = user
result = currentUserService.canCreatePrivateProjects()
expect(result).to.be.eql({
valid: false,
reason: 'max_private_projects',
type: 'private_project',
current: 1,
max: 1
})
it "the user can create private projects", () ->
user = Immutable.fromJS({
id: 1,
name: "<NAME>1",
max_private_projects: 10,
total_private_projects: 1,
max_memberships_private_projects: 20
})
currentUserService._user = user
result = currentUserService.canCreatePrivateProjects(10)
expect(result).to.be.eql({
valid: true
})
it "the user can't create public projects if they reach the maximum number of private projects", () ->
user = Immutable.fromJS({
id: 1,
name: "<NAME>1",
max_public_projects: 1,
total_public_projects: 1
})
currentUserService._user = user
result = currentUserService.canCreatePublicProjects(0)
expect(result).to.be.eql({
valid: false,
reason: 'max_public_projects',
type: 'public_project',
current: 1,
max: 1
})
it "the user can create public projects", () ->
user = Immutable.fromJS({
id: 1,
name: "<NAME>",
max_public_projects: 10,
total_public_projects: 1,
max_memberships_public_projects: 20
})
currentUserService._user = user
result = currentUserService.canCreatePublicProjects(10)
expect(result).to.be.eql({
valid: true
})
it "the user can own public project", () ->
user = Immutable.fromJS({
id: 1,
name: "<NAME>",
max_public_projects: 10,
total_public_projects: 1,
max_memberships_public_projects: 20
})
currentUserService._user = user
project = Immutable.fromJS({
id: 2,
name: "<NAME>",
total_memberships: 5,
is_private: false
})
result = currentUserService.canOwnProject(project)
expect(result).to.be.eql({
valid: true
})
it "the user can't own public project because of max projects", () ->
user = Immutable.fromJS({
id: 1,
name: "<NAME>",
max_public_projects: 1,
total_public_projects: 1,
max_memberships_public_projects: 20
})
currentUserService._user = user
project = Immutable.fromJS({
id: 2,
name: "<NAME>",
total_memberships: 5,
is_private: false
})
result = currentUserService.canOwnProject(project)
expect(result).to.be.eql({
valid: false
reason: 'max_public_projects'
type: 'public_project',
current: 1,
max: 1
})
it "the user can't own public project because of max memberships", () ->
user = Immutable.fromJS({
id: 1,
name: "<NAME>",
max_public_projects: 5,
total_public_projects: 1,
max_memberships_public_projects: 4
})
currentUserService._user = user
project = Immutable.fromJS({
id: 2,
name: "<NAME>",
total_memberships: 5,
is_private: false
})
result = currentUserService.canOwnProject(project)
expect(result).to.be.eql({
valid: false
reason: 'max_members_public_projects'
type: 'public_project',
current: 5,
max: 4
})
it "the user can own private project", () ->
user = Immutable.fromJS({
id: 1,
name: "<NAME>",
max_private_projects: 10,
total_private_projects: 1,
max_memberships_private_projects: 20
})
currentUserService._user = user
project = Immutable.fromJS({
id: 2,
name: "<NAME>",
total_memberships: 5,
is_private: true
})
result = currentUserService.canOwnProject(project)
expect(result).to.be.eql({
valid: true
})
it "the user can't own private project because of max projects", () ->
user = Immutable.fromJS({
id: 1,
name: "<NAME>",
max_private_projects: 1,
total_private_projects: 1,
max_memberships_private_projects: 20
})
currentUserService._user = user
project = Immutable.fromJS({
id: 2,
name: "<NAME>",
total_memberships: 5,
is_private: true
})
result = currentUserService.canOwnProject(project)
expect(result).to.be.eql({
valid: false
reason: 'max_private_projects'
type: 'private_project',
current: 1,
max: 1
})
it "the user can't own private project because of max memberships", () ->
user = Immutable.fromJS({
id: 1,
name: "<NAME>",
max_private_projects: 10,
total_private_projects: 1,
max_memberships_private_projects: 4
})
currentUserService._user = user
project = Immutable.fromJS({
id: 2,
name: "fake2",
total_memberships: 5,
is_private: true
})
result = currentUserService.canOwnProject(project)
expect(result).to.be.eql({
valid: false
reason: 'max_members_private_projects'
type: 'private_project',
current: 5,
max: 4
})
| 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: services/current-user.service.spec.coffee
###
describe "tgCurrentUserService", ->
currentUserService = provide = null
mocks = {}
_mockTgStorage = () ->
mocks.storageService = {
get: sinon.stub()
}
provide.value "$tgStorage", mocks.storageService
_mockProjectsService = () ->
mocks.projectsService = {
getProjectsByUserId: sinon.stub()
getListProjectsByUserId: sinon.stub()
bulkUpdateProjectsOrder: sinon.stub()
}
provide.value "tgProjectsService", mocks.projectsService
_mockResources = () ->
mocks.resources = {
user: {
setUserStorage: sinon.stub(),
getUserStorage: sinon.stub(),
createUserStorage: sinon.stub()
}
}
provide.value "tgResources", mocks.resources
_inject = (callback) ->
inject (_tgCurrentUserService_) ->
currentUserService = _tgCurrentUserService_
callback() if callback
_mocks = () ->
module ($provide) ->
provide = $provide
_mockTgStorage()
_mockProjectsService()
_mockResources()
return null
_setup = ->
_mocks()
beforeEach ->
module "taigaCommon"
_setup()
_inject()
describe "get user", () ->
it "return the user if it is defined", () ->
currentUserService._user = 123
expect(currentUserService.getUser()).to.be.equal(123)
it "get user form storage if it is not defined", () ->
user = {id: 1, name: "fake1"}
currentUserService.setUser = sinon.spy()
mocks.storageService.get.withArgs("userInfo").returns(user)
_user = currentUserService.getUser()
expect(currentUserService.setUser).to.be.calledOnce
it "set user and load user info", (done) ->
user = Immutable.fromJS({id: 1, name: "fake1"})
projects = Immutable.fromJS([
{id: 1, name: "PI:NAME:<NAME>END_PI1"},
{id: 2, name: "PI:NAME:<NAME>END_PI"},
{id: 3, name: "PI:NAME:<NAME>END_PI3"},
{id: 4, name: "PI:NAME:<NAME>END_PI4"},
{id: 5, name: "fake5"}
])
mocks.projectsService.getListProjectsByUserId = sinon.stub()
mocks.projectsService.getListProjectsByUserId.withArgs(user.get("id")).promise().resolve(projects)
currentUserService.setUser(user).then () ->
expect(currentUserService._user).to.be.equal(user)
expect(currentUserService.projects.get("all").size).to.be.equal(5)
expect(currentUserService.projects.get("recents").size).to.be.equal(5)
expect(currentUserService.projectsById.size).to.be.equal(5)
expect(currentUserService.projectsById.get("3").get("name")).to.be.equal("fake3")
done()
it "bulkUpdateProjectsOrder and reload projects", (done) ->
fakeData = [{id: 1, id: 2}]
currentUserService.loadProjects = sinon.stub()
mocks.projectsService.bulkUpdateProjectsOrder.withArgs(fakeData).promise().resolve()
currentUserService.bulkUpdateProjectsOrder(fakeData).then () ->
expect(currentUserService.loadProjects).to.be.callOnce
done()
it "loadProject and set it", (done) ->
user = Immutable.fromJS({id: 1, name: "fake1"})
project = Immutable.fromJS({id: 2, name: "fake2"})
currentUserService._user = user
currentUserService.setProjects = sinon.stub()
mocks.projectsService.getListProjectsByUserId.withArgs(1).promise().resolve(project)
currentUserService.loadProjectsList().then () ->
expect(currentUserService.setProjects).to.have.been.calledWith(project)
done()
it "setProject", () ->
projectsRaw = [
{id: 1, name: "fake1"},
{id: 2, name: "fake2"},
{id: 3, name: "fake3"},
{id: 4, name: "fake4"}
]
projectsRawById = {
1: {id: 1, name: "fake1"},
2: {id: 2, name: "fake2"},
3: {id: 3, name: "fake3"},
4: {id: 4, name: "fake4"}
}
projects = Immutable.fromJS(projectsRaw)
currentUserService.setProjects(projects)
expect(currentUserService.projects.get('all').toJS()).to.be.eql(projectsRaw)
expect(currentUserService.projects.get('recents').toJS()).to.be.eql(projectsRaw)
expect(currentUserService.projectsById.toJS()).to.be.eql(projectsRawById)
it "is authenticated", () ->
currentUserService.getUser = sinon.stub()
currentUserService.getUser.returns({})
expect(currentUserService.isAuthenticated()).to.be.true
currentUserService.getUser.returns(null)
expect(currentUserService.isAuthenticated()).to.be.false
it "remove user", () ->
currentUserService._user = true
currentUserService.removeUser()
expect(currentUserService._user).to.be.null
it "disable joyride for anon user", () ->
currentUserService.isAuthenticated = sinon.stub()
currentUserService.isAuthenticated.returns(false)
currentUserService.disableJoyRide()
expect(mocks.resources.user.setUserStorage).to.have.not.been.called
it "disable joyride for logged user", () ->
currentUserService.isAuthenticated = sinon.stub()
currentUserService.isAuthenticated.returns(true)
currentUserService.disableJoyRide()
expect(mocks.resources.user.setUserStorage).to.have.been.calledWith('joyride', {
backlog: false,
kanban: false,
dashboard: false
})
it "load joyride config", (done) ->
mocks.resources.user.getUserStorage.withArgs('joyride').promise().resolve(true)
currentUserService.loadJoyRideConfig().then (config) ->
expect(config).to.be.true
done()
it "create default joyride config", (done) ->
mocks.resources.user.getUserStorage.withArgs('joyride').promise().reject(new Error('error'))
currentUserService.loadJoyRideConfig().then (config) ->
joyride = {
backlog: true,
kanban: true,
dashboard: true
}
expect(mocks.resources.user.createUserStorage).to.have.been.calledWith('joyride', joyride)
expect(config).to.be.eql(joyride)
done()
it "the user can't create private projects if they reach the maximum number of private projects", () ->
user = Immutable.fromJS({
id: 1,
name: "PI:NAME:<NAME>END_PI1",
max_private_projects: 1,
total_private_projects: 1
})
currentUserService._user = user
result = currentUserService.canCreatePrivateProjects()
expect(result).to.be.eql({
valid: false,
reason: 'max_private_projects',
type: 'private_project',
current: 1,
max: 1
})
it "the user can create private projects", () ->
user = Immutable.fromJS({
id: 1,
name: "PI:NAME:<NAME>END_PI1",
max_private_projects: 10,
total_private_projects: 1,
max_memberships_private_projects: 20
})
currentUserService._user = user
result = currentUserService.canCreatePrivateProjects(10)
expect(result).to.be.eql({
valid: true
})
it "the user can't create public projects if they reach the maximum number of private projects", () ->
user = Immutable.fromJS({
id: 1,
name: "PI:NAME:<NAME>END_PI1",
max_public_projects: 1,
total_public_projects: 1
})
currentUserService._user = user
result = currentUserService.canCreatePublicProjects(0)
expect(result).to.be.eql({
valid: false,
reason: 'max_public_projects',
type: 'public_project',
current: 1,
max: 1
})
it "the user can create public projects", () ->
user = Immutable.fromJS({
id: 1,
name: "PI:NAME:<NAME>END_PI",
max_public_projects: 10,
total_public_projects: 1,
max_memberships_public_projects: 20
})
currentUserService._user = user
result = currentUserService.canCreatePublicProjects(10)
expect(result).to.be.eql({
valid: true
})
it "the user can own public project", () ->
user = Immutable.fromJS({
id: 1,
name: "PI:NAME:<NAME>END_PI",
max_public_projects: 10,
total_public_projects: 1,
max_memberships_public_projects: 20
})
currentUserService._user = user
project = Immutable.fromJS({
id: 2,
name: "PI:NAME:<NAME>END_PI",
total_memberships: 5,
is_private: false
})
result = currentUserService.canOwnProject(project)
expect(result).to.be.eql({
valid: true
})
it "the user can't own public project because of max projects", () ->
user = Immutable.fromJS({
id: 1,
name: "PI:NAME:<NAME>END_PI",
max_public_projects: 1,
total_public_projects: 1,
max_memberships_public_projects: 20
})
currentUserService._user = user
project = Immutable.fromJS({
id: 2,
name: "PI:NAME:<NAME>END_PI",
total_memberships: 5,
is_private: false
})
result = currentUserService.canOwnProject(project)
expect(result).to.be.eql({
valid: false
reason: 'max_public_projects'
type: 'public_project',
current: 1,
max: 1
})
it "the user can't own public project because of max memberships", () ->
user = Immutable.fromJS({
id: 1,
name: "PI:NAME:<NAME>END_PI",
max_public_projects: 5,
total_public_projects: 1,
max_memberships_public_projects: 4
})
currentUserService._user = user
project = Immutable.fromJS({
id: 2,
name: "PI:NAME:<NAME>END_PI",
total_memberships: 5,
is_private: false
})
result = currentUserService.canOwnProject(project)
expect(result).to.be.eql({
valid: false
reason: 'max_members_public_projects'
type: 'public_project',
current: 5,
max: 4
})
it "the user can own private project", () ->
user = Immutable.fromJS({
id: 1,
name: "PI:NAME:<NAME>END_PI",
max_private_projects: 10,
total_private_projects: 1,
max_memberships_private_projects: 20
})
currentUserService._user = user
project = Immutable.fromJS({
id: 2,
name: "PI:NAME:<NAME>END_PI",
total_memberships: 5,
is_private: true
})
result = currentUserService.canOwnProject(project)
expect(result).to.be.eql({
valid: true
})
it "the user can't own private project because of max projects", () ->
user = Immutable.fromJS({
id: 1,
name: "PI:NAME:<NAME>END_PI",
max_private_projects: 1,
total_private_projects: 1,
max_memberships_private_projects: 20
})
currentUserService._user = user
project = Immutable.fromJS({
id: 2,
name: "PI:NAME:<NAME>END_PI",
total_memberships: 5,
is_private: true
})
result = currentUserService.canOwnProject(project)
expect(result).to.be.eql({
valid: false
reason: 'max_private_projects'
type: 'private_project',
current: 1,
max: 1
})
it "the user can't own private project because of max memberships", () ->
user = Immutable.fromJS({
id: 1,
name: "PI:NAME:<NAME>END_PI",
max_private_projects: 10,
total_private_projects: 1,
max_memberships_private_projects: 4
})
currentUserService._user = user
project = Immutable.fromJS({
id: 2,
name: "fake2",
total_memberships: 5,
is_private: true
})
result = currentUserService.canOwnProject(project)
expect(result).to.be.eql({
valid: false
reason: 'max_members_private_projects'
type: 'private_project',
current: 5,
max: 4
})
|
[
{
"context": "pt.apply(hasher, arguments)\n @\n password = mnemonicPhrase.normalize('NFKD')\n salt = \"mnemonic\" + passphrase.normalize('N",
"end": 2427,
"score": 0.838266134262085,
"start": 2397,
"tag": "PASSWORD",
"value": "mnemonicPhrase.normalize('NFKD"
},
{
"context"... | app/src/bitcoin/bip39.coffee | romanornr/ledger-wallet-crw | 173 | ledger.bitcoin ?= {}
ledger.bitcoin.bip39 ?= {}
Bip39 = ledger.bitcoin.bip39
_.extend ledger.bitcoin.bip39,
ENTROPY_BIT_LENGTH: 256
DEFAULT_PHRASE_LENGTH: 24
# @param [String] mnemonicWords Mnemonic words.
# @return [Array] Mnemonic words in the phrase.
isMnemonicPhraseValid: (mnemonicPhrase) ->
try
@utils.checkMnemonicPhraseValid(mnemonicPhrase) && true
catch e
false
# @return [String]
generateEntropy: (entropyBitLength = @ENTROPY_BIT_LENGTH) ->
entropyBytesArray = new Uint8Array(entropyBitLength / 8)
crypto.getRandomValues(entropyBytesArray)
@utils._bytesArrayToHexString(entropyBytesArray)
# @param [string] entropy A hexadecimal string.
# @return [string] Mnemonic phrase. Phrase may contains 12 to 24 words depending of entropy length.
entropyToMnemonicPhrase: (entropy) ->
throw "Invalid entropy format. Wait a hexadecimal string" if ! entropy.match(/^[0-9a-fA-F]+$/)
throw "Invalid entropy length: #{entropy.length*4}" if entropy.length % 8 != 0
# Compute checksum
entropyIntegersArray = entropy.match(/[0-9a-fA-F]{8}/g).map (h) -> parseInt(h,16)
hashedEntropyIntegersArray = sjcl.hash.sha256.hash entropyIntegersArray
hashedEntropy = hashedEntropyIntegersArray.map((i) => @utils._intToBin(i,32)).join('')
# 1 checksum bit per 32 bits of entropy.
binChecksum = hashedEntropy.slice(0,entropyIntegersArray.length)
binEntropy = entropyIntegersArray.map((i) => @utils._intToBin(i,32)).join('')
binMnemonic = binEntropy + binChecksum
throw "Invalid binMnemonic length : #{binMnemonic.length}" if binMnemonic.length % 11 != 0
mnemonicIndexes = binMnemonic.match(/[01]{11}/g).map (b) -> parseInt(b,2)
mnemonicWords = mnemonicIndexes.map (idx) => @wordlist[idx]
mnemonicWords.join(' ')
# @return [String]
generateMnemonicPhrase: (phraseLength=@DEFAULT_PHRASE_LENGTH) ->
entropyBitLength = phraseLength * 32 / 3
@entropyToMnemonicPhrase(@generateEntropy(entropyBitLength))
# @param [String] mnemonicWords Mnemonic words.
# @return [Array] Mnemonic words in the phrase.
mnemonicPhraseToSeed: (mnemonicPhrase, passphrase="") ->
@utils.checkMnemonicPhraseValid(mnemonicPhrase)
hmacSHA512 = (key) ->
hasher = new sjcl.misc.hmac(key, sjcl.hash.sha512)
@encrypt = ->
return hasher.encrypt.apply(hasher, arguments)
@
password = mnemonicPhrase.normalize('NFKD')
salt = "mnemonic" + passphrase.normalize('NFKD')
passwordBits = sjcl.codec.utf8String.toBits(password)
saltBits = sjcl.codec.utf8String.toBits(salt)
result = sjcl.misc.pbkdf2(passwordBits, saltBits, 2048, 512, hmacSHA512)
hashHex = sjcl.codec.hex.fromBits(result)
return hashHex
mnemonicPhraseToWordIndexes: (mnemonicPhrase) ->
(ledger.bitcoin.bip39.wordlist.indexOf(word) for word in mnemonicPhrase.split(' '))
utils:
BITS_IN_INTEGER: 8 * 4
checkMnemonicPhraseValid: (mnemonicPhrase) ->
mnemonicWords = @mnemonicWordsFromPhrase(mnemonicPhrase)
if mnemonicWords.length != ledger.bitcoin.bip39.DEFAULT_PHRASE_LENGTH
throw "Invalid mnemonic length: #{mnemonicWords.length}"
mnemonicIndexes = @mnemonicWordsToIndexes(mnemonicWords)
if mnemonicIndexes.length % 3 != 0
throw "Invalid mnemonic length : #{mnemonicIndexes.length}"
if mnemonicIndexes.indexOf(-1) != -1
word = mnemonicPhrase.trim().split(' ')[mnemonicIndexes.indexOf(-1)]
throw "Invalid mnemonic word : #{word}"
mnemonicBin = @mnemonicIndexesToBin(mnemonicIndexes)
[binEntropy, binChecksum] = @splitMnemonicBin(mnemonicBin)
if ! @checkEntropyChecksum(binEntropy, binChecksum)
throw "Checksum error."
return true
# Do not check if mnemonic words are valids.
# @param [String] mnemonicPhrase A mnemonic phrase.
# @return [Array] Mnemonic words in the phrase.
mnemonicWordsFromPhrase: (mnemonicPhrase="") ->
mnemonicPhrase = _.str.clean(mnemonicPhrase)
mnemonicPhrase.trim().split(/\ /)
# @param [String] mnemonicWord
# @return [Integer] Index of mnemonicWord in wordlist
mnemonicWordToIndex: (mnemonicWord) ->
Bip39.wordlist.indexOf(mnemonicWord)
# @param [Array] mnemonicWords
# @return [Array] Indexes of each mnemonicWord in wordlist
mnemonicWordsToIndexes: (mnemonicWords) ->
@mnemonicWordToIndex(mnemonicWord) for mnemonicWord in mnemonicWords
# @return [Array] Return entropy bits and checksum bits.
splitMnemonicBin: (mnemonicBin) ->
# There is a checksum bit for each 33 bits (= 3 mnemonics word) slice.
[mnemonicBin.slice(0, -(mnemonicBin.length/33)), mnemonicBin.slice(-(mnemonicBin.length/33))]
checkEntropyChecksum: (entropyBin, checksumBin) ->
integersEntropy = entropyBin.match(/[01]{32}/g).map (s) -> parseInt(s,2)
hashedIntegersEntropy = sjcl.hash.sha256.hash integersEntropy
hashedEntropyBinaryArray = hashedIntegersEntropy.map (s) => @_intToBin(s, @BITS_IN_INTEGER)
computedChecksumBin = hashedEntropyBinaryArray.join('').slice(0, checksumBin.length)
return computedChecksumBin == checksumBin
mnemonicIndexToBin: (mnemonicIndex) ->
@_intToBin(mnemonicIndex, 11)
mnemonicIndexesToBin: (mnemonicIndexes) ->
(@mnemonicIndexToBin(index) for index in mnemonicIndexes).join('')
# Do not check if mnemonic phrase is valid.
# @param [String] mnemonicPhrase A mnemonic phrase.
# @return [Integer] The number of mnemonic word in the phrase.
mnemonicPhraseWordsLength: (mnemonicPhrase) ->
@mnemonicWordsFromPhrase(mnemonicPhrase).length
# @param [String] mnemonicWord A mnemonic word.
# @return [Boolean] Return true if mnemonic word is in wordlist
isMnemonicWordValid: (mnemonicWord) ->
@mnemonicWordToIndex(mnemonicWord) != -1
# Just check if each mnemonic word is valid.
# Do not check checksum, length, etc.
# @param [Array] mnemonicWords An array of mnemonic words.
# @return [Boolean] Return true if each mnemonic word is in wordlist
isMnemonicWordsValid: (mnemonicWords) ->
_.every(mnemonicWords, (word) => @isMnemonicWordValid(word))
_intToBin: (int, binLength) ->
int += 1 if int < 0
str = int.toString(2)
str = str.replace("-","0").replace(/0/g,'a').replace(/1/g,'0').replace(/a/g,'1') if int < 0
str = (if int < 0 then '1' else '0') + str while str.length < binLength
str
_bytesArrayToHexString: (bytesArray) ->
(_.str.lpad(byte.toString(16), 2, '0') for byte in bytesArray).join('')
| 112582 | ledger.bitcoin ?= {}
ledger.bitcoin.bip39 ?= {}
Bip39 = ledger.bitcoin.bip39
_.extend ledger.bitcoin.bip39,
ENTROPY_BIT_LENGTH: 256
DEFAULT_PHRASE_LENGTH: 24
# @param [String] mnemonicWords Mnemonic words.
# @return [Array] Mnemonic words in the phrase.
isMnemonicPhraseValid: (mnemonicPhrase) ->
try
@utils.checkMnemonicPhraseValid(mnemonicPhrase) && true
catch e
false
# @return [String]
generateEntropy: (entropyBitLength = @ENTROPY_BIT_LENGTH) ->
entropyBytesArray = new Uint8Array(entropyBitLength / 8)
crypto.getRandomValues(entropyBytesArray)
@utils._bytesArrayToHexString(entropyBytesArray)
# @param [string] entropy A hexadecimal string.
# @return [string] Mnemonic phrase. Phrase may contains 12 to 24 words depending of entropy length.
entropyToMnemonicPhrase: (entropy) ->
throw "Invalid entropy format. Wait a hexadecimal string" if ! entropy.match(/^[0-9a-fA-F]+$/)
throw "Invalid entropy length: #{entropy.length*4}" if entropy.length % 8 != 0
# Compute checksum
entropyIntegersArray = entropy.match(/[0-9a-fA-F]{8}/g).map (h) -> parseInt(h,16)
hashedEntropyIntegersArray = sjcl.hash.sha256.hash entropyIntegersArray
hashedEntropy = hashedEntropyIntegersArray.map((i) => @utils._intToBin(i,32)).join('')
# 1 checksum bit per 32 bits of entropy.
binChecksum = hashedEntropy.slice(0,entropyIntegersArray.length)
binEntropy = entropyIntegersArray.map((i) => @utils._intToBin(i,32)).join('')
binMnemonic = binEntropy + binChecksum
throw "Invalid binMnemonic length : #{binMnemonic.length}" if binMnemonic.length % 11 != 0
mnemonicIndexes = binMnemonic.match(/[01]{11}/g).map (b) -> parseInt(b,2)
mnemonicWords = mnemonicIndexes.map (idx) => @wordlist[idx]
mnemonicWords.join(' ')
# @return [String]
generateMnemonicPhrase: (phraseLength=@DEFAULT_PHRASE_LENGTH) ->
entropyBitLength = phraseLength * 32 / 3
@entropyToMnemonicPhrase(@generateEntropy(entropyBitLength))
# @param [String] mnemonicWords Mnemonic words.
# @return [Array] Mnemonic words in the phrase.
mnemonicPhraseToSeed: (mnemonicPhrase, passphrase="") ->
@utils.checkMnemonicPhraseValid(mnemonicPhrase)
hmacSHA512 = (key) ->
hasher = new sjcl.misc.hmac(key, sjcl.hash.sha512)
@encrypt = ->
return hasher.encrypt.apply(hasher, arguments)
@
password = <PASSWORD>')
salt = "<PASSWORD>" + passphrase.normalize('N<PASSWORD>')
passwordBits = sjcl.codec.utf8String.toBits(password)
saltBits = sjcl.codec.utf8String.toBits(salt)
result = sjcl.misc.pbkdf2(passwordBits, saltBits, 2048, 512, hmacSHA512)
hashHex = sjcl.codec.hex.fromBits(result)
return hashHex
mnemonicPhraseToWordIndexes: (mnemonicPhrase) ->
(ledger.bitcoin.bip39.wordlist.indexOf(word) for word in mnemonicPhrase.split(' '))
utils:
BITS_IN_INTEGER: 8 * 4
checkMnemonicPhraseValid: (mnemonicPhrase) ->
mnemonicWords = @mnemonicWordsFromPhrase(mnemonicPhrase)
if mnemonicWords.length != ledger.bitcoin.bip39.DEFAULT_PHRASE_LENGTH
throw "Invalid mnemonic length: #{mnemonicWords.length}"
mnemonicIndexes = @mnemonicWordsToIndexes(mnemonicWords)
if mnemonicIndexes.length % 3 != 0
throw "Invalid mnemonic length : #{mnemonicIndexes.length}"
if mnemonicIndexes.indexOf(-1) != -1
word = mnemonicPhrase.trim().split(' ')[mnemonicIndexes.indexOf(-1)]
throw "Invalid mnemonic word : #{word}"
mnemonicBin = @mnemonicIndexesToBin(mnemonicIndexes)
[binEntropy, binChecksum] = @splitMnemonicBin(mnemonicBin)
if ! @checkEntropyChecksum(binEntropy, binChecksum)
throw "Checksum error."
return true
# Do not check if mnemonic words are valids.
# @param [String] mnemonicPhrase A mnemonic phrase.
# @return [Array] Mnemonic words in the phrase.
mnemonicWordsFromPhrase: (mnemonicPhrase="") ->
mnemonicPhrase = _.str.clean(mnemonicPhrase)
mnemonicPhrase.trim().split(/\ /)
# @param [String] mnemonicWord
# @return [Integer] Index of mnemonicWord in wordlist
mnemonicWordToIndex: (mnemonicWord) ->
Bip39.wordlist.indexOf(mnemonicWord)
# @param [Array] mnemonicWords
# @return [Array] Indexes of each mnemonicWord in wordlist
mnemonicWordsToIndexes: (mnemonicWords) ->
@mnemonicWordToIndex(mnemonicWord) for mnemonicWord in mnemonicWords
# @return [Array] Return entropy bits and checksum bits.
splitMnemonicBin: (mnemonicBin) ->
# There is a checksum bit for each 33 bits (= 3 mnemonics word) slice.
[mnemonicBin.slice(0, -(mnemonicBin.length/33)), mnemonicBin.slice(-(mnemonicBin.length/33))]
checkEntropyChecksum: (entropyBin, checksumBin) ->
integersEntropy = entropyBin.match(/[01]{32}/g).map (s) -> parseInt(s,2)
hashedIntegersEntropy = sjcl.hash.sha256.hash integersEntropy
hashedEntropyBinaryArray = hashedIntegersEntropy.map (s) => @_intToBin(s, @BITS_IN_INTEGER)
computedChecksumBin = hashedEntropyBinaryArray.join('').slice(0, checksumBin.length)
return computedChecksumBin == checksumBin
mnemonicIndexToBin: (mnemonicIndex) ->
@_intToBin(mnemonicIndex, 11)
mnemonicIndexesToBin: (mnemonicIndexes) ->
(@mnemonicIndexToBin(index) for index in mnemonicIndexes).join('')
# Do not check if mnemonic phrase is valid.
# @param [String] mnemonicPhrase A mnemonic phrase.
# @return [Integer] The number of mnemonic word in the phrase.
mnemonicPhraseWordsLength: (mnemonicPhrase) ->
@mnemonicWordsFromPhrase(mnemonicPhrase).length
# @param [String] mnemonicWord A mnemonic word.
# @return [Boolean] Return true if mnemonic word is in wordlist
isMnemonicWordValid: (mnemonicWord) ->
@mnemonicWordToIndex(mnemonicWord) != -1
# Just check if each mnemonic word is valid.
# Do not check checksum, length, etc.
# @param [Array] mnemonicWords An array of mnemonic words.
# @return [Boolean] Return true if each mnemonic word is in wordlist
isMnemonicWordsValid: (mnemonicWords) ->
_.every(mnemonicWords, (word) => @isMnemonicWordValid(word))
_intToBin: (int, binLength) ->
int += 1 if int < 0
str = int.toString(2)
str = str.replace("-","0").replace(/0/g,'a').replace(/1/g,'0').replace(/a/g,'1') if int < 0
str = (if int < 0 then '1' else '0') + str while str.length < binLength
str
_bytesArrayToHexString: (bytesArray) ->
(_.str.lpad(byte.toString(16), 2, '0') for byte in bytesArray).join('')
| true | ledger.bitcoin ?= {}
ledger.bitcoin.bip39 ?= {}
Bip39 = ledger.bitcoin.bip39
_.extend ledger.bitcoin.bip39,
ENTROPY_BIT_LENGTH: 256
DEFAULT_PHRASE_LENGTH: 24
# @param [String] mnemonicWords Mnemonic words.
# @return [Array] Mnemonic words in the phrase.
isMnemonicPhraseValid: (mnemonicPhrase) ->
try
@utils.checkMnemonicPhraseValid(mnemonicPhrase) && true
catch e
false
# @return [String]
generateEntropy: (entropyBitLength = @ENTROPY_BIT_LENGTH) ->
entropyBytesArray = new Uint8Array(entropyBitLength / 8)
crypto.getRandomValues(entropyBytesArray)
@utils._bytesArrayToHexString(entropyBytesArray)
# @param [string] entropy A hexadecimal string.
# @return [string] Mnemonic phrase. Phrase may contains 12 to 24 words depending of entropy length.
entropyToMnemonicPhrase: (entropy) ->
throw "Invalid entropy format. Wait a hexadecimal string" if ! entropy.match(/^[0-9a-fA-F]+$/)
throw "Invalid entropy length: #{entropy.length*4}" if entropy.length % 8 != 0
# Compute checksum
entropyIntegersArray = entropy.match(/[0-9a-fA-F]{8}/g).map (h) -> parseInt(h,16)
hashedEntropyIntegersArray = sjcl.hash.sha256.hash entropyIntegersArray
hashedEntropy = hashedEntropyIntegersArray.map((i) => @utils._intToBin(i,32)).join('')
# 1 checksum bit per 32 bits of entropy.
binChecksum = hashedEntropy.slice(0,entropyIntegersArray.length)
binEntropy = entropyIntegersArray.map((i) => @utils._intToBin(i,32)).join('')
binMnemonic = binEntropy + binChecksum
throw "Invalid binMnemonic length : #{binMnemonic.length}" if binMnemonic.length % 11 != 0
mnemonicIndexes = binMnemonic.match(/[01]{11}/g).map (b) -> parseInt(b,2)
mnemonicWords = mnemonicIndexes.map (idx) => @wordlist[idx]
mnemonicWords.join(' ')
# @return [String]
generateMnemonicPhrase: (phraseLength=@DEFAULT_PHRASE_LENGTH) ->
entropyBitLength = phraseLength * 32 / 3
@entropyToMnemonicPhrase(@generateEntropy(entropyBitLength))
# @param [String] mnemonicWords Mnemonic words.
# @return [Array] Mnemonic words in the phrase.
mnemonicPhraseToSeed: (mnemonicPhrase, passphrase="") ->
@utils.checkMnemonicPhraseValid(mnemonicPhrase)
hmacSHA512 = (key) ->
hasher = new sjcl.misc.hmac(key, sjcl.hash.sha512)
@encrypt = ->
return hasher.encrypt.apply(hasher, arguments)
@
password = PI:PASSWORD:<PASSWORD>END_PI')
salt = "PI:PASSWORD:<PASSWORD>END_PI" + passphrase.normalize('NPI:PASSWORD:<PASSWORD>END_PI')
passwordBits = sjcl.codec.utf8String.toBits(password)
saltBits = sjcl.codec.utf8String.toBits(salt)
result = sjcl.misc.pbkdf2(passwordBits, saltBits, 2048, 512, hmacSHA512)
hashHex = sjcl.codec.hex.fromBits(result)
return hashHex
mnemonicPhraseToWordIndexes: (mnemonicPhrase) ->
(ledger.bitcoin.bip39.wordlist.indexOf(word) for word in mnemonicPhrase.split(' '))
utils:
BITS_IN_INTEGER: 8 * 4
checkMnemonicPhraseValid: (mnemonicPhrase) ->
mnemonicWords = @mnemonicWordsFromPhrase(mnemonicPhrase)
if mnemonicWords.length != ledger.bitcoin.bip39.DEFAULT_PHRASE_LENGTH
throw "Invalid mnemonic length: #{mnemonicWords.length}"
mnemonicIndexes = @mnemonicWordsToIndexes(mnemonicWords)
if mnemonicIndexes.length % 3 != 0
throw "Invalid mnemonic length : #{mnemonicIndexes.length}"
if mnemonicIndexes.indexOf(-1) != -1
word = mnemonicPhrase.trim().split(' ')[mnemonicIndexes.indexOf(-1)]
throw "Invalid mnemonic word : #{word}"
mnemonicBin = @mnemonicIndexesToBin(mnemonicIndexes)
[binEntropy, binChecksum] = @splitMnemonicBin(mnemonicBin)
if ! @checkEntropyChecksum(binEntropy, binChecksum)
throw "Checksum error."
return true
# Do not check if mnemonic words are valids.
# @param [String] mnemonicPhrase A mnemonic phrase.
# @return [Array] Mnemonic words in the phrase.
mnemonicWordsFromPhrase: (mnemonicPhrase="") ->
mnemonicPhrase = _.str.clean(mnemonicPhrase)
mnemonicPhrase.trim().split(/\ /)
# @param [String] mnemonicWord
# @return [Integer] Index of mnemonicWord in wordlist
mnemonicWordToIndex: (mnemonicWord) ->
Bip39.wordlist.indexOf(mnemonicWord)
# @param [Array] mnemonicWords
# @return [Array] Indexes of each mnemonicWord in wordlist
mnemonicWordsToIndexes: (mnemonicWords) ->
@mnemonicWordToIndex(mnemonicWord) for mnemonicWord in mnemonicWords
# @return [Array] Return entropy bits and checksum bits.
splitMnemonicBin: (mnemonicBin) ->
# There is a checksum bit for each 33 bits (= 3 mnemonics word) slice.
[mnemonicBin.slice(0, -(mnemonicBin.length/33)), mnemonicBin.slice(-(mnemonicBin.length/33))]
checkEntropyChecksum: (entropyBin, checksumBin) ->
integersEntropy = entropyBin.match(/[01]{32}/g).map (s) -> parseInt(s,2)
hashedIntegersEntropy = sjcl.hash.sha256.hash integersEntropy
hashedEntropyBinaryArray = hashedIntegersEntropy.map (s) => @_intToBin(s, @BITS_IN_INTEGER)
computedChecksumBin = hashedEntropyBinaryArray.join('').slice(0, checksumBin.length)
return computedChecksumBin == checksumBin
mnemonicIndexToBin: (mnemonicIndex) ->
@_intToBin(mnemonicIndex, 11)
mnemonicIndexesToBin: (mnemonicIndexes) ->
(@mnemonicIndexToBin(index) for index in mnemonicIndexes).join('')
# Do not check if mnemonic phrase is valid.
# @param [String] mnemonicPhrase A mnemonic phrase.
# @return [Integer] The number of mnemonic word in the phrase.
mnemonicPhraseWordsLength: (mnemonicPhrase) ->
@mnemonicWordsFromPhrase(mnemonicPhrase).length
# @param [String] mnemonicWord A mnemonic word.
# @return [Boolean] Return true if mnemonic word is in wordlist
isMnemonicWordValid: (mnemonicWord) ->
@mnemonicWordToIndex(mnemonicWord) != -1
# Just check if each mnemonic word is valid.
# Do not check checksum, length, etc.
# @param [Array] mnemonicWords An array of mnemonic words.
# @return [Boolean] Return true if each mnemonic word is in wordlist
isMnemonicWordsValid: (mnemonicWords) ->
_.every(mnemonicWords, (word) => @isMnemonicWordValid(word))
_intToBin: (int, binLength) ->
int += 1 if int < 0
str = int.toString(2)
str = str.replace("-","0").replace(/0/g,'a').replace(/1/g,'0').replace(/a/g,'1') if int < 0
str = (if int < 0 then '1' else '0') + str while str.length < binLength
str
_bytesArrayToHexString: (bytesArray) ->
(_.str.lpad(byte.toString(16), 2, '0') for byte in bytesArray).join('')
|
[
{
"context": "sts for the given manufacturer and model.\r\n@author Nathan Klick\r\n@copyright QRef 2012\r\n###\r\nclass AircraftCheckli",
"end": 814,
"score": 0.9998360276222229,
"start": 802,
"tag": "NAME",
"value": "Nathan Klick"
}
] | Workspace/QRef/NodeServer/src/router/routes/ajax/aircraft/AircraftChecklistsByModelRoute.coffee | qrefdev/qref | 0 | AjaxRoute = require('../../../AjaxRoute')
AjaxResponse = require('../../../../serialization/AjaxResponse')
UserAuth = require('../../../../security/UserAuth')
QRefDatabase = require('../../../../db/QRefDatabase')
###
Service route that allows the retrieval of all checklists for a given manufacturer and model.
@example Service Methods (see {CreateAircraftChecklistAjaxRequest})
Request Format: application/json
Response Format: application/json
GET /services/ajax/aircraft/checklist/manufacturer/:manufacturerId/model/:modelId?token=:token
:manufacturerId - (Required) The Id of a manufacturer.
:modelId - (Required) The Id of a model.
:token - (Required) A valid authentication token.
Retrieves all checklists for the given manufacturer and model.
@author Nathan Klick
@copyright QRef 2012
###
class AircraftChecklistsByModelRoute extends AjaxRoute
constructor: () ->
super [{ method: 'POST', path: '/checklist/manufacturer/:manufacturerId/model/:modelId' }, { method: 'GET', path: '/checklist/manufacturer/:manufacturerId/model/:modelId' }]
get: (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')
mfg = req.params.manufacturerId
mdl = req.params.modelId
checklistId = req.params.checklistId
UserAuth.validateToken(token, (err, isTokenValid) ->
if err? or not isTokenValid == true
resp = new AjaxResponse()
resp.failure('Not Authorized', 403)
res.json(resp, 200)
return
# Validate Permissions Here
query = db.AircraftChecklist.find({ model : mdl, manufacturer : mfg, user: null })
query.exec((err, arrObjs) ->
if err?
resp = new AjaxResponse()
resp.failure('Internal Error', 500)
res.json(resp, 200)
return
if arrObjs.length > 0
resp = new AjaxResponse()
resp.addRecords(arrObjs)
resp.setTotal(arrObjs.length)
res.json(resp, 200)
else
resp = new AjaxResponse()
resp.failure('Not Found', 404)
res.json(resp, 200)
)
)
post: (req, res) =>
resp = new AjaxResponse()
resp.failure('Not Found', 404)
res.json(resp, 200)
return
isValidRequest: (req) ->
if (req.query? and req.query?.token? and req.params? and req.params?.modelId? and req.params?.manufacturerId?)
true
else
false
module.exports = new AircraftChecklistsByModelRoute() | 175699 | AjaxRoute = require('../../../AjaxRoute')
AjaxResponse = require('../../../../serialization/AjaxResponse')
UserAuth = require('../../../../security/UserAuth')
QRefDatabase = require('../../../../db/QRefDatabase')
###
Service route that allows the retrieval of all checklists for a given manufacturer and model.
@example Service Methods (see {CreateAircraftChecklistAjaxRequest})
Request Format: application/json
Response Format: application/json
GET /services/ajax/aircraft/checklist/manufacturer/:manufacturerId/model/:modelId?token=:token
:manufacturerId - (Required) The Id of a manufacturer.
:modelId - (Required) The Id of a model.
:token - (Required) A valid authentication token.
Retrieves all checklists for the given manufacturer and model.
@author <NAME>
@copyright QRef 2012
###
class AircraftChecklistsByModelRoute extends AjaxRoute
constructor: () ->
super [{ method: 'POST', path: '/checklist/manufacturer/:manufacturerId/model/:modelId' }, { method: 'GET', path: '/checklist/manufacturer/:manufacturerId/model/:modelId' }]
get: (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')
mfg = req.params.manufacturerId
mdl = req.params.modelId
checklistId = req.params.checklistId
UserAuth.validateToken(token, (err, isTokenValid) ->
if err? or not isTokenValid == true
resp = new AjaxResponse()
resp.failure('Not Authorized', 403)
res.json(resp, 200)
return
# Validate Permissions Here
query = db.AircraftChecklist.find({ model : mdl, manufacturer : mfg, user: null })
query.exec((err, arrObjs) ->
if err?
resp = new AjaxResponse()
resp.failure('Internal Error', 500)
res.json(resp, 200)
return
if arrObjs.length > 0
resp = new AjaxResponse()
resp.addRecords(arrObjs)
resp.setTotal(arrObjs.length)
res.json(resp, 200)
else
resp = new AjaxResponse()
resp.failure('Not Found', 404)
res.json(resp, 200)
)
)
post: (req, res) =>
resp = new AjaxResponse()
resp.failure('Not Found', 404)
res.json(resp, 200)
return
isValidRequest: (req) ->
if (req.query? and req.query?.token? and req.params? and req.params?.modelId? and req.params?.manufacturerId?)
true
else
false
module.exports = new AircraftChecklistsByModelRoute() | true | AjaxRoute = require('../../../AjaxRoute')
AjaxResponse = require('../../../../serialization/AjaxResponse')
UserAuth = require('../../../../security/UserAuth')
QRefDatabase = require('../../../../db/QRefDatabase')
###
Service route that allows the retrieval of all checklists for a given manufacturer and model.
@example Service Methods (see {CreateAircraftChecklistAjaxRequest})
Request Format: application/json
Response Format: application/json
GET /services/ajax/aircraft/checklist/manufacturer/:manufacturerId/model/:modelId?token=:token
:manufacturerId - (Required) The Id of a manufacturer.
:modelId - (Required) The Id of a model.
:token - (Required) A valid authentication token.
Retrieves all checklists for the given manufacturer and model.
@author PI:NAME:<NAME>END_PI
@copyright QRef 2012
###
class AircraftChecklistsByModelRoute extends AjaxRoute
constructor: () ->
super [{ method: 'POST', path: '/checklist/manufacturer/:manufacturerId/model/:modelId' }, { method: 'GET', path: '/checklist/manufacturer/:manufacturerId/model/:modelId' }]
get: (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')
mfg = req.params.manufacturerId
mdl = req.params.modelId
checklistId = req.params.checklistId
UserAuth.validateToken(token, (err, isTokenValid) ->
if err? or not isTokenValid == true
resp = new AjaxResponse()
resp.failure('Not Authorized', 403)
res.json(resp, 200)
return
# Validate Permissions Here
query = db.AircraftChecklist.find({ model : mdl, manufacturer : mfg, user: null })
query.exec((err, arrObjs) ->
if err?
resp = new AjaxResponse()
resp.failure('Internal Error', 500)
res.json(resp, 200)
return
if arrObjs.length > 0
resp = new AjaxResponse()
resp.addRecords(arrObjs)
resp.setTotal(arrObjs.length)
res.json(resp, 200)
else
resp = new AjaxResponse()
resp.failure('Not Found', 404)
res.json(resp, 200)
)
)
post: (req, res) =>
resp = new AjaxResponse()
resp.failure('Not Found', 404)
res.json(resp, 200)
return
isValidRequest: (req) ->
if (req.query? and req.query?.token? and req.params? and req.params?.modelId? and req.params?.manufacturerId?)
true
else
false
module.exports = new AircraftChecklistsByModelRoute() |
[
{
"context": "angular: [\n { key: \"data.name\" }\n #{ key: \"data.storagerepositoryname\" }\n]\n",
"end": 71,
"score": 0.9354338049888611,
"start": 45,
"tag": "KEY",
"value": "data.storagerepositoryname"
}
] | jobs/vm-action-copy/form.cson | ratokeshi/meshblu-connector-xenserver | 0 | angular: [
{ key: "data.name" }
#{ key: "data.storagerepositoryname" }
]
| 64867 | angular: [
{ key: "data.name" }
#{ key: "<KEY>" }
]
| true | angular: [
{ key: "data.name" }
#{ key: "PI:KEY:<KEY>END_PI" }
]
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9981744289398193,
"start": 12,
"tag": "NAME",
"value": "Joyent"
},
{
"context": ".com\"\n cert:\n subjectaltname: \"IP Address:127.0.0.1\"\n subject: {}\n\n er... | test/simple/test-tls-check-server-identity.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")
util = require("util")
tls = require("tls")
tests = [
{
# Basic CN handling
host: "a.com"
cert:
subject:
CN: "a.com"
}
{
host: "a.com"
cert:
subject:
CN: "A.COM"
}
{
host: "a.com"
cert:
subject:
CN: "b.com"
error: "Host: a.com. is not cert's CN: b.com"
}
{
host: "a.com"
cert:
subject:
CN: "a.com."
}
{
# Wildcards in CN
host: "b.a.com"
cert:
subject:
CN: "*.a.com"
}
{
host: "b.a.com"
cert:
subjectaltname: "DNS:omg.com"
subject:
CN: "*.a.com"
error: "Host: b.a.com. is not in the cert's altnames: " + "DNS:omg.com"
}
{
# Multiple CN fields
host: "foo.com"
cert:
subject: # CN=foo.com; CN=bar.com;
CN: [
"foo.com"
"bar.com"
]
}
{
# DNS names and CN
host: "a.com"
cert:
subjectaltname: "DNS:*"
subject:
CN: "b.com"
error: "Host: a.com. is not in the cert's altnames: " + "DNS:*"
}
{
host: "a.com"
cert:
subjectaltname: "DNS:*.com"
subject:
CN: "b.com"
error: "Host: a.com. is not in the cert's altnames: " + "DNS:*.com"
}
{
host: "a.co.uk"
cert:
subjectaltname: "DNS:*.co.uk"
subject:
CN: "b.com"
}
{
host: "a.com"
cert:
subjectaltname: "DNS:*.a.com"
subject:
CN: "a.com"
error: "Host: a.com. is not in the cert's altnames: " + "DNS:*.a.com"
}
{
host: "a.com"
cert:
subjectaltname: "DNS:*.a.com"
subject:
CN: "b.com"
error: "Host: a.com. is not in the cert's altnames: " + "DNS:*.a.com"
}
{
host: "a.com"
cert:
subjectaltname: "DNS:a.com"
subject:
CN: "b.com"
}
{
host: "a.com"
cert:
subjectaltname: "DNS:A.COM"
subject:
CN: "b.com"
}
{
# DNS names
host: "a.com"
cert:
subjectaltname: "DNS:*.a.com"
subject: {}
error: "Host: a.com. is not in the cert's altnames: " + "DNS:*.a.com"
}
{
host: "b.a.com"
cert:
subjectaltname: "DNS:*.a.com"
subject: {}
}
{
host: "c.b.a.com"
cert:
subjectaltname: "DNS:*.a.com"
subject: {}
error: "Host: c.b.a.com. is not in the cert's altnames: " + "DNS:*.a.com"
}
{
host: "b.a.com"
cert:
subjectaltname: "DNS:*b.a.com"
subject: {}
}
{
host: "a-cb.a.com"
cert:
subjectaltname: "DNS:*b.a.com"
subject: {}
}
{
host: "a.b.a.com"
cert:
subjectaltname: "DNS:*b.a.com"
subject: {}
error: "Host: a.b.a.com. is not in the cert's altnames: " + "DNS:*b.a.com"
}
{
# Mutliple DNS names
host: "a.b.a.com"
cert:
subjectaltname: "DNS:*b.a.com, DNS:a.b.a.com"
subject: {}
}
{
# URI names
host: "a.b.a.com"
cert:
subjectaltname: "URI:http://a.b.a.com/"
subject: {}
}
{
host: "a.b.a.com"
cert:
subjectaltname: "URI:http://*.b.a.com/"
subject: {}
error: "Host: a.b.a.com. is not in the cert's altnames: " + "URI:http://*.b.a.com/"
}
{
# IP addresses
host: "a.b.a.com"
cert:
subjectaltname: "IP Address:127.0.0.1"
subject: {}
error: "Host: a.b.a.com. is not in the cert's altnames: " + "IP Address:127.0.0.1"
}
{
host: "127.0.0.1"
cert:
subjectaltname: "IP Address:127.0.0.1"
subject: {}
}
{
host: "127.0.0.2"
cert:
subjectaltname: "IP Address:127.0.0.1"
subject: {}
error: "IP: 127.0.0.2 is not in the cert's list: " + "127.0.0.1"
}
{
host: "127.0.0.1"
cert:
subjectaltname: "DNS:a.com"
subject: {}
error: "IP: 127.0.0.1 is not in the cert's list: "
}
{
host: "localhost"
cert:
subjectaltname: "DNS:a.com"
subject:
CN: "localhost"
error: "Host: localhost. is not in the cert's altnames: " + "DNS:a.com"
}
]
tests.forEach (test, i) ->
err = tls.checkServerIdentity(test.host, test.cert)
assert.equal err and err.reason, test.error, "Test#" + i + " failed: " + util.inspect(test) + "\n" + test.error + " != " + (err and err.reason)
return
| 32666 | # 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")
util = require("util")
tls = require("tls")
tests = [
{
# Basic CN handling
host: "a.com"
cert:
subject:
CN: "a.com"
}
{
host: "a.com"
cert:
subject:
CN: "A.COM"
}
{
host: "a.com"
cert:
subject:
CN: "b.com"
error: "Host: a.com. is not cert's CN: b.com"
}
{
host: "a.com"
cert:
subject:
CN: "a.com."
}
{
# Wildcards in CN
host: "b.a.com"
cert:
subject:
CN: "*.a.com"
}
{
host: "b.a.com"
cert:
subjectaltname: "DNS:omg.com"
subject:
CN: "*.a.com"
error: "Host: b.a.com. is not in the cert's altnames: " + "DNS:omg.com"
}
{
# Multiple CN fields
host: "foo.com"
cert:
subject: # CN=foo.com; CN=bar.com;
CN: [
"foo.com"
"bar.com"
]
}
{
# DNS names and CN
host: "a.com"
cert:
subjectaltname: "DNS:*"
subject:
CN: "b.com"
error: "Host: a.com. is not in the cert's altnames: " + "DNS:*"
}
{
host: "a.com"
cert:
subjectaltname: "DNS:*.com"
subject:
CN: "b.com"
error: "Host: a.com. is not in the cert's altnames: " + "DNS:*.com"
}
{
host: "a.co.uk"
cert:
subjectaltname: "DNS:*.co.uk"
subject:
CN: "b.com"
}
{
host: "a.com"
cert:
subjectaltname: "DNS:*.a.com"
subject:
CN: "a.com"
error: "Host: a.com. is not in the cert's altnames: " + "DNS:*.a.com"
}
{
host: "a.com"
cert:
subjectaltname: "DNS:*.a.com"
subject:
CN: "b.com"
error: "Host: a.com. is not in the cert's altnames: " + "DNS:*.a.com"
}
{
host: "a.com"
cert:
subjectaltname: "DNS:a.com"
subject:
CN: "b.com"
}
{
host: "a.com"
cert:
subjectaltname: "DNS:A.COM"
subject:
CN: "b.com"
}
{
# DNS names
host: "a.com"
cert:
subjectaltname: "DNS:*.a.com"
subject: {}
error: "Host: a.com. is not in the cert's altnames: " + "DNS:*.a.com"
}
{
host: "b.a.com"
cert:
subjectaltname: "DNS:*.a.com"
subject: {}
}
{
host: "c.b.a.com"
cert:
subjectaltname: "DNS:*.a.com"
subject: {}
error: "Host: c.b.a.com. is not in the cert's altnames: " + "DNS:*.a.com"
}
{
host: "b.a.com"
cert:
subjectaltname: "DNS:*b.a.com"
subject: {}
}
{
host: "a-cb.a.com"
cert:
subjectaltname: "DNS:*b.a.com"
subject: {}
}
{
host: "a.b.a.com"
cert:
subjectaltname: "DNS:*b.a.com"
subject: {}
error: "Host: a.b.a.com. is not in the cert's altnames: " + "DNS:*b.a.com"
}
{
# Mutliple DNS names
host: "a.b.a.com"
cert:
subjectaltname: "DNS:*b.a.com, DNS:a.b.a.com"
subject: {}
}
{
# URI names
host: "a.b.a.com"
cert:
subjectaltname: "URI:http://a.b.a.com/"
subject: {}
}
{
host: "a.b.a.com"
cert:
subjectaltname: "URI:http://*.b.a.com/"
subject: {}
error: "Host: a.b.a.com. is not in the cert's altnames: " + "URI:http://*.b.a.com/"
}
{
# IP addresses
host: "a.b.a.com"
cert:
subjectaltname: "IP Address:127.0.0.1"
subject: {}
error: "Host: a.b.a.com. is not in the cert's altnames: " + "IP Address:127.0.0.1"
}
{
host: "127.0.0.1"
cert:
subjectaltname: "IP Address:127.0.0.1"
subject: {}
}
{
host: "127.0.0.2"
cert:
subjectaltname: "IP Address:127.0.0.1"
subject: {}
error: "IP: 127.0.0.2 is not in the cert's list: " + "127.0.0.1"
}
{
host: "127.0.0.1"
cert:
subjectaltname: "DNS:a.com"
subject: {}
error: "IP: 127.0.0.1 is not in the cert's list: "
}
{
host: "localhost"
cert:
subjectaltname: "DNS:a.com"
subject:
CN: "localhost"
error: "Host: localhost. is not in the cert's altnames: " + "DNS:a.com"
}
]
tests.forEach (test, i) ->
err = tls.checkServerIdentity(test.host, test.cert)
assert.equal err and err.reason, test.error, "Test#" + i + " failed: " + util.inspect(test) + "\n" + test.error + " != " + (err and err.reason)
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")
util = require("util")
tls = require("tls")
tests = [
{
# Basic CN handling
host: "a.com"
cert:
subject:
CN: "a.com"
}
{
host: "a.com"
cert:
subject:
CN: "A.COM"
}
{
host: "a.com"
cert:
subject:
CN: "b.com"
error: "Host: a.com. is not cert's CN: b.com"
}
{
host: "a.com"
cert:
subject:
CN: "a.com."
}
{
# Wildcards in CN
host: "b.a.com"
cert:
subject:
CN: "*.a.com"
}
{
host: "b.a.com"
cert:
subjectaltname: "DNS:omg.com"
subject:
CN: "*.a.com"
error: "Host: b.a.com. is not in the cert's altnames: " + "DNS:omg.com"
}
{
# Multiple CN fields
host: "foo.com"
cert:
subject: # CN=foo.com; CN=bar.com;
CN: [
"foo.com"
"bar.com"
]
}
{
# DNS names and CN
host: "a.com"
cert:
subjectaltname: "DNS:*"
subject:
CN: "b.com"
error: "Host: a.com. is not in the cert's altnames: " + "DNS:*"
}
{
host: "a.com"
cert:
subjectaltname: "DNS:*.com"
subject:
CN: "b.com"
error: "Host: a.com. is not in the cert's altnames: " + "DNS:*.com"
}
{
host: "a.co.uk"
cert:
subjectaltname: "DNS:*.co.uk"
subject:
CN: "b.com"
}
{
host: "a.com"
cert:
subjectaltname: "DNS:*.a.com"
subject:
CN: "a.com"
error: "Host: a.com. is not in the cert's altnames: " + "DNS:*.a.com"
}
{
host: "a.com"
cert:
subjectaltname: "DNS:*.a.com"
subject:
CN: "b.com"
error: "Host: a.com. is not in the cert's altnames: " + "DNS:*.a.com"
}
{
host: "a.com"
cert:
subjectaltname: "DNS:a.com"
subject:
CN: "b.com"
}
{
host: "a.com"
cert:
subjectaltname: "DNS:A.COM"
subject:
CN: "b.com"
}
{
# DNS names
host: "a.com"
cert:
subjectaltname: "DNS:*.a.com"
subject: {}
error: "Host: a.com. is not in the cert's altnames: " + "DNS:*.a.com"
}
{
host: "b.a.com"
cert:
subjectaltname: "DNS:*.a.com"
subject: {}
}
{
host: "c.b.a.com"
cert:
subjectaltname: "DNS:*.a.com"
subject: {}
error: "Host: c.b.a.com. is not in the cert's altnames: " + "DNS:*.a.com"
}
{
host: "b.a.com"
cert:
subjectaltname: "DNS:*b.a.com"
subject: {}
}
{
host: "a-cb.a.com"
cert:
subjectaltname: "DNS:*b.a.com"
subject: {}
}
{
host: "a.b.a.com"
cert:
subjectaltname: "DNS:*b.a.com"
subject: {}
error: "Host: a.b.a.com. is not in the cert's altnames: " + "DNS:*b.a.com"
}
{
# Mutliple DNS names
host: "a.b.a.com"
cert:
subjectaltname: "DNS:*b.a.com, DNS:a.b.a.com"
subject: {}
}
{
# URI names
host: "a.b.a.com"
cert:
subjectaltname: "URI:http://a.b.a.com/"
subject: {}
}
{
host: "a.b.a.com"
cert:
subjectaltname: "URI:http://*.b.a.com/"
subject: {}
error: "Host: a.b.a.com. is not in the cert's altnames: " + "URI:http://*.b.a.com/"
}
{
# IP addresses
host: "a.b.a.com"
cert:
subjectaltname: "IP Address:127.0.0.1"
subject: {}
error: "Host: a.b.a.com. is not in the cert's altnames: " + "IP Address:127.0.0.1"
}
{
host: "127.0.0.1"
cert:
subjectaltname: "IP Address:127.0.0.1"
subject: {}
}
{
host: "127.0.0.2"
cert:
subjectaltname: "IP Address:127.0.0.1"
subject: {}
error: "IP: 127.0.0.2 is not in the cert's list: " + "127.0.0.1"
}
{
host: "127.0.0.1"
cert:
subjectaltname: "DNS:a.com"
subject: {}
error: "IP: 127.0.0.1 is not in the cert's list: "
}
{
host: "localhost"
cert:
subjectaltname: "DNS:a.com"
subject:
CN: "localhost"
error: "Host: localhost. is not in the cert's altnames: " + "DNS:a.com"
}
]
tests.forEach (test, i) ->
err = tls.checkServerIdentity(test.host, test.cert)
assert.equal err and err.reason, test.error, "Test#" + i + " failed: " + util.inspect(test) + "\n" + test.error + " != " + (err and err.reason)
return
|
[
{
"context": "require '../lib/user'\n{prng} = require 'crypto'\n\nalice = bob = charlie = null\n\nexports.init = (T,cb) ->\n",
"end": 112,
"score": 0.9926829934120178,
"start": 107,
"tag": "NAME",
"value": "alice"
},
{
"context": " '../lib/user'\n{prng} = require 'crypto'\n\nalice ... | test/files/5_dir.iced | AngelKey/Angelkey.nodeclient | 151 | fs = require 'fs'
path = require 'path'
{User} = require '../lib/user'
{prng} = require 'crypto'
alice = bob = charlie = null
exports.init = (T,cb) ->
tmp = {}
await User.load_many { names : [ 'alice', 'bob', 'charlie'], res : tmp }, defer err
{alice,bob,charlie} = tmp
cb err
ctext = null
# -----------------------------------------------------------------------------------------
act =
sign_home_dir: (T, who, cb) ->
args = ["dir", "sign", who.homedir]
await who.keybase {args, quiet: true}, defer err, out
T.no_error err, "failed to sign home dir"
T.assert out, "failed to sign home dir"
cb()
__verify_home_dir: (T, who, expect_success, strict, cb) ->
if strict
args = ["dir", "verify", "--strict", who.homedir]
else
args = ["dir", "verify", who.homedir]
await who.keybase {args, quiet: true}, defer err, out
if expect_success
T.no_error err, "failed to verify good home dir signing"
T.assert out, "failed to verify good home dir signing"
else
T.assert err?, "expected an error in home dir signature"
cb()
verify_with_assertions: (T, who, whom, assertions, expect_success, cb) ->
args = ["dir", "verify", whom.homedir]
args.push "--assert"
args.push assertions.join " && "
await who.keybase {args, quiet: true}, defer err, out
if expect_success
T.no_error err, "failed to verify good home dir signing"
T.assert out, "failed to verify good home dir signing"
else
T.assert err?, "expected an error in home dir signature"
cb()
proof_ids: (T, who, cb) ->
args = ["status"]
await who.keybase {args}, defer err, out
T.no_error err, "failed to status"
T.assert out, "failed to status"
res = null
if (not err) and out?.toString()
res = JSON.parse(out.toString()).user.proofs
cb res
verify_home_dir: (T, who, expect_success, cb) -> act.__verify_home_dir T, who, expect_success, false, cb
strict_verify_home_dir: (T, who, expect_success, cb) -> act.__verify_home_dir T, who, expect_success, true, cb
rfile: -> "file_#{prng(12).toString('hex')}.txt"
rdir: -> "dir_#{prng(12).toString('hex')}"
unlink: (T, who, fname, cb) ->
await fs.unlink path.join(who.homedir, fname), defer err
T.no_error err, "failed to unlink file"
cb()
rmdir: (T, who, dname, cb) ->
await fs.rmdir path.join(who.homedir, dname), defer err
T.no_error err, "failed to rmdir"
cb()
symlink: (T, who, src, dest, cb) ->
p_src = path.join who.homedir, src
p_dest = path.join who.homedir, dest
await fs.symlink p_src, p_dest, defer err
T.no_error err, "failed to symlink file"
cb()
chmod: (T, who, fname, mode, cb) ->
await fs.chmod (path.join who.homedir, fname), mode, defer err
T.no_error err, "error chmod'ing"
cb()
write_random_file: (T, who, cb) ->
await fs.writeFile (path.join who.homedir, act.rfile()), 'fake', defer err
T.no_error err, "error writing random file"
cb()
mk_random_dir: (T, who, cb) ->
await fs.mkdir (path.join who.homedir, act.rdir()), defer err
T.no_error err, "error creating random directory"
cb()
mkdir: (T, who, dname, cb) ->
await fs.mkdir (path.join who.homedir, dname), defer err
T.no_error err, "error creating directory"
cb()
append_junk: (T, who, fname, cb) ->
await fs.appendFile (path.join who.homedir, fname), prng(100).toString('hex'), defer err
T.no_error err, "error writing/appending to file"
cb()
# -----------------------------------------------------------------------------------------
exports.alice_sign_and_verify_homedir = (T, cb) ->
await act.sign_home_dir T, alice, defer()
await act.verify_home_dir T, alice, true, defer()
cb()
exports.assertions = (T, cb) ->
await act.sign_home_dir T, charlie, defer()
await act.proof_ids T, charlie, defer proof_ids
await act.verify_with_assertions T, alice, charlie, ["twitter://#{proof_ids.twitter}", "github://#{proof_ids.github}"], true, defer()
await act.verify_with_assertions T, alice, charlie, ["twitter://evil_wrongdoer", "github://wrong_evildoer"], false, defer()
cb()
exports.alice_wrong_item_types = (T, cb) ->
fname = act.rfile()
await act.append_junk T, alice, fname, defer()
await act.sign_home_dir T, alice, defer()
await act.unlink T, alice, fname, defer()
await act.mkdir T, alice, fname, defer()
await act.verify_home_dir T, alice, false, defer()
await act.sign_home_dir T, alice, defer()
await act.rmdir T, alice, fname, defer()
await act.append_junk T, alice, fname, defer()
await act.verify_home_dir T, alice, false, defer()
cb()
exports.alice_wrong_exec_privs = (T, cb) ->
fname = act.rfile()
await act.append_junk T, alice, fname, defer()
await act.sign_home_dir T, alice, defer()
await act.chmod T, alice, fname, '0755', defer()
await act.verify_home_dir T, alice, true, defer()
await act.strict_verify_home_dir T, alice, false, defer()
await act.chmod T, alice, fname, '0666', defer()
await act.strict_verify_home_dir T, alice, true, defer()
cb()
exports.alice_bad_signatures = (T, cb) ->
await act.sign_home_dir T, alice, defer()
await act.verify_home_dir T, alice, true, defer()
await act.write_random_file T, alice, defer()
await act.verify_home_dir T, alice, false, defer()
cb()
exports.alice_bad_file_contents = (T, cb) ->
fname = act.rfile()
await act.append_junk T, alice, fname, defer()
await act.sign_home_dir T, alice, defer()
await act.verify_home_dir T, alice, true, defer()
await act.append_junk T, alice, fname, defer()
await act.verify_home_dir T, alice, false, defer()
cb()
exports.alice_file_missing = (T, cb) ->
fname = act.rfile()
await act.append_junk T, alice, fname, defer()
await act.sign_home_dir T, alice, defer()
await act.verify_home_dir T, alice, true, defer()
await act.unlink T, alice, fname, defer()
await act.verify_home_dir T, alice, false, defer()
cb()
exports.alice_extra_file = (T, cb) ->
await act.sign_home_dir T, alice, defer()
await act.write_random_file T, alice, defer()
await act.verify_home_dir T, alice, false, defer()
cb()
exports.alice_extra_dir = (T, cb) ->
await act.sign_home_dir T, alice, defer()
await act.mk_random_dir T, alice, defer()
await act.verify_home_dir T, alice, true, defer()
await act.strict_verify_home_dir T, alice, false, defer()
cb()
exports.alice_dir_missing = (T, cb) ->
d = act.rdir()
await act.mkdir T, alice, d, defer()
await act.sign_home_dir T, alice, defer()
await act.rmdir T, alice, d, defer()
await act.verify_home_dir T, alice, true, defer()
await act.strict_verify_home_dir T, alice, false, defer()
cb()
exports.alice_bad_symlinks = (T, cb) ->
src = act.rfile()
dest1 = act.rfile()
dest2 = act.rfile()
await act.append_junk T, alice, dest1, defer()
await act.append_junk T, alice, dest2, defer()
await act.symlink T, alice, dest1, src, defer()
await act.sign_home_dir T, alice, defer()
await act.verify_home_dir T, alice, true, defer()
await act.unlink T, alice, src, defer()
await act.symlink T, alice, dest2, src, defer()
await act.verify_home_dir T, alice, false, defer()
cb()
| 170831 | fs = require 'fs'
path = require 'path'
{User} = require '../lib/user'
{prng} = require 'crypto'
<NAME> = <NAME> = <NAME> = null
exports.init = (T,cb) ->
tmp = {}
await User.load_many { names : [ '<NAME>', '<NAME>', '<NAME>'], res : tmp }, defer err
{<NAME>,<NAME>,<NAME>} = tmp
cb err
ctext = null
# -----------------------------------------------------------------------------------------
act =
sign_home_dir: (T, who, cb) ->
args = ["dir", "sign", who.homedir]
await who.keybase {args, quiet: true}, defer err, out
T.no_error err, "failed to sign home dir"
T.assert out, "failed to sign home dir"
cb()
__verify_home_dir: (T, who, expect_success, strict, cb) ->
if strict
args = ["dir", "verify", "--strict", who.homedir]
else
args = ["dir", "verify", who.homedir]
await who.keybase {args, quiet: true}, defer err, out
if expect_success
T.no_error err, "failed to verify good home dir signing"
T.assert out, "failed to verify good home dir signing"
else
T.assert err?, "expected an error in home dir signature"
cb()
verify_with_assertions: (T, who, whom, assertions, expect_success, cb) ->
args = ["dir", "verify", whom.homedir]
args.push "--assert"
args.push assertions.join " && "
await who.keybase {args, quiet: true}, defer err, out
if expect_success
T.no_error err, "failed to verify good home dir signing"
T.assert out, "failed to verify good home dir signing"
else
T.assert err?, "expected an error in home dir signature"
cb()
proof_ids: (T, who, cb) ->
args = ["status"]
await who.keybase {args}, defer err, out
T.no_error err, "failed to status"
T.assert out, "failed to status"
res = null
if (not err) and out?.toString()
res = JSON.parse(out.toString()).user.proofs
cb res
verify_home_dir: (T, who, expect_success, cb) -> act.__verify_home_dir T, who, expect_success, false, cb
strict_verify_home_dir: (T, who, expect_success, cb) -> act.__verify_home_dir T, who, expect_success, true, cb
rfile: -> "file_#{prng(12).toString('hex')}.txt"
rdir: -> "dir_#{prng(12).toString('hex')}"
unlink: (T, who, fname, cb) ->
await fs.unlink path.join(who.homedir, fname), defer err
T.no_error err, "failed to unlink file"
cb()
rmdir: (T, who, dname, cb) ->
await fs.rmdir path.join(who.homedir, dname), defer err
T.no_error err, "failed to rmdir"
cb()
symlink: (T, who, src, dest, cb) ->
p_src = path.join who.homedir, src
p_dest = path.join who.homedir, dest
await fs.symlink p_src, p_dest, defer err
T.no_error err, "failed to symlink file"
cb()
chmod: (T, who, fname, mode, cb) ->
await fs.chmod (path.join who.homedir, fname), mode, defer err
T.no_error err, "error chmod'ing"
cb()
write_random_file: (T, who, cb) ->
await fs.writeFile (path.join who.homedir, act.rfile()), 'fake', defer err
T.no_error err, "error writing random file"
cb()
mk_random_dir: (T, who, cb) ->
await fs.mkdir (path.join who.homedir, act.rdir()), defer err
T.no_error err, "error creating random directory"
cb()
mkdir: (T, who, dname, cb) ->
await fs.mkdir (path.join who.homedir, dname), defer err
T.no_error err, "error creating directory"
cb()
append_junk: (T, who, fname, cb) ->
await fs.appendFile (path.join who.homedir, fname), prng(100).toString('hex'), defer err
T.no_error err, "error writing/appending to file"
cb()
# -----------------------------------------------------------------------------------------
exports.alice_sign_and_verify_homedir = (T, cb) ->
await act.sign_home_dir T, <NAME>, defer()
await act.verify_home_dir T, <NAME>, true, defer()
cb()
exports.assertions = (T, cb) ->
await act.sign_home_dir T, <NAME> <NAME>, defer()
await act.proof_ids T, <NAME> <NAME>, defer proof_ids
await act.verify_with_assertions T, <NAME>, <NAME>, ["twitter://#{proof_ids.twitter}", "github://#{proof_ids.github}"], true, defer()
await act.verify_with_assertions T, <NAME>, <NAME>, ["twitter://evil_wrongdoer", "github://wrong_evildoer"], false, defer()
cb()
exports.alice_wrong_item_types = (T, cb) ->
fname = act.rfile()
await act.append_junk T, <NAME>, fname, defer()
await act.sign_home_dir T, <NAME>, defer()
await act.unlink T, <NAME>, fname, defer()
await act.mkdir T, <NAME>, fname, defer()
await act.verify_home_dir T, <NAME>, false, defer()
await act.sign_home_dir T, <NAME>, defer()
await act.rmdir T, <NAME>, fname, defer()
await act.append_junk T, <NAME>, fname, defer()
await act.verify_home_dir T, <NAME>, false, defer()
cb()
exports.alice_wrong_exec_privs = (T, cb) ->
fname = act.rfile()
await act.append_junk T, <NAME>, fname, defer()
await act.sign_home_dir T, <NAME>, defer()
await act.chmod T, <NAME>, fname, '0755', defer()
await act.verify_home_dir T, <NAME>, true, defer()
await act.strict_verify_home_dir T, alice, false, defer()
await act.chmod T, <NAME>, fname, '0666', defer()
await act.strict_verify_home_dir T, <NAME>, true, defer()
cb()
exports.alice_bad_signatures = (T, cb) ->
await act.sign_home_dir T, <NAME>, defer()
await act.verify_home_dir T, <NAME>, true, defer()
await act.write_random_file T, <NAME>, defer()
await act.verify_home_dir T, <NAME>, false, defer()
cb()
exports.alice_bad_file_contents = (T, cb) ->
fname = act.rfile()
await act.append_junk T, <NAME>, fname, defer()
await act.sign_home_dir T, <NAME>, defer()
await act.verify_home_dir T, <NAME>, true, defer()
await act.append_junk T, <NAME>, fname, defer()
await act.verify_home_dir T, <NAME>, false, defer()
cb()
exports.alice_file_missing = (T, cb) ->
fname = act.rfile()
await act.append_junk T, <NAME>, fname, defer()
await act.sign_home_dir T, <NAME>, defer()
await act.verify_home_dir T, <NAME>, true, defer()
await act.unlink T, alice, fname, defer()
await act.verify_home_dir T, <NAME>, false, defer()
cb()
exports.alice_extra_file = (T, cb) ->
await act.sign_home_dir T, <NAME>, defer()
await act.write_random_file T, <NAME>, defer()
await act.verify_home_dir T, <NAME>, false, defer()
cb()
exports.alice_extra_dir = (T, cb) ->
await act.sign_home_dir T, <NAME>, defer()
await act.mk_random_dir T, <NAME>, defer()
await act.verify_home_dir T, <NAME>, true, defer()
await act.strict_verify_home_dir T, alice, false, defer()
cb()
exports.alice_dir_missing = (T, cb) ->
d = act.rdir()
await act.mkdir T, <NAME>, d, defer()
await act.sign_home_dir T, <NAME>, defer()
await act.rmdir T, <NAME>, d, defer()
await act.verify_home_dir T, <NAME>, true, defer()
await act.strict_verify_home_dir T, <NAME>, false, defer()
cb()
exports.alice_bad_symlinks = (T, cb) ->
src = act.rfile()
dest1 = act.rfile()
dest2 = act.rfile()
await act.append_junk T, <NAME>, dest1, defer()
await act.append_junk T, <NAME>, dest2, defer()
await act.symlink T, alice, dest1, src, defer()
await act.sign_home_dir T, <NAME>, defer()
await act.verify_home_dir T, <NAME>, true, defer()
await act.unlink T, <NAME>, src, defer()
await act.symlink T, alice, dest2, src, defer()
await act.verify_home_dir T, alice, false, defer()
cb()
| true | fs = require 'fs'
path = require 'path'
{User} = require '../lib/user'
{prng} = require 'crypto'
PI:NAME:<NAME>END_PI = PI:NAME:<NAME>END_PI = PI:NAME:<NAME>END_PI = null
exports.init = (T,cb) ->
tmp = {}
await User.load_many { names : [ 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'], res : tmp }, defer err
{PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI} = tmp
cb err
ctext = null
# -----------------------------------------------------------------------------------------
act =
sign_home_dir: (T, who, cb) ->
args = ["dir", "sign", who.homedir]
await who.keybase {args, quiet: true}, defer err, out
T.no_error err, "failed to sign home dir"
T.assert out, "failed to sign home dir"
cb()
__verify_home_dir: (T, who, expect_success, strict, cb) ->
if strict
args = ["dir", "verify", "--strict", who.homedir]
else
args = ["dir", "verify", who.homedir]
await who.keybase {args, quiet: true}, defer err, out
if expect_success
T.no_error err, "failed to verify good home dir signing"
T.assert out, "failed to verify good home dir signing"
else
T.assert err?, "expected an error in home dir signature"
cb()
verify_with_assertions: (T, who, whom, assertions, expect_success, cb) ->
args = ["dir", "verify", whom.homedir]
args.push "--assert"
args.push assertions.join " && "
await who.keybase {args, quiet: true}, defer err, out
if expect_success
T.no_error err, "failed to verify good home dir signing"
T.assert out, "failed to verify good home dir signing"
else
T.assert err?, "expected an error in home dir signature"
cb()
proof_ids: (T, who, cb) ->
args = ["status"]
await who.keybase {args}, defer err, out
T.no_error err, "failed to status"
T.assert out, "failed to status"
res = null
if (not err) and out?.toString()
res = JSON.parse(out.toString()).user.proofs
cb res
verify_home_dir: (T, who, expect_success, cb) -> act.__verify_home_dir T, who, expect_success, false, cb
strict_verify_home_dir: (T, who, expect_success, cb) -> act.__verify_home_dir T, who, expect_success, true, cb
rfile: -> "file_#{prng(12).toString('hex')}.txt"
rdir: -> "dir_#{prng(12).toString('hex')}"
unlink: (T, who, fname, cb) ->
await fs.unlink path.join(who.homedir, fname), defer err
T.no_error err, "failed to unlink file"
cb()
rmdir: (T, who, dname, cb) ->
await fs.rmdir path.join(who.homedir, dname), defer err
T.no_error err, "failed to rmdir"
cb()
symlink: (T, who, src, dest, cb) ->
p_src = path.join who.homedir, src
p_dest = path.join who.homedir, dest
await fs.symlink p_src, p_dest, defer err
T.no_error err, "failed to symlink file"
cb()
chmod: (T, who, fname, mode, cb) ->
await fs.chmod (path.join who.homedir, fname), mode, defer err
T.no_error err, "error chmod'ing"
cb()
write_random_file: (T, who, cb) ->
await fs.writeFile (path.join who.homedir, act.rfile()), 'fake', defer err
T.no_error err, "error writing random file"
cb()
mk_random_dir: (T, who, cb) ->
await fs.mkdir (path.join who.homedir, act.rdir()), defer err
T.no_error err, "error creating random directory"
cb()
mkdir: (T, who, dname, cb) ->
await fs.mkdir (path.join who.homedir, dname), defer err
T.no_error err, "error creating directory"
cb()
append_junk: (T, who, fname, cb) ->
await fs.appendFile (path.join who.homedir, fname), prng(100).toString('hex'), defer err
T.no_error err, "error writing/appending to file"
cb()
# -----------------------------------------------------------------------------------------
exports.alice_sign_and_verify_homedir = (T, cb) ->
await act.sign_home_dir T, PI:NAME:<NAME>END_PI, defer()
await act.verify_home_dir T, PI:NAME:<NAME>END_PI, true, defer()
cb()
exports.assertions = (T, cb) ->
await act.sign_home_dir T, PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI, defer()
await act.proof_ids T, PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI, defer proof_ids
await act.verify_with_assertions T, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, ["twitter://#{proof_ids.twitter}", "github://#{proof_ids.github}"], true, defer()
await act.verify_with_assertions T, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, ["twitter://evil_wrongdoer", "github://wrong_evildoer"], false, defer()
cb()
exports.alice_wrong_item_types = (T, cb) ->
fname = act.rfile()
await act.append_junk T, PI:NAME:<NAME>END_PI, fname, defer()
await act.sign_home_dir T, PI:NAME:<NAME>END_PI, defer()
await act.unlink T, PI:NAME:<NAME>END_PI, fname, defer()
await act.mkdir T, PI:NAME:<NAME>END_PI, fname, defer()
await act.verify_home_dir T, PI:NAME:<NAME>END_PI, false, defer()
await act.sign_home_dir T, PI:NAME:<NAME>END_PI, defer()
await act.rmdir T, PI:NAME:<NAME>END_PI, fname, defer()
await act.append_junk T, PI:NAME:<NAME>END_PI, fname, defer()
await act.verify_home_dir T, PI:NAME:<NAME>END_PI, false, defer()
cb()
exports.alice_wrong_exec_privs = (T, cb) ->
fname = act.rfile()
await act.append_junk T, PI:NAME:<NAME>END_PI, fname, defer()
await act.sign_home_dir T, PI:NAME:<NAME>END_PI, defer()
await act.chmod T, PI:NAME:<NAME>END_PI, fname, '0755', defer()
await act.verify_home_dir T, PI:NAME:<NAME>END_PI, true, defer()
await act.strict_verify_home_dir T, alice, false, defer()
await act.chmod T, PI:NAME:<NAME>END_PI, fname, '0666', defer()
await act.strict_verify_home_dir T, PI:NAME:<NAME>END_PI, true, defer()
cb()
exports.alice_bad_signatures = (T, cb) ->
await act.sign_home_dir T, PI:NAME:<NAME>END_PI, defer()
await act.verify_home_dir T, PI:NAME:<NAME>END_PI, true, defer()
await act.write_random_file T, PI:NAME:<NAME>END_PI, defer()
await act.verify_home_dir T, PI:NAME:<NAME>END_PI, false, defer()
cb()
exports.alice_bad_file_contents = (T, cb) ->
fname = act.rfile()
await act.append_junk T, PI:NAME:<NAME>END_PI, fname, defer()
await act.sign_home_dir T, PI:NAME:<NAME>END_PI, defer()
await act.verify_home_dir T, PI:NAME:<NAME>END_PI, true, defer()
await act.append_junk T, PI:NAME:<NAME>END_PI, fname, defer()
await act.verify_home_dir T, PI:NAME:<NAME>END_PI, false, defer()
cb()
exports.alice_file_missing = (T, cb) ->
fname = act.rfile()
await act.append_junk T, PI:NAME:<NAME>END_PI, fname, defer()
await act.sign_home_dir T, PI:NAME:<NAME>END_PI, defer()
await act.verify_home_dir T, PI:NAME:<NAME>END_PI, true, defer()
await act.unlink T, alice, fname, defer()
await act.verify_home_dir T, PI:NAME:<NAME>END_PI, false, defer()
cb()
exports.alice_extra_file = (T, cb) ->
await act.sign_home_dir T, PI:NAME:<NAME>END_PI, defer()
await act.write_random_file T, PI:NAME:<NAME>END_PI, defer()
await act.verify_home_dir T, PI:NAME:<NAME>END_PI, false, defer()
cb()
exports.alice_extra_dir = (T, cb) ->
await act.sign_home_dir T, PI:NAME:<NAME>END_PI, defer()
await act.mk_random_dir T, PI:NAME:<NAME>END_PI, defer()
await act.verify_home_dir T, PI:NAME:<NAME>END_PI, true, defer()
await act.strict_verify_home_dir T, alice, false, defer()
cb()
exports.alice_dir_missing = (T, cb) ->
d = act.rdir()
await act.mkdir T, PI:NAME:<NAME>END_PI, d, defer()
await act.sign_home_dir T, PI:NAME:<NAME>END_PI, defer()
await act.rmdir T, PI:NAME:<NAME>END_PI, d, defer()
await act.verify_home_dir T, PI:NAME:<NAME>END_PI, true, defer()
await act.strict_verify_home_dir T, PI:NAME:<NAME>END_PI, false, defer()
cb()
exports.alice_bad_symlinks = (T, cb) ->
src = act.rfile()
dest1 = act.rfile()
dest2 = act.rfile()
await act.append_junk T, PI:NAME:<NAME>END_PI, dest1, defer()
await act.append_junk T, PI:NAME:<NAME>END_PI, dest2, defer()
await act.symlink T, alice, dest1, src, defer()
await act.sign_home_dir T, PI:NAME:<NAME>END_PI, defer()
await act.verify_home_dir T, PI:NAME:<NAME>END_PI, true, defer()
await act.unlink T, PI:NAME:<NAME>END_PI, src, defer()
await act.symlink T, alice, dest2, src, defer()
await act.verify_home_dir T, alice, false, defer()
cb()
|
[
{
"context": "ges/icons/jira@2x.png'\n\n @_fields.push\n key: 'webhookUrl'\n type: 'text'\n readonly: true\n descr",
"end": 1264,
"score": 0.6933654546737671,
"start": 1257,
"tag": "KEY",
"value": "webhook"
}
] | src/services/jira.coffee | jianliaoim/talk-services | 40 | util = require '../util'
_receiveWebhook = ({body}) ->
payload = body
message = {}
attachment = category: 'quote', data: {}
JIRA_CREATE_EVENT = "jira:issue_created"
JIRA_UPDATE_EVENT = "jira:issue_updated"
if body.webhookEvent is JIRA_CREATE_EVENT
attachment.data.title = "#{body.user.displayName} created an issue for project #{body.issue.fields.project.name}"
attachment.data.text = "Summary: #{body.issue.fields.summary}"
else if body.webhookEvent is JIRA_UPDATE_EVENT
attachment.data.title = "#{body.user.displayName} updated an issue for project #{body.issue.fields.project.name}"
attachment.data.text = "Summary: #{body.issue.fields.summary}"
else
throw new Error("Unknown Jira event type")
message.attachments = [attachment]
message
module.exports = ->
@title = 'Jira'
@template = 'webhook'
@summary = util.i18n
zh: '项目管理和事务追踪'
en: 'The flexible and scalable issue tracker for software teams.'
@description = util.i18n
zh: 'JIRA是Atlassian公司出品的项目与事务跟踪工具,被广泛应用于缺陷跟踪、客户服务、需求收集、流程审批、任务跟踪、项目跟踪和敏捷管理等工作领域。'
en: 'Track and manage everything with JIRA project and issue tracking software by Atlassian.'
@iconUrl = util.static 'images/icons/jira@2x.png'
@_fields.push
key: 'webhookUrl'
type: 'text'
readonly: true
description: util.i18n
zh: '复制 webhook 地址到你的 Jira 的项目配置当中使用。'
en: 'Copy this webhook to your Jira project setting to use it.'
@registerEvent 'service.webhook', _receiveWebhook
| 8144 | util = require '../util'
_receiveWebhook = ({body}) ->
payload = body
message = {}
attachment = category: 'quote', data: {}
JIRA_CREATE_EVENT = "jira:issue_created"
JIRA_UPDATE_EVENT = "jira:issue_updated"
if body.webhookEvent is JIRA_CREATE_EVENT
attachment.data.title = "#{body.user.displayName} created an issue for project #{body.issue.fields.project.name}"
attachment.data.text = "Summary: #{body.issue.fields.summary}"
else if body.webhookEvent is JIRA_UPDATE_EVENT
attachment.data.title = "#{body.user.displayName} updated an issue for project #{body.issue.fields.project.name}"
attachment.data.text = "Summary: #{body.issue.fields.summary}"
else
throw new Error("Unknown Jira event type")
message.attachments = [attachment]
message
module.exports = ->
@title = 'Jira'
@template = 'webhook'
@summary = util.i18n
zh: '项目管理和事务追踪'
en: 'The flexible and scalable issue tracker for software teams.'
@description = util.i18n
zh: 'JIRA是Atlassian公司出品的项目与事务跟踪工具,被广泛应用于缺陷跟踪、客户服务、需求收集、流程审批、任务跟踪、项目跟踪和敏捷管理等工作领域。'
en: 'Track and manage everything with JIRA project and issue tracking software by Atlassian.'
@iconUrl = util.static 'images/icons/jira@2x.png'
@_fields.push
key: '<KEY>Url'
type: 'text'
readonly: true
description: util.i18n
zh: '复制 webhook 地址到你的 Jira 的项目配置当中使用。'
en: 'Copy this webhook to your Jira project setting to use it.'
@registerEvent 'service.webhook', _receiveWebhook
| true | util = require '../util'
_receiveWebhook = ({body}) ->
payload = body
message = {}
attachment = category: 'quote', data: {}
JIRA_CREATE_EVENT = "jira:issue_created"
JIRA_UPDATE_EVENT = "jira:issue_updated"
if body.webhookEvent is JIRA_CREATE_EVENT
attachment.data.title = "#{body.user.displayName} created an issue for project #{body.issue.fields.project.name}"
attachment.data.text = "Summary: #{body.issue.fields.summary}"
else if body.webhookEvent is JIRA_UPDATE_EVENT
attachment.data.title = "#{body.user.displayName} updated an issue for project #{body.issue.fields.project.name}"
attachment.data.text = "Summary: #{body.issue.fields.summary}"
else
throw new Error("Unknown Jira event type")
message.attachments = [attachment]
message
module.exports = ->
@title = 'Jira'
@template = 'webhook'
@summary = util.i18n
zh: '项目管理和事务追踪'
en: 'The flexible and scalable issue tracker for software teams.'
@description = util.i18n
zh: 'JIRA是Atlassian公司出品的项目与事务跟踪工具,被广泛应用于缺陷跟踪、客户服务、需求收集、流程审批、任务跟踪、项目跟踪和敏捷管理等工作领域。'
en: 'Track and manage everything with JIRA project and issue tracking software by Atlassian.'
@iconUrl = util.static 'images/icons/jira@2x.png'
@_fields.push
key: 'PI:KEY:<KEY>END_PIUrl'
type: 'text'
readonly: true
description: util.i18n
zh: '复制 webhook 地址到你的 Jira 的项目配置当中使用。'
en: 'Copy this webhook to your Jira project setting to use it.'
@registerEvent 'service.webhook', _receiveWebhook
|
[
{
"context": "miniEditor.getText()\n keys = @sessionId.split(\"-\")\n [@app_key, @app_secret] = [keys[0], keys[",
"end": 11783,
"score": 0.5900612473487854,
"start": 11783,
"tag": "KEY",
"value": ""
}
] | lib/controller.coffee | mingsai/atom-supercopair | 7 | #atom-supercollider
url = require('url')
Repl = require('./repl')
## {$, Range} = require 'atom'
{$, Range} = require 'atom-space-pen-views'
#atom-pair
StartView = require './views/start-view'
InputView = require './views/input-view'
AlertView = require './views/alert-view'
require './pusher/pusher'
require './pusher/pusher-js-client-auth'
randomstring = require 'randomstring'
_ = require 'underscore'
chunkString = require './helpers/chunk-string'
HipChatInvite = require './modules/hipchat_invite'
Marker = require './modules/marker'
GrammarSync = require './modules/grammar_sync'
SuperCopairConfig = require './modules/keys_config'
{CompositeDisposable, Range} = require 'atom'
module.exports =
class Controller
#atom-pair
SuperCopairView: null
modalPanel: null
subscriptions: null
constructor: (directory) ->
#atom-supercollider
@defaultURI = "sclang://localhost:57120"
@projectRoot = if directory then directory.path else ''
@repls = {}
@activeRepl = null
@markers = []
start: ->
#atom-pair
# Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
@subscriptions = new CompositeDisposable
@editorListeners = new CompositeDisposable
# Register command that toggles this view
@subscriptions.add atom.commands.add 'atom-workspace', 'supercopair:start-new-pairing-session': => @startSession()
@subscriptions.add atom.commands.add 'atom-workspace', 'supercopair:join-pairing-session': => @joinSession()
@subscriptions.add atom.commands.add 'atom-workspace', 'supercopair:set-configuration-keys': => @setConfig()
@subscriptions.add atom.commands.add 'atom-workspace', 'supercopair:invite-over-hipchat': => @inviteOverHipChat()
@subscriptions.add atom.commands.add 'atom-workspace', 'supercopair:custom-paste': => @customPaste()
atom.commands.add 'atom-workspace', 'supercopair:hide-views': => @hidePanel()
atom.commands.add '.session-id', 'supercopair:copyid': => @copyId()
@colours = require('./helpers/colour-list')
@friendColours = []
@timeouts = []
@events = []
_.extend(@, HipChatInvite, Marker, GrammarSync, SuperCopairConfig)
#atom-supercopair
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:broadcast-eval", => @broadcastEval(false)
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:broadcast-cmd-period", => @broadcastCmdPeriod(false)
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:broadcast-eval-exclusively", => @broadcastEval(true)
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:broadcast-cmd-period-exclusively", => @broadcastCmdPeriod(true)
#atom-supercollider
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:open-post-window", => @openPostWindow(@defaultURI)
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:clear-post-window", => @clearPostWindow()
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:recompile", => @recompile()
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:cmd-period", => @cmdPeriod()
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:eval", => @eval()
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:open-help-file", => @openHelpFile()
# open a REPL for sclang on this host/port
atom.workspace.addOpener (uri, options) =>
try
{protocol, hostname, port} = url.parse(uri)
catch error
return
return unless protocol is 'sclang:'
onClose = =>
if @activeRepl is repl
@destroyRepl()
delete @repls[uri]
repl = new Repl(uri, @projectRoot, onClose)
@activateRepl repl
@repls[uri] = repl
window = repl.createPostWindow()
repl.startSCLang()
window
#atom-supercollider
stop: ->
for repl in @repls
repl.stop()
@destroyRepl()
@repls = {}
activateRepl: (repl) ->
@activeRepl = repl
@activeRepl.unsubscriber = repl.emit.subscribe (event) =>
@handleReplEvent(event)
destroyRepl: () ->
@activeRepl?.unsubscriber()
@activeRepl = null
handleReplEvent: (event) ->
error = event.value()
# only expecting compile errors for now
if error.index == 0
@openToSyntaxError(error.file, error.line, error.char)
openPostWindow: (uri) ->
repl = @repls[uri]
if repl
@activateRepl repl
else
# open links on click
fileOpener = (event) =>
# A or child of A
link = event.target.href
unless link
link = $(event.target).parents('a').attr('href')
return unless link
event.preventDefault()
if link.substr(0, 7) == 'file://'
path = link.substr(7)
atom.workspace.open(path, split: 'left', searchAllPanes: true)
return
if link.substr(0, 10) == 'scclass://'
link = link.substr(10)
[path, charPos] = link.split(':')
if ',' in charPos
[lineno, char] = charPos.split(',')
@openFile(
path,
null,
parseInt(lineno),
parseInt(char),
'line',
'line-highlight')
else
@openFile(
path,
parseInt(charPos),
null,
null,
'line',
'line-highlight')
options =
split: 'right'
searchAllPanes: true
atom.workspace.open(uri, options)
.then () =>
@activateRepl @repls[uri]
$('.post-window').on 'click', fileOpener
clearPostWindow: ->
@activeRepl?.clearPostWindow()
recompile: ->
@destroyMarkers()
if @activeRepl
@activeRepl.recompile()
else
@openPostWindow(@defaultURI)
cmdPeriod: ->
@activeRepl?.cmdPeriod()
editorIsSC: ->
editor = atom.workspace.getActiveTextEditor()
editor and editor.getGrammar().scopeName is 'source.supercollider'
currentExpression: ->
editor = atom.workspace.getActiveTextEditor()
return unless editor?
selection = editor.getLastSelection()
expression = selection.getText()
if expression
range = selection.getBufferRange()
else
# execute the line you are on
pos = editor.getCursorBufferPosition()
row = editor.getCursorScreenPosition().row
if row?
range = new Range([row, 0], [row + 1, 0])
expression = editor.lineTextForBufferRow(row)
else
range = null
expression = null
[expression, range]
currentPath: ->
editor = atom.workspace.getActiveTextEditor()
return unless editor?
editor.getPath()
eval: ->
return unless @editorIsSC()
[expression, range] = @currentExpression()
@evalWithRepl(expression, @currentPath(), range)
evalWithRepl: (expression, path, range) ->
@destroyMarkers()
return unless expression
doIt = () =>
if range?
unflash = @evalFlash(range)
onSuccess = () ->
unflash?('eval-success')
onError = (error) =>
if error.type is 'SyntaxError'
unflash?('eval-syntax-error')
if path
# offset syntax error by position of selected text in file
row = range.getRows()[0] + error.error.line
col = error.error.charPos
@openToSyntaxError(path, parseInt(row), parseInt(col))
else
# runtime error
unflash?('eval-error')
@activeRepl.eval(expression, false, path)
.then(onSuccess, onError)
if @activeRepl
# if stuck in compile error
# then post warning and return
unless @activeRepl.isCompiled()
@activeRepl.warnIsNotCompiled()
return
doIt()
else
@openPostWindow(@defaultURI)
.then doIt
openToSyntaxError: (path, line, char) ->
@openFile(path, null, line, char)
openHelpFile: ->
unless @editorIsSC()
return false
[expression, range] = @currentExpression()
base = null
# Klass.openHelpFile
klassy = /^([A-Z]{1}[a-zA-Z0-9\_]*)$/
match = expression.match(klassy)
if match
base = expression
else
# 'someMethod'.openHelpFile
# starts with lowercase has no punctuation, wrap in ''
# TODO match ops
methody = /^([a-z]{1}[a-zA-Z0-9\_]*)$/
match = expression.match(methody)
if match
base = "'#{expression}'"
else
# anything else just do a search
stringy = /^([^"]+)$/
match = expression.match(stringy)
if match
base = '"' + expression + '"'
if base
@evalWithRepl("#{base}.openHelpFile")
openFile: (uri, charPos, row, col, markerType="line", cssClass="line-error")->
options =
initialLine: row
initialColumn: col
split: 'left'
activatePane: false
searchAllPanes: true
atom.workspace.open(uri, options)
.then (editor) =>
setMark = (point) =>
editor.setCursorBufferPosition(point)
expression = editor.lineForBufferRow(point[0])
range = [point, [point[0], expression.length - 1]]
@destroyMarkers()
marker = editor.markBufferRange(range, invalidate: 'touch')
decoration = editor.decorateMarker(marker,
type: markerType,
class: cssClass)
@markers.push marker
if row?
# mark is zero indexed
return setMark([row - 1, col])
text = editor.getText()
cursor = 0
li = 0
for ll in text.split('\n')
cursor += (ll.length + 1)
if cursor > charPos
return setMark([li, cursor - charPos - ll.length])
li += 1
destroyMarkers: () ->
@markers.forEach (m) ->
m.destroy()
@markers = []
evalFlash: (range) ->
editor = atom.workspace.getActiveTextEditor()
if editor
marker = editor.markBufferRange(range, invalidate: 'touch')
decoration = editor.decorateMarker(marker,
type: 'line',
class: "eval-flash")
# return fn to flash error/success and destroy the flash
(cssClass) ->
decoration.update(type: 'line', class: cssClass)
destroy = ->
marker.destroy()
setTimeout(destroy, 100)
#atom-pair
customPaste: ->
text = atom.clipboard.read()
if text.length > 800
chunks = chunkString(text, 800)
_.each chunks, (chunk, index) =>
setTimeout(( =>
atom.clipboard.write(chunk)
@editor.pasteText()
if index is (chunks.length - 1) then atom.clipboard.write(text)
), 180 * index)
else
@editor.pasteText()
disconnect: ->
@pusher.disconnect()
@editorListeners.dispose()
_.each @friendColours, (colour) => @clearMarkers(colour)
@clearMarkers(@markerColour)
@markerColour = null
atom.views.getView(@editor).removeAttribute('id')
@hidePanel()
copyId: ->
atom.clipboard.write(@sessionId)
@startPanel.hide()
hidePanel: ->
_.each atom.workspace.getModalPanels(), (panel) -> panel.hide()
joinSession: ->
if @markerColour
alreadyPairing = new AlertView "It looks like you are already in a pairing session. Please open a new window (cmd+shift+N) to start/join a new one."
atom.workspace.addModalPanel(item: alreadyPairing, visible: true)
return
@joinView = new InputView("Enter the session ID here:")
@joinPanel = atom.workspace.addModalPanel(item: @joinView, visible: true)
@joinView.miniEditor.focus()
@joinView.on 'core:confirm', =>
@sessionId = @joinView.miniEditor.getText()
keys = @sessionId.split("-")
[@app_key, @app_secret] = [keys[0], keys[1]]
@joinPanel.hide()
atom.workspace.open().then => @pairingSetup() #starts a new tab to join pairing session
startSession: ->
@getKeysFromConfig()
if @missingPusherKeys()
alertView = new AlertView "Please set your Pusher keys."
atom.workspace.addModalPanel(item: alertView, visible: true)
else
if @markerColour
alreadyPairing = new AlertView "It looks like you are already in a pairing session. Please disconnect or open a new window to start/join a new one."
atom.workspace.addModalPanel(item: alreadyPairing, visible: true)
return
@generateSessionId()
@startView = new StartView(@sessionId)
@startPanel = atom.workspace.addModalPanel(item: @startView, visible: true)
@startView.focus()
@markerColour = @colours[0]
@pairingSetup()
@activeRepl?.postMessage('SuperCopair: Session started!')
generateSessionId: ->
@sessionId = "#{@app_key}-#{@app_secret}-#{randomstring.generate(11)}"
pairingSetup: ->
@editor = atom.workspace.getActiveTextEditor()
if !@editor then return atom.workspace.open().then => @pairingSetup()
atom.views.getView(@editor).setAttribute('id', 'SuperCopair')
@connectToPusher()
@synchronizeColours()
@subscriptions.add atom.commands.add 'atom-workspace', 'SuperCopair:disconnect': => @disconnect()
connectToPusher: ->
@pusher = new Pusher @app_key,
authTransport: 'client'
clientAuth:
key: @app_key
secret: @app_secret
user_id: @markerColour || "blank"
@pairingChannel = @pusher.subscribe("presence-session-#{@sessionId}")
synchronizeColours: ->
@pairingChannel.bind 'pusher:subscription_succeeded', (members) =>
@membersCount = members.count
return @resubscribe() unless @markerColour
colours = Object.keys(members.members)
@friendColours = _.without(colours, @markerColour)
_.each(@friendColours, (colour) => @addMarker 0, colour)
@startPairing()
resubscribe: ->
@pairingChannel.unsubscribe()
@markerColour = @colours[@membersCount - 1]
@connectToPusher()
@synchronizeColours()
startPairing: ->
@triggerPush = true
buffer = @buffer = @editor.buffer
# listening for Pusher events
@pairingChannel.bind 'pusher:member_added', (member) =>
noticeView = new AlertView "Your pair buddy has joined the session."
atom.workspace.addModalPanel(item: noticeView, visible: true)
@sendGrammar()
@shareCurrentFile()
@friendColours.push(member.id)
@addMarker 0, member.id
@pairingChannel.bind 'client-grammar-sync', (syntax) =>
grammar = atom.grammars.grammarForScopeName(syntax)
@editor.setGrammar(grammar)
@pairingChannel.bind 'client-share-whole-file', (file) =>
@triggerPush = false
buffer.setText(file)
@triggerPush = true
@pairingChannel.bind 'client-share-partial-file', (chunk) =>
@triggerPush = false
buffer.append(chunk)
@triggerPush = true
@pairingChannel.bind 'client-change', (events) =>
_.each events, (event) =>
@changeBuffer(event) if event.eventType is 'buffer-change'
if event.eventType is 'buffer-selection'
@updateCollaboratorMarker(event)
#atom-supercopair
if event.eventType is 'broadcast-event'
@pairEval(event)
@pairingChannel.bind 'pusher:member_removed', (member) =>
@clearMarkers(member.id)
disconnectView = new AlertView "Your pair buddy has left the session."
atom.workspace.addModalPanel(item: disconnectView, visible: true)
@triggerEventQueue()
# listening for buffer events
@editorListeners.add @listenToBufferChanges()
@editorListeners.add @syncSelectionRange()
@editorListeners.add @syncGrammars()
# listening for its own demise
@listenForDestruction()
listenForDestruction: ->
@editorListeners.add @buffer.onDidDestroy => @disconnect()
@editorListeners.add @editor.onDidDestroy => @disconnect()
listenToBufferChanges: ->
@buffer.onDidChange (event) =>
return unless @triggerPush
if !(event.newText is "\n") and (event.newText.length is 0)
changeType = 'deletion'
event = {oldRange: event.oldRange}
else if event.oldRange.containsRange(event.newRange)
changeType = 'substitution'
event = {oldRange: event.oldRange, newRange: event.newRange, newText: event.newText}
else
changeType = 'insertion'
event = {newRange: event.newRange, newText: event.newText}
event = {changeType: changeType, event: event, colour: @markerColour, eventType: 'buffer-change'}
@events.push(event)
changeBuffer: (data) ->
if data.event.newRange then newRange = Range.fromObject(data.event.newRange)
if data.event.oldRange then oldRange = Range.fromObject(data.event.oldRange)
if data.event.newText then newText = data.event.newText
@triggerPush = false
@clearMarkers(data.colour)
switch data.changeType
when 'deletion'
@buffer.delete oldRange
actionArea = oldRange.start
when 'substitution'
@buffer.setTextInRange oldRange, newText
actionArea = oldRange.start
else
@buffer.insert newRange.start, newText
actionArea = newRange.start
#@editor.scrollToBufferPosition(actionArea)
@addMarker(actionArea.toArray()[0], data.colour)
@triggerPush = true
syncSelectionRange: ->
@editor.onDidChangeSelectionRange (event) =>
rows = event.newBufferRange.getRows()
return unless rows.length > 1
@events.push {eventType: 'buffer-selection', colour: @markerColour, rows: rows}
triggerEventQueue: ->
@eventInterval = setInterval(=>
if @events.length > 0
@pairingChannel.trigger 'client-change', @events
@events = []
, 120)
shareCurrentFile: ->
currentFile = @buffer.getText()
return if currentFile.length is 0
if currentFile.length < 950
@pairingChannel.trigger 'client-share-whole-file', currentFile
else
chunks = chunkString(currentFile, 950)
_.each chunks, (chunk, index) =>
setTimeout(( => @pairingChannel.trigger 'client-share-partial-file', chunk), 180 * index)
#atom-supercopair
broadcastEval: (exclusively) -> #broadcast evaluation exclusively or not
return unless @editorIsSC()
[expression, range] = @currentExpression()
changeType = 'evaluation'
event = {newRange: range, newExpression: expression}
event = {changeType: changeType, event: event, colour: @markerColour, eventType: 'broadcast-event'}
@events.push(event)
@activeRepl?.postMessage("You had broadcast: \n"+expression)
if not exclusively
@eval()
broadcastCmdPeriod: (exclusively) -> #broadcast command+period exclusively or not
changeType = 'cmd-period'
event = {}
event = {changeType: changeType, event: event, colour: @markerColour, eventType: 'broadcast-event'}
@events.push(event)
if not exclusively
@activeRepl?.cmdPeriod()
@activeRepl?.postMessage("You had broadcast: Stop!")
pairEval: (data) -> #pair evaluation
if data.event.newRange then newRange = Range.fromObject(data.event.newRange)
if data.event.newExpression then newExpression = data.event.newExpression
if data.colour then buddyColour = data.colour
if atom.config.get('supercopair.disable_broadcast')
return
if atom.config.get('supercopair.broadcast_bypass')
if not confirm("Your "+buddyColour+" buddy wants to evaluate:\n"+newExpression)
return;
switch data.changeType
when 'evaluation'
@evalWithRepl(newExpression, @currentPath(), newRange)
@activeRepl?.postMessage("Your "+buddyColour+" buddy evaluated: \n"+newExpression)
# noticeView = new AlertView "Your "+buddyColour+" buddy evaluated: \n"+newExpression
# atom.workspace.addModalPanel(item: noticeView, visible: true)
when 'cmd-period'
@activeRepl?.cmdPeriod()
@activeRepl?.postMessage("Your "+buddyColour+" buddy evaluated: Stop!")
# noticeView = new AlertView "Your "+buddyColour+" buddy evaluated: Stop!"
# atom.workspace.addModalPanel(item: noticeView, visible: true)
else
;
| 126712 | #atom-supercollider
url = require('url')
Repl = require('./repl')
## {$, Range} = require 'atom'
{$, Range} = require 'atom-space-pen-views'
#atom-pair
StartView = require './views/start-view'
InputView = require './views/input-view'
AlertView = require './views/alert-view'
require './pusher/pusher'
require './pusher/pusher-js-client-auth'
randomstring = require 'randomstring'
_ = require 'underscore'
chunkString = require './helpers/chunk-string'
HipChatInvite = require './modules/hipchat_invite'
Marker = require './modules/marker'
GrammarSync = require './modules/grammar_sync'
SuperCopairConfig = require './modules/keys_config'
{CompositeDisposable, Range} = require 'atom'
module.exports =
class Controller
#atom-pair
SuperCopairView: null
modalPanel: null
subscriptions: null
constructor: (directory) ->
#atom-supercollider
@defaultURI = "sclang://localhost:57120"
@projectRoot = if directory then directory.path else ''
@repls = {}
@activeRepl = null
@markers = []
start: ->
#atom-pair
# Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
@subscriptions = new CompositeDisposable
@editorListeners = new CompositeDisposable
# Register command that toggles this view
@subscriptions.add atom.commands.add 'atom-workspace', 'supercopair:start-new-pairing-session': => @startSession()
@subscriptions.add atom.commands.add 'atom-workspace', 'supercopair:join-pairing-session': => @joinSession()
@subscriptions.add atom.commands.add 'atom-workspace', 'supercopair:set-configuration-keys': => @setConfig()
@subscriptions.add atom.commands.add 'atom-workspace', 'supercopair:invite-over-hipchat': => @inviteOverHipChat()
@subscriptions.add atom.commands.add 'atom-workspace', 'supercopair:custom-paste': => @customPaste()
atom.commands.add 'atom-workspace', 'supercopair:hide-views': => @hidePanel()
atom.commands.add '.session-id', 'supercopair:copyid': => @copyId()
@colours = require('./helpers/colour-list')
@friendColours = []
@timeouts = []
@events = []
_.extend(@, HipChatInvite, Marker, GrammarSync, SuperCopairConfig)
#atom-supercopair
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:broadcast-eval", => @broadcastEval(false)
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:broadcast-cmd-period", => @broadcastCmdPeriod(false)
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:broadcast-eval-exclusively", => @broadcastEval(true)
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:broadcast-cmd-period-exclusively", => @broadcastCmdPeriod(true)
#atom-supercollider
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:open-post-window", => @openPostWindow(@defaultURI)
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:clear-post-window", => @clearPostWindow()
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:recompile", => @recompile()
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:cmd-period", => @cmdPeriod()
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:eval", => @eval()
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:open-help-file", => @openHelpFile()
# open a REPL for sclang on this host/port
atom.workspace.addOpener (uri, options) =>
try
{protocol, hostname, port} = url.parse(uri)
catch error
return
return unless protocol is 'sclang:'
onClose = =>
if @activeRepl is repl
@destroyRepl()
delete @repls[uri]
repl = new Repl(uri, @projectRoot, onClose)
@activateRepl repl
@repls[uri] = repl
window = repl.createPostWindow()
repl.startSCLang()
window
#atom-supercollider
stop: ->
for repl in @repls
repl.stop()
@destroyRepl()
@repls = {}
activateRepl: (repl) ->
@activeRepl = repl
@activeRepl.unsubscriber = repl.emit.subscribe (event) =>
@handleReplEvent(event)
destroyRepl: () ->
@activeRepl?.unsubscriber()
@activeRepl = null
handleReplEvent: (event) ->
error = event.value()
# only expecting compile errors for now
if error.index == 0
@openToSyntaxError(error.file, error.line, error.char)
openPostWindow: (uri) ->
repl = @repls[uri]
if repl
@activateRepl repl
else
# open links on click
fileOpener = (event) =>
# A or child of A
link = event.target.href
unless link
link = $(event.target).parents('a').attr('href')
return unless link
event.preventDefault()
if link.substr(0, 7) == 'file://'
path = link.substr(7)
atom.workspace.open(path, split: 'left', searchAllPanes: true)
return
if link.substr(0, 10) == 'scclass://'
link = link.substr(10)
[path, charPos] = link.split(':')
if ',' in charPos
[lineno, char] = charPos.split(',')
@openFile(
path,
null,
parseInt(lineno),
parseInt(char),
'line',
'line-highlight')
else
@openFile(
path,
parseInt(charPos),
null,
null,
'line',
'line-highlight')
options =
split: 'right'
searchAllPanes: true
atom.workspace.open(uri, options)
.then () =>
@activateRepl @repls[uri]
$('.post-window').on 'click', fileOpener
clearPostWindow: ->
@activeRepl?.clearPostWindow()
recompile: ->
@destroyMarkers()
if @activeRepl
@activeRepl.recompile()
else
@openPostWindow(@defaultURI)
cmdPeriod: ->
@activeRepl?.cmdPeriod()
editorIsSC: ->
editor = atom.workspace.getActiveTextEditor()
editor and editor.getGrammar().scopeName is 'source.supercollider'
currentExpression: ->
editor = atom.workspace.getActiveTextEditor()
return unless editor?
selection = editor.getLastSelection()
expression = selection.getText()
if expression
range = selection.getBufferRange()
else
# execute the line you are on
pos = editor.getCursorBufferPosition()
row = editor.getCursorScreenPosition().row
if row?
range = new Range([row, 0], [row + 1, 0])
expression = editor.lineTextForBufferRow(row)
else
range = null
expression = null
[expression, range]
currentPath: ->
editor = atom.workspace.getActiveTextEditor()
return unless editor?
editor.getPath()
eval: ->
return unless @editorIsSC()
[expression, range] = @currentExpression()
@evalWithRepl(expression, @currentPath(), range)
evalWithRepl: (expression, path, range) ->
@destroyMarkers()
return unless expression
doIt = () =>
if range?
unflash = @evalFlash(range)
onSuccess = () ->
unflash?('eval-success')
onError = (error) =>
if error.type is 'SyntaxError'
unflash?('eval-syntax-error')
if path
# offset syntax error by position of selected text in file
row = range.getRows()[0] + error.error.line
col = error.error.charPos
@openToSyntaxError(path, parseInt(row), parseInt(col))
else
# runtime error
unflash?('eval-error')
@activeRepl.eval(expression, false, path)
.then(onSuccess, onError)
if @activeRepl
# if stuck in compile error
# then post warning and return
unless @activeRepl.isCompiled()
@activeRepl.warnIsNotCompiled()
return
doIt()
else
@openPostWindow(@defaultURI)
.then doIt
openToSyntaxError: (path, line, char) ->
@openFile(path, null, line, char)
openHelpFile: ->
unless @editorIsSC()
return false
[expression, range] = @currentExpression()
base = null
# Klass.openHelpFile
klassy = /^([A-Z]{1}[a-zA-Z0-9\_]*)$/
match = expression.match(klassy)
if match
base = expression
else
# 'someMethod'.openHelpFile
# starts with lowercase has no punctuation, wrap in ''
# TODO match ops
methody = /^([a-z]{1}[a-zA-Z0-9\_]*)$/
match = expression.match(methody)
if match
base = "'#{expression}'"
else
# anything else just do a search
stringy = /^([^"]+)$/
match = expression.match(stringy)
if match
base = '"' + expression + '"'
if base
@evalWithRepl("#{base}.openHelpFile")
openFile: (uri, charPos, row, col, markerType="line", cssClass="line-error")->
options =
initialLine: row
initialColumn: col
split: 'left'
activatePane: false
searchAllPanes: true
atom.workspace.open(uri, options)
.then (editor) =>
setMark = (point) =>
editor.setCursorBufferPosition(point)
expression = editor.lineForBufferRow(point[0])
range = [point, [point[0], expression.length - 1]]
@destroyMarkers()
marker = editor.markBufferRange(range, invalidate: 'touch')
decoration = editor.decorateMarker(marker,
type: markerType,
class: cssClass)
@markers.push marker
if row?
# mark is zero indexed
return setMark([row - 1, col])
text = editor.getText()
cursor = 0
li = 0
for ll in text.split('\n')
cursor += (ll.length + 1)
if cursor > charPos
return setMark([li, cursor - charPos - ll.length])
li += 1
destroyMarkers: () ->
@markers.forEach (m) ->
m.destroy()
@markers = []
evalFlash: (range) ->
editor = atom.workspace.getActiveTextEditor()
if editor
marker = editor.markBufferRange(range, invalidate: 'touch')
decoration = editor.decorateMarker(marker,
type: 'line',
class: "eval-flash")
# return fn to flash error/success and destroy the flash
(cssClass) ->
decoration.update(type: 'line', class: cssClass)
destroy = ->
marker.destroy()
setTimeout(destroy, 100)
#atom-pair
customPaste: ->
text = atom.clipboard.read()
if text.length > 800
chunks = chunkString(text, 800)
_.each chunks, (chunk, index) =>
setTimeout(( =>
atom.clipboard.write(chunk)
@editor.pasteText()
if index is (chunks.length - 1) then atom.clipboard.write(text)
), 180 * index)
else
@editor.pasteText()
disconnect: ->
@pusher.disconnect()
@editorListeners.dispose()
_.each @friendColours, (colour) => @clearMarkers(colour)
@clearMarkers(@markerColour)
@markerColour = null
atom.views.getView(@editor).removeAttribute('id')
@hidePanel()
copyId: ->
atom.clipboard.write(@sessionId)
@startPanel.hide()
hidePanel: ->
_.each atom.workspace.getModalPanels(), (panel) -> panel.hide()
joinSession: ->
if @markerColour
alreadyPairing = new AlertView "It looks like you are already in a pairing session. Please open a new window (cmd+shift+N) to start/join a new one."
atom.workspace.addModalPanel(item: alreadyPairing, visible: true)
return
@joinView = new InputView("Enter the session ID here:")
@joinPanel = atom.workspace.addModalPanel(item: @joinView, visible: true)
@joinView.miniEditor.focus()
@joinView.on 'core:confirm', =>
@sessionId = @joinView.miniEditor.getText()
keys = @sessionId.split<KEY>("-")
[@app_key, @app_secret] = [keys[0], keys[1]]
@joinPanel.hide()
atom.workspace.open().then => @pairingSetup() #starts a new tab to join pairing session
startSession: ->
@getKeysFromConfig()
if @missingPusherKeys()
alertView = new AlertView "Please set your Pusher keys."
atom.workspace.addModalPanel(item: alertView, visible: true)
else
if @markerColour
alreadyPairing = new AlertView "It looks like you are already in a pairing session. Please disconnect or open a new window to start/join a new one."
atom.workspace.addModalPanel(item: alreadyPairing, visible: true)
return
@generateSessionId()
@startView = new StartView(@sessionId)
@startPanel = atom.workspace.addModalPanel(item: @startView, visible: true)
@startView.focus()
@markerColour = @colours[0]
@pairingSetup()
@activeRepl?.postMessage('SuperCopair: Session started!')
generateSessionId: ->
@sessionId = "#{@app_key}-#{@app_secret}-#{randomstring.generate(11)}"
pairingSetup: ->
@editor = atom.workspace.getActiveTextEditor()
if !@editor then return atom.workspace.open().then => @pairingSetup()
atom.views.getView(@editor).setAttribute('id', 'SuperCopair')
@connectToPusher()
@synchronizeColours()
@subscriptions.add atom.commands.add 'atom-workspace', 'SuperCopair:disconnect': => @disconnect()
connectToPusher: ->
@pusher = new Pusher @app_key,
authTransport: 'client'
clientAuth:
key: @app_key
secret: @app_secret
user_id: @markerColour || "blank"
@pairingChannel = @pusher.subscribe("presence-session-#{@sessionId}")
synchronizeColours: ->
@pairingChannel.bind 'pusher:subscription_succeeded', (members) =>
@membersCount = members.count
return @resubscribe() unless @markerColour
colours = Object.keys(members.members)
@friendColours = _.without(colours, @markerColour)
_.each(@friendColours, (colour) => @addMarker 0, colour)
@startPairing()
resubscribe: ->
@pairingChannel.unsubscribe()
@markerColour = @colours[@membersCount - 1]
@connectToPusher()
@synchronizeColours()
startPairing: ->
@triggerPush = true
buffer = @buffer = @editor.buffer
# listening for Pusher events
@pairingChannel.bind 'pusher:member_added', (member) =>
noticeView = new AlertView "Your pair buddy has joined the session."
atom.workspace.addModalPanel(item: noticeView, visible: true)
@sendGrammar()
@shareCurrentFile()
@friendColours.push(member.id)
@addMarker 0, member.id
@pairingChannel.bind 'client-grammar-sync', (syntax) =>
grammar = atom.grammars.grammarForScopeName(syntax)
@editor.setGrammar(grammar)
@pairingChannel.bind 'client-share-whole-file', (file) =>
@triggerPush = false
buffer.setText(file)
@triggerPush = true
@pairingChannel.bind 'client-share-partial-file', (chunk) =>
@triggerPush = false
buffer.append(chunk)
@triggerPush = true
@pairingChannel.bind 'client-change', (events) =>
_.each events, (event) =>
@changeBuffer(event) if event.eventType is 'buffer-change'
if event.eventType is 'buffer-selection'
@updateCollaboratorMarker(event)
#atom-supercopair
if event.eventType is 'broadcast-event'
@pairEval(event)
@pairingChannel.bind 'pusher:member_removed', (member) =>
@clearMarkers(member.id)
disconnectView = new AlertView "Your pair buddy has left the session."
atom.workspace.addModalPanel(item: disconnectView, visible: true)
@triggerEventQueue()
# listening for buffer events
@editorListeners.add @listenToBufferChanges()
@editorListeners.add @syncSelectionRange()
@editorListeners.add @syncGrammars()
# listening for its own demise
@listenForDestruction()
listenForDestruction: ->
@editorListeners.add @buffer.onDidDestroy => @disconnect()
@editorListeners.add @editor.onDidDestroy => @disconnect()
listenToBufferChanges: ->
@buffer.onDidChange (event) =>
return unless @triggerPush
if !(event.newText is "\n") and (event.newText.length is 0)
changeType = 'deletion'
event = {oldRange: event.oldRange}
else if event.oldRange.containsRange(event.newRange)
changeType = 'substitution'
event = {oldRange: event.oldRange, newRange: event.newRange, newText: event.newText}
else
changeType = 'insertion'
event = {newRange: event.newRange, newText: event.newText}
event = {changeType: changeType, event: event, colour: @markerColour, eventType: 'buffer-change'}
@events.push(event)
changeBuffer: (data) ->
if data.event.newRange then newRange = Range.fromObject(data.event.newRange)
if data.event.oldRange then oldRange = Range.fromObject(data.event.oldRange)
if data.event.newText then newText = data.event.newText
@triggerPush = false
@clearMarkers(data.colour)
switch data.changeType
when 'deletion'
@buffer.delete oldRange
actionArea = oldRange.start
when 'substitution'
@buffer.setTextInRange oldRange, newText
actionArea = oldRange.start
else
@buffer.insert newRange.start, newText
actionArea = newRange.start
#@editor.scrollToBufferPosition(actionArea)
@addMarker(actionArea.toArray()[0], data.colour)
@triggerPush = true
syncSelectionRange: ->
@editor.onDidChangeSelectionRange (event) =>
rows = event.newBufferRange.getRows()
return unless rows.length > 1
@events.push {eventType: 'buffer-selection', colour: @markerColour, rows: rows}
triggerEventQueue: ->
@eventInterval = setInterval(=>
if @events.length > 0
@pairingChannel.trigger 'client-change', @events
@events = []
, 120)
shareCurrentFile: ->
currentFile = @buffer.getText()
return if currentFile.length is 0
if currentFile.length < 950
@pairingChannel.trigger 'client-share-whole-file', currentFile
else
chunks = chunkString(currentFile, 950)
_.each chunks, (chunk, index) =>
setTimeout(( => @pairingChannel.trigger 'client-share-partial-file', chunk), 180 * index)
#atom-supercopair
broadcastEval: (exclusively) -> #broadcast evaluation exclusively or not
return unless @editorIsSC()
[expression, range] = @currentExpression()
changeType = 'evaluation'
event = {newRange: range, newExpression: expression}
event = {changeType: changeType, event: event, colour: @markerColour, eventType: 'broadcast-event'}
@events.push(event)
@activeRepl?.postMessage("You had broadcast: \n"+expression)
if not exclusively
@eval()
broadcastCmdPeriod: (exclusively) -> #broadcast command+period exclusively or not
changeType = 'cmd-period'
event = {}
event = {changeType: changeType, event: event, colour: @markerColour, eventType: 'broadcast-event'}
@events.push(event)
if not exclusively
@activeRepl?.cmdPeriod()
@activeRepl?.postMessage("You had broadcast: Stop!")
pairEval: (data) -> #pair evaluation
if data.event.newRange then newRange = Range.fromObject(data.event.newRange)
if data.event.newExpression then newExpression = data.event.newExpression
if data.colour then buddyColour = data.colour
if atom.config.get('supercopair.disable_broadcast')
return
if atom.config.get('supercopair.broadcast_bypass')
if not confirm("Your "+buddyColour+" buddy wants to evaluate:\n"+newExpression)
return;
switch data.changeType
when 'evaluation'
@evalWithRepl(newExpression, @currentPath(), newRange)
@activeRepl?.postMessage("Your "+buddyColour+" buddy evaluated: \n"+newExpression)
# noticeView = new AlertView "Your "+buddyColour+" buddy evaluated: \n"+newExpression
# atom.workspace.addModalPanel(item: noticeView, visible: true)
when 'cmd-period'
@activeRepl?.cmdPeriod()
@activeRepl?.postMessage("Your "+buddyColour+" buddy evaluated: Stop!")
# noticeView = new AlertView "Your "+buddyColour+" buddy evaluated: Stop!"
# atom.workspace.addModalPanel(item: noticeView, visible: true)
else
;
| true | #atom-supercollider
url = require('url')
Repl = require('./repl')
## {$, Range} = require 'atom'
{$, Range} = require 'atom-space-pen-views'
#atom-pair
StartView = require './views/start-view'
InputView = require './views/input-view'
AlertView = require './views/alert-view'
require './pusher/pusher'
require './pusher/pusher-js-client-auth'
randomstring = require 'randomstring'
_ = require 'underscore'
chunkString = require './helpers/chunk-string'
HipChatInvite = require './modules/hipchat_invite'
Marker = require './modules/marker'
GrammarSync = require './modules/grammar_sync'
SuperCopairConfig = require './modules/keys_config'
{CompositeDisposable, Range} = require 'atom'
module.exports =
class Controller
#atom-pair
SuperCopairView: null
modalPanel: null
subscriptions: null
constructor: (directory) ->
#atom-supercollider
@defaultURI = "sclang://localhost:57120"
@projectRoot = if directory then directory.path else ''
@repls = {}
@activeRepl = null
@markers = []
start: ->
#atom-pair
# Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
@subscriptions = new CompositeDisposable
@editorListeners = new CompositeDisposable
# Register command that toggles this view
@subscriptions.add atom.commands.add 'atom-workspace', 'supercopair:start-new-pairing-session': => @startSession()
@subscriptions.add atom.commands.add 'atom-workspace', 'supercopair:join-pairing-session': => @joinSession()
@subscriptions.add atom.commands.add 'atom-workspace', 'supercopair:set-configuration-keys': => @setConfig()
@subscriptions.add atom.commands.add 'atom-workspace', 'supercopair:invite-over-hipchat': => @inviteOverHipChat()
@subscriptions.add atom.commands.add 'atom-workspace', 'supercopair:custom-paste': => @customPaste()
atom.commands.add 'atom-workspace', 'supercopair:hide-views': => @hidePanel()
atom.commands.add '.session-id', 'supercopair:copyid': => @copyId()
@colours = require('./helpers/colour-list')
@friendColours = []
@timeouts = []
@events = []
_.extend(@, HipChatInvite, Marker, GrammarSync, SuperCopairConfig)
#atom-supercopair
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:broadcast-eval", => @broadcastEval(false)
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:broadcast-cmd-period", => @broadcastCmdPeriod(false)
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:broadcast-eval-exclusively", => @broadcastEval(true)
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:broadcast-cmd-period-exclusively", => @broadcastCmdPeriod(true)
#atom-supercollider
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:open-post-window", => @openPostWindow(@defaultURI)
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:clear-post-window", => @clearPostWindow()
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:recompile", => @recompile()
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:cmd-period", => @cmdPeriod()
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:eval", => @eval()
@subscriptions.add atom.commands.add 'atom-workspace', "supercopair:open-help-file", => @openHelpFile()
# open a REPL for sclang on this host/port
atom.workspace.addOpener (uri, options) =>
try
{protocol, hostname, port} = url.parse(uri)
catch error
return
return unless protocol is 'sclang:'
onClose = =>
if @activeRepl is repl
@destroyRepl()
delete @repls[uri]
repl = new Repl(uri, @projectRoot, onClose)
@activateRepl repl
@repls[uri] = repl
window = repl.createPostWindow()
repl.startSCLang()
window
#atom-supercollider
stop: ->
for repl in @repls
repl.stop()
@destroyRepl()
@repls = {}
activateRepl: (repl) ->
@activeRepl = repl
@activeRepl.unsubscriber = repl.emit.subscribe (event) =>
@handleReplEvent(event)
destroyRepl: () ->
@activeRepl?.unsubscriber()
@activeRepl = null
handleReplEvent: (event) ->
error = event.value()
# only expecting compile errors for now
if error.index == 0
@openToSyntaxError(error.file, error.line, error.char)
openPostWindow: (uri) ->
repl = @repls[uri]
if repl
@activateRepl repl
else
# open links on click
fileOpener = (event) =>
# A or child of A
link = event.target.href
unless link
link = $(event.target).parents('a').attr('href')
return unless link
event.preventDefault()
if link.substr(0, 7) == 'file://'
path = link.substr(7)
atom.workspace.open(path, split: 'left', searchAllPanes: true)
return
if link.substr(0, 10) == 'scclass://'
link = link.substr(10)
[path, charPos] = link.split(':')
if ',' in charPos
[lineno, char] = charPos.split(',')
@openFile(
path,
null,
parseInt(lineno),
parseInt(char),
'line',
'line-highlight')
else
@openFile(
path,
parseInt(charPos),
null,
null,
'line',
'line-highlight')
options =
split: 'right'
searchAllPanes: true
atom.workspace.open(uri, options)
.then () =>
@activateRepl @repls[uri]
$('.post-window').on 'click', fileOpener
clearPostWindow: ->
@activeRepl?.clearPostWindow()
recompile: ->
@destroyMarkers()
if @activeRepl
@activeRepl.recompile()
else
@openPostWindow(@defaultURI)
cmdPeriod: ->
@activeRepl?.cmdPeriod()
editorIsSC: ->
editor = atom.workspace.getActiveTextEditor()
editor and editor.getGrammar().scopeName is 'source.supercollider'
currentExpression: ->
editor = atom.workspace.getActiveTextEditor()
return unless editor?
selection = editor.getLastSelection()
expression = selection.getText()
if expression
range = selection.getBufferRange()
else
# execute the line you are on
pos = editor.getCursorBufferPosition()
row = editor.getCursorScreenPosition().row
if row?
range = new Range([row, 0], [row + 1, 0])
expression = editor.lineTextForBufferRow(row)
else
range = null
expression = null
[expression, range]
currentPath: ->
editor = atom.workspace.getActiveTextEditor()
return unless editor?
editor.getPath()
eval: ->
return unless @editorIsSC()
[expression, range] = @currentExpression()
@evalWithRepl(expression, @currentPath(), range)
evalWithRepl: (expression, path, range) ->
@destroyMarkers()
return unless expression
doIt = () =>
if range?
unflash = @evalFlash(range)
onSuccess = () ->
unflash?('eval-success')
onError = (error) =>
if error.type is 'SyntaxError'
unflash?('eval-syntax-error')
if path
# offset syntax error by position of selected text in file
row = range.getRows()[0] + error.error.line
col = error.error.charPos
@openToSyntaxError(path, parseInt(row), parseInt(col))
else
# runtime error
unflash?('eval-error')
@activeRepl.eval(expression, false, path)
.then(onSuccess, onError)
if @activeRepl
# if stuck in compile error
# then post warning and return
unless @activeRepl.isCompiled()
@activeRepl.warnIsNotCompiled()
return
doIt()
else
@openPostWindow(@defaultURI)
.then doIt
openToSyntaxError: (path, line, char) ->
@openFile(path, null, line, char)
openHelpFile: ->
unless @editorIsSC()
return false
[expression, range] = @currentExpression()
base = null
# Klass.openHelpFile
klassy = /^([A-Z]{1}[a-zA-Z0-9\_]*)$/
match = expression.match(klassy)
if match
base = expression
else
# 'someMethod'.openHelpFile
# starts with lowercase has no punctuation, wrap in ''
# TODO match ops
methody = /^([a-z]{1}[a-zA-Z0-9\_]*)$/
match = expression.match(methody)
if match
base = "'#{expression}'"
else
# anything else just do a search
stringy = /^([^"]+)$/
match = expression.match(stringy)
if match
base = '"' + expression + '"'
if base
@evalWithRepl("#{base}.openHelpFile")
openFile: (uri, charPos, row, col, markerType="line", cssClass="line-error")->
options =
initialLine: row
initialColumn: col
split: 'left'
activatePane: false
searchAllPanes: true
atom.workspace.open(uri, options)
.then (editor) =>
setMark = (point) =>
editor.setCursorBufferPosition(point)
expression = editor.lineForBufferRow(point[0])
range = [point, [point[0], expression.length - 1]]
@destroyMarkers()
marker = editor.markBufferRange(range, invalidate: 'touch')
decoration = editor.decorateMarker(marker,
type: markerType,
class: cssClass)
@markers.push marker
if row?
# mark is zero indexed
return setMark([row - 1, col])
text = editor.getText()
cursor = 0
li = 0
for ll in text.split('\n')
cursor += (ll.length + 1)
if cursor > charPos
return setMark([li, cursor - charPos - ll.length])
li += 1
destroyMarkers: () ->
@markers.forEach (m) ->
m.destroy()
@markers = []
evalFlash: (range) ->
editor = atom.workspace.getActiveTextEditor()
if editor
marker = editor.markBufferRange(range, invalidate: 'touch')
decoration = editor.decorateMarker(marker,
type: 'line',
class: "eval-flash")
# return fn to flash error/success and destroy the flash
(cssClass) ->
decoration.update(type: 'line', class: cssClass)
destroy = ->
marker.destroy()
setTimeout(destroy, 100)
#atom-pair
customPaste: ->
text = atom.clipboard.read()
if text.length > 800
chunks = chunkString(text, 800)
_.each chunks, (chunk, index) =>
setTimeout(( =>
atom.clipboard.write(chunk)
@editor.pasteText()
if index is (chunks.length - 1) then atom.clipboard.write(text)
), 180 * index)
else
@editor.pasteText()
disconnect: ->
@pusher.disconnect()
@editorListeners.dispose()
_.each @friendColours, (colour) => @clearMarkers(colour)
@clearMarkers(@markerColour)
@markerColour = null
atom.views.getView(@editor).removeAttribute('id')
@hidePanel()
copyId: ->
atom.clipboard.write(@sessionId)
@startPanel.hide()
hidePanel: ->
_.each atom.workspace.getModalPanels(), (panel) -> panel.hide()
joinSession: ->
if @markerColour
alreadyPairing = new AlertView "It looks like you are already in a pairing session. Please open a new window (cmd+shift+N) to start/join a new one."
atom.workspace.addModalPanel(item: alreadyPairing, visible: true)
return
@joinView = new InputView("Enter the session ID here:")
@joinPanel = atom.workspace.addModalPanel(item: @joinView, visible: true)
@joinView.miniEditor.focus()
@joinView.on 'core:confirm', =>
@sessionId = @joinView.miniEditor.getText()
keys = @sessionId.splitPI:KEY:<KEY>END_PI("-")
[@app_key, @app_secret] = [keys[0], keys[1]]
@joinPanel.hide()
atom.workspace.open().then => @pairingSetup() #starts a new tab to join pairing session
startSession: ->
@getKeysFromConfig()
if @missingPusherKeys()
alertView = new AlertView "Please set your Pusher keys."
atom.workspace.addModalPanel(item: alertView, visible: true)
else
if @markerColour
alreadyPairing = new AlertView "It looks like you are already in a pairing session. Please disconnect or open a new window to start/join a new one."
atom.workspace.addModalPanel(item: alreadyPairing, visible: true)
return
@generateSessionId()
@startView = new StartView(@sessionId)
@startPanel = atom.workspace.addModalPanel(item: @startView, visible: true)
@startView.focus()
@markerColour = @colours[0]
@pairingSetup()
@activeRepl?.postMessage('SuperCopair: Session started!')
generateSessionId: ->
@sessionId = "#{@app_key}-#{@app_secret}-#{randomstring.generate(11)}"
pairingSetup: ->
@editor = atom.workspace.getActiveTextEditor()
if !@editor then return atom.workspace.open().then => @pairingSetup()
atom.views.getView(@editor).setAttribute('id', 'SuperCopair')
@connectToPusher()
@synchronizeColours()
@subscriptions.add atom.commands.add 'atom-workspace', 'SuperCopair:disconnect': => @disconnect()
connectToPusher: ->
@pusher = new Pusher @app_key,
authTransport: 'client'
clientAuth:
key: @app_key
secret: @app_secret
user_id: @markerColour || "blank"
@pairingChannel = @pusher.subscribe("presence-session-#{@sessionId}")
synchronizeColours: ->
@pairingChannel.bind 'pusher:subscription_succeeded', (members) =>
@membersCount = members.count
return @resubscribe() unless @markerColour
colours = Object.keys(members.members)
@friendColours = _.without(colours, @markerColour)
_.each(@friendColours, (colour) => @addMarker 0, colour)
@startPairing()
resubscribe: ->
@pairingChannel.unsubscribe()
@markerColour = @colours[@membersCount - 1]
@connectToPusher()
@synchronizeColours()
startPairing: ->
@triggerPush = true
buffer = @buffer = @editor.buffer
# listening for Pusher events
@pairingChannel.bind 'pusher:member_added', (member) =>
noticeView = new AlertView "Your pair buddy has joined the session."
atom.workspace.addModalPanel(item: noticeView, visible: true)
@sendGrammar()
@shareCurrentFile()
@friendColours.push(member.id)
@addMarker 0, member.id
@pairingChannel.bind 'client-grammar-sync', (syntax) =>
grammar = atom.grammars.grammarForScopeName(syntax)
@editor.setGrammar(grammar)
@pairingChannel.bind 'client-share-whole-file', (file) =>
@triggerPush = false
buffer.setText(file)
@triggerPush = true
@pairingChannel.bind 'client-share-partial-file', (chunk) =>
@triggerPush = false
buffer.append(chunk)
@triggerPush = true
@pairingChannel.bind 'client-change', (events) =>
_.each events, (event) =>
@changeBuffer(event) if event.eventType is 'buffer-change'
if event.eventType is 'buffer-selection'
@updateCollaboratorMarker(event)
#atom-supercopair
if event.eventType is 'broadcast-event'
@pairEval(event)
@pairingChannel.bind 'pusher:member_removed', (member) =>
@clearMarkers(member.id)
disconnectView = new AlertView "Your pair buddy has left the session."
atom.workspace.addModalPanel(item: disconnectView, visible: true)
@triggerEventQueue()
# listening for buffer events
@editorListeners.add @listenToBufferChanges()
@editorListeners.add @syncSelectionRange()
@editorListeners.add @syncGrammars()
# listening for its own demise
@listenForDestruction()
listenForDestruction: ->
@editorListeners.add @buffer.onDidDestroy => @disconnect()
@editorListeners.add @editor.onDidDestroy => @disconnect()
listenToBufferChanges: ->
@buffer.onDidChange (event) =>
return unless @triggerPush
if !(event.newText is "\n") and (event.newText.length is 0)
changeType = 'deletion'
event = {oldRange: event.oldRange}
else if event.oldRange.containsRange(event.newRange)
changeType = 'substitution'
event = {oldRange: event.oldRange, newRange: event.newRange, newText: event.newText}
else
changeType = 'insertion'
event = {newRange: event.newRange, newText: event.newText}
event = {changeType: changeType, event: event, colour: @markerColour, eventType: 'buffer-change'}
@events.push(event)
changeBuffer: (data) ->
if data.event.newRange then newRange = Range.fromObject(data.event.newRange)
if data.event.oldRange then oldRange = Range.fromObject(data.event.oldRange)
if data.event.newText then newText = data.event.newText
@triggerPush = false
@clearMarkers(data.colour)
switch data.changeType
when 'deletion'
@buffer.delete oldRange
actionArea = oldRange.start
when 'substitution'
@buffer.setTextInRange oldRange, newText
actionArea = oldRange.start
else
@buffer.insert newRange.start, newText
actionArea = newRange.start
#@editor.scrollToBufferPosition(actionArea)
@addMarker(actionArea.toArray()[0], data.colour)
@triggerPush = true
syncSelectionRange: ->
@editor.onDidChangeSelectionRange (event) =>
rows = event.newBufferRange.getRows()
return unless rows.length > 1
@events.push {eventType: 'buffer-selection', colour: @markerColour, rows: rows}
triggerEventQueue: ->
@eventInterval = setInterval(=>
if @events.length > 0
@pairingChannel.trigger 'client-change', @events
@events = []
, 120)
shareCurrentFile: ->
currentFile = @buffer.getText()
return if currentFile.length is 0
if currentFile.length < 950
@pairingChannel.trigger 'client-share-whole-file', currentFile
else
chunks = chunkString(currentFile, 950)
_.each chunks, (chunk, index) =>
setTimeout(( => @pairingChannel.trigger 'client-share-partial-file', chunk), 180 * index)
#atom-supercopair
broadcastEval: (exclusively) -> #broadcast evaluation exclusively or not
return unless @editorIsSC()
[expression, range] = @currentExpression()
changeType = 'evaluation'
event = {newRange: range, newExpression: expression}
event = {changeType: changeType, event: event, colour: @markerColour, eventType: 'broadcast-event'}
@events.push(event)
@activeRepl?.postMessage("You had broadcast: \n"+expression)
if not exclusively
@eval()
broadcastCmdPeriod: (exclusively) -> #broadcast command+period exclusively or not
changeType = 'cmd-period'
event = {}
event = {changeType: changeType, event: event, colour: @markerColour, eventType: 'broadcast-event'}
@events.push(event)
if not exclusively
@activeRepl?.cmdPeriod()
@activeRepl?.postMessage("You had broadcast: Stop!")
pairEval: (data) -> #pair evaluation
if data.event.newRange then newRange = Range.fromObject(data.event.newRange)
if data.event.newExpression then newExpression = data.event.newExpression
if data.colour then buddyColour = data.colour
if atom.config.get('supercopair.disable_broadcast')
return
if atom.config.get('supercopair.broadcast_bypass')
if not confirm("Your "+buddyColour+" buddy wants to evaluate:\n"+newExpression)
return;
switch data.changeType
when 'evaluation'
@evalWithRepl(newExpression, @currentPath(), newRange)
@activeRepl?.postMessage("Your "+buddyColour+" buddy evaluated: \n"+newExpression)
# noticeView = new AlertView "Your "+buddyColour+" buddy evaluated: \n"+newExpression
# atom.workspace.addModalPanel(item: noticeView, visible: true)
when 'cmd-period'
@activeRepl?.cmdPeriod()
@activeRepl?.postMessage("Your "+buddyColour+" buddy evaluated: Stop!")
# noticeView = new AlertView "Your "+buddyColour+" buddy evaluated: Stop!"
# atom.workspace.addModalPanel(item: noticeView, visible: true)
else
;
|
[
{
"context": "rverPort}\"\n auth:\n username: 'user-uuid'\n password: 'user-token'\n jso",
"end": 1228,
"score": 0.9996647834777832,
"start": 1219,
"tag": "USERNAME",
"value": "user-uuid"
},
{
"context": " username: 'user-uuid'\n ... | test/integration/send-message-spec.coffee | octoblu/meshblu-responder-service | 0 | http = require 'http'
request = require 'request'
shmock = require '@octoblu/shmock'
Server = require '../../src/server'
FakeMeshblu = require '../fake-meshblu'
describe 'Send Message', ->
beforeEach (done) ->
@meshblu = shmock 0xd00d
serverOptions =
port: undefined,
disableLogging: true
meshbluConfig =
server: 'localhost'
port: 0xd00d
@fakeMeshblu = new FakeMeshblu
uuid =
v1: sinon.stub().returns 'some-response-uuid'
@server = new Server serverOptions, {meshbluConfig, uuid, Meshblu: @fakeMeshblu}
@server.run =>
@serverPort = @server.address().port
done()
afterEach (done) ->
@server.stop done
afterEach (done) ->
@meshblu.close done
describe 'On POST /messages', ->
describe 'when it succeeds', ->
beforeEach (done) ->
userAuth = new Buffer('user-uuid:user-token').toString 'base64'
@authDevice = @meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{userAuth}"
.reply 200, uuid: 'user-uuid', token: 'user-token'
options =
uri: '/messages'
baseUrl: "http://localhost:#{@serverPort}"
auth:
username: 'user-uuid'
password: 'user-token'
json:
foo: 'bar'
request.post options, (error, @response, @body) =>
done error
it 'should auth the device', ->
@authDevice.done()
it 'should return a 200', ->
expect(@response.statusCode).to.equal 200
describe 'when it times out', ->
beforeEach (done) ->
@timeout 6000
userAuth = new Buffer('user-uuid:user-token').toString 'base64'
@authDevice = @meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{userAuth}"
.reply 200, uuid: 'user-uuid', token: 'user-token'
@fakeMeshblu.failOnEvent 'message'
options =
uri: '/messages'
baseUrl: "http://localhost:#{@serverPort}"
auth:
username: 'user-uuid'
password: 'user-token'
json:
foo: 'bar'
request.post options, (error, @response, @body) =>
done error
it 'should auth the device', ->
@authDevice.done()
it 'should return a 408', ->
expect(@response.statusCode).to.equal 408
describe 'when it fires not ready', ->
beforeEach (done) ->
userAuth = new Buffer('user-uuid:user-token').toString 'base64'
@authDevice = @meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{userAuth}"
.reply 200, uuid: 'user-uuid', token: 'user-token'
@fakeMeshblu.fireNotReady()
options =
uri: '/messages'
baseUrl: "http://localhost:#{@serverPort}"
auth:
username: 'user-uuid'
password: 'user-token'
json:
foo: 'bar'
request.post options, (error, @response, @body) =>
done error
it 'should auth the device', ->
@authDevice.done()
it 'should return a 500', ->
expect(@response.statusCode).to.equal 500
| 213372 | http = require 'http'
request = require 'request'
shmock = require '@octoblu/shmock'
Server = require '../../src/server'
FakeMeshblu = require '../fake-meshblu'
describe 'Send Message', ->
beforeEach (done) ->
@meshblu = shmock 0xd00d
serverOptions =
port: undefined,
disableLogging: true
meshbluConfig =
server: 'localhost'
port: 0xd00d
@fakeMeshblu = new FakeMeshblu
uuid =
v1: sinon.stub().returns 'some-response-uuid'
@server = new Server serverOptions, {meshbluConfig, uuid, Meshblu: @fakeMeshblu}
@server.run =>
@serverPort = @server.address().port
done()
afterEach (done) ->
@server.stop done
afterEach (done) ->
@meshblu.close done
describe 'On POST /messages', ->
describe 'when it succeeds', ->
beforeEach (done) ->
userAuth = new Buffer('user-uuid:user-token').toString 'base64'
@authDevice = @meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{userAuth}"
.reply 200, uuid: 'user-uuid', token: 'user-token'
options =
uri: '/messages'
baseUrl: "http://localhost:#{@serverPort}"
auth:
username: 'user-uuid'
password: '<PASSWORD>'
json:
foo: 'bar'
request.post options, (error, @response, @body) =>
done error
it 'should auth the device', ->
@authDevice.done()
it 'should return a 200', ->
expect(@response.statusCode).to.equal 200
describe 'when it times out', ->
beforeEach (done) ->
@timeout 6000
userAuth = new Buffer('user-uuid:user-token').toString 'base64'
@authDevice = @meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{userAuth}"
.reply 200, uuid: 'user-uuid', token: '<PASSWORD>'
@fakeMeshblu.failOnEvent 'message'
options =
uri: '/messages'
baseUrl: "http://localhost:#{@serverPort}"
auth:
username: 'user-uuid'
password: '<PASSWORD>'
json:
foo: 'bar'
request.post options, (error, @response, @body) =>
done error
it 'should auth the device', ->
@authDevice.done()
it 'should return a 408', ->
expect(@response.statusCode).to.equal 408
describe 'when it fires not ready', ->
beforeEach (done) ->
userAuth = new Buffer('user-uuid:user-token').toString 'base64'
@authDevice = @meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{userAuth}"
.reply 200, uuid: 'user-uuid', token: 'user<PASSWORD>-token'
@fakeMeshblu.fireNotReady()
options =
uri: '/messages'
baseUrl: "http://localhost:#{@serverPort}"
auth:
username: 'user-uuid'
password: '<PASSWORD>'
json:
foo: 'bar'
request.post options, (error, @response, @body) =>
done error
it 'should auth the device', ->
@authDevice.done()
it 'should return a 500', ->
expect(@response.statusCode).to.equal 500
| true | http = require 'http'
request = require 'request'
shmock = require '@octoblu/shmock'
Server = require '../../src/server'
FakeMeshblu = require '../fake-meshblu'
describe 'Send Message', ->
beforeEach (done) ->
@meshblu = shmock 0xd00d
serverOptions =
port: undefined,
disableLogging: true
meshbluConfig =
server: 'localhost'
port: 0xd00d
@fakeMeshblu = new FakeMeshblu
uuid =
v1: sinon.stub().returns 'some-response-uuid'
@server = new Server serverOptions, {meshbluConfig, uuid, Meshblu: @fakeMeshblu}
@server.run =>
@serverPort = @server.address().port
done()
afterEach (done) ->
@server.stop done
afterEach (done) ->
@meshblu.close done
describe 'On POST /messages', ->
describe 'when it succeeds', ->
beforeEach (done) ->
userAuth = new Buffer('user-uuid:user-token').toString 'base64'
@authDevice = @meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{userAuth}"
.reply 200, uuid: 'user-uuid', token: 'user-token'
options =
uri: '/messages'
baseUrl: "http://localhost:#{@serverPort}"
auth:
username: 'user-uuid'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
json:
foo: 'bar'
request.post options, (error, @response, @body) =>
done error
it 'should auth the device', ->
@authDevice.done()
it 'should return a 200', ->
expect(@response.statusCode).to.equal 200
describe 'when it times out', ->
beforeEach (done) ->
@timeout 6000
userAuth = new Buffer('user-uuid:user-token').toString 'base64'
@authDevice = @meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{userAuth}"
.reply 200, uuid: 'user-uuid', token: 'PI:PASSWORD:<PASSWORD>END_PI'
@fakeMeshblu.failOnEvent 'message'
options =
uri: '/messages'
baseUrl: "http://localhost:#{@serverPort}"
auth:
username: 'user-uuid'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
json:
foo: 'bar'
request.post options, (error, @response, @body) =>
done error
it 'should auth the device', ->
@authDevice.done()
it 'should return a 408', ->
expect(@response.statusCode).to.equal 408
describe 'when it fires not ready', ->
beforeEach (done) ->
userAuth = new Buffer('user-uuid:user-token').toString 'base64'
@authDevice = @meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{userAuth}"
.reply 200, uuid: 'user-uuid', token: 'userPI:PASSWORD:<PASSWORD>END_PI-token'
@fakeMeshblu.fireNotReady()
options =
uri: '/messages'
baseUrl: "http://localhost:#{@serverPort}"
auth:
username: 'user-uuid'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
json:
foo: 'bar'
request.post options, (error, @response, @body) =>
done error
it 'should auth the device', ->
@authDevice.done()
it 'should return a 500', ->
expect(@response.statusCode).to.equal 500
|
[
{
"context": "tScope.$new()\n $scope.ann = {id: 401, name: \"Ann\"}\n $scope.myfields = [{key: 'age', label: \"A",
"end": 812,
"score": 0.9998055696487427,
"start": 809,
"tag": "NAME",
"value": "Ann"
},
{
"context": "Equal(true)\n\n fetch.resolve({id: 401, name: \"Ann\... | karma/test-directives.coffee | rapidpro/ureport-partners | 21 | # Unit tests for our Angular directives
describe('directives:', () ->
$compile = null
$rootScope = null
$templateCache = null
$q = null
$filter = null
beforeEach(() ->
module('templates')
module('cases')
inject((_$compile_, _$rootScope_, _$templateCache_, _$q_, _$filter_) ->
$compile = _$compile_
$rootScope = _$rootScope_
$templateCache = _$templateCache_
$q = _$q_
$filter = _$filter_
)
)
describe('contact', () ->
ContactService = null
beforeEach(() ->
inject((_ContactService_) ->
ContactService = _ContactService_
)
)
it('replaces element', () ->
$templateCache.put('/partials/directive_contact.html', '[[ contact.name ]]')
$scope = $rootScope.$new()
$scope.ann = {id: 401, name: "Ann"}
$scope.myfields = [{key: 'age', label: "Age"}]
fetch = spyOnPromise($q, $scope, ContactService, 'fetch')
element = $compile('<cp-contact contact="ann" fields="myfields" />')($scope)
$rootScope.$digest()
expect(element.html()).toContain("Ann");
expect(element.isolateScope().contact).toEqual($scope.ann)
expect(element.isolateScope().fields).toEqual([{key: 'age', label: "Age"}])
expect(element.isolateScope().fetched).toEqual(false)
expect(element.isolateScope().popoverIsOpen).toEqual(false)
expect(element.isolateScope().popoverTemplateUrl).toEqual('/partials/popover_contact.html')
element.isolateScope().openPopover()
expect(element.isolateScope().popoverIsOpen).toEqual(true)
fetch.resolve({id: 401, name: "Ann", fields:{age: 35}})
expect(element.isolateScope().fetched).toEqual(true)
element.isolateScope().closePopover()
expect(element.isolateScope().popoverIsOpen).toEqual(false)
)
)
#=======================================================================
# Tests for date tooltip
#=======================================================================
describe('cpDate', () ->
it('adds tooltip at the specified position on the date', () ->
$scope = $rootScope.$new()
$scope.time = new Date "December 25, 2016 23:15:00"
template = $compile('<cp-date time="time" tooltip-position="top-left" />')
element = template($scope)[0]
$rootScope.$digest()
autodate = $filter('autodate')
expect(element.textContent).toMatch(autodate($scope.time))
div = element.querySelector('div')
expect(div.hasAttribute("uib-tooltip")).toBe(true)
fulldate = $filter('fulldate')
expect(div.getAttribute("uib-tooltip")).toEqual(fulldate($scope.time))
expect(div.hasAttribute("tooltip-placement")).toBe(true)
expect(div.getAttribute("tooltip-placement")).toEqual("top-left")
)
it('adds tooltip at default position on the date', () ->
$scope = $rootScope.$new()
$scope.time = new Date "December 25, 2016 23:15:00"
template = $compile('<cp-date time="time" />')
element = template($scope)[0]
$rootScope.$digest()
autodate = $filter('autodate')
expect(element.textContent).toMatch(autodate($scope.time))
div = element.querySelector('div')
expect(div.hasAttribute("uib-tooltip")).toBe(true)
fulldate = $filter('fulldate')
expect(div.getAttribute("uib-tooltip")).toEqual(fulldate($scope.time))
expect(div.hasAttribute("tooltip-placement")).toBe(true)
expect(div.getAttribute("tooltip-placement")).toEqual("top-right")
)
)
describe('fieldvalue', () ->
$filter = null
beforeEach(() ->
inject(( _$filter_) ->
$filter = _$filter_
)
)
it('it looksup and formats value based on type', () ->
$scope = $rootScope.$new()
$scope.ann = {id: 401, name: "Ann", fields: {nid: 1234567, edd: '2016-07-04T12:59:46.309033Z'}}
$scope.myfields = [
{key: 'nid', label: "NID", value_type:'N'},
{key: 'edd', label: "EDD", value_type:'D'},
{key: 'nickname', label: "Nickname", value_type:'T'}
]
# check numerical field
element = $compile('<cp-fieldvalue contact="ann" field="myfields[0]" />')($scope)
$rootScope.$digest()
expect(element.isolateScope().contact).toEqual($scope.ann)
expect(element.isolateScope().field).toEqual($scope.myfields[0])
expect(element.isolateScope().value).toEqual("1,234,567")
expect(element.text()).toEqual("1,234,567")
# check date field
element = $compile('<cp-fieldvalue contact="ann" field="myfields[1]" />')($scope)
$rootScope.$digest()
expect(element.text()).toEqual("Jul 4, 2016")
# check field with no value
element = $compile('<cp-fieldvalue contact="ann" field="myfields[2]" />')($scope)
$rootScope.$digest()
expect(element.text()).toEqual("--")
)
)
#=======================================================================
# Tests for URN
#=======================================================================
describe('cpUrn', () ->
it('formats a URN as a link', () ->
$scope = $rootScope.$new()
$scope.urn = 'tel:+11234567890'
el = $compile('<cp-urn urn="urn" />')($scope)[0]
$rootScope.$digest()
link = el.querySelector('a')
expect(link.href).toEqual('tel:+11234567890')
expect(link.textContent).toEqual('+11234567890')
$scope.urn = 'twitter:bobby'
el = $compile('<cp-urn urn="urn" />')($scope)[0]
$rootScope.$digest()
link = el.querySelector('a')
expect(link.href).toEqual('https://twitter.com/bobby')
expect(link.textContent).toEqual('bobby')
$scope.urn = 'mailto:jim@unicef.org'
el = $compile('<cp-urn urn="urn" />')($scope)[0]
$rootScope.$digest()
link = el.querySelector('a')
expect(link.href).toEqual('mailto:jim@unicef.org')
expect(link.textContent).toEqual('jim@unicef.org')
)
)
)
| 17225 | # Unit tests for our Angular directives
describe('directives:', () ->
$compile = null
$rootScope = null
$templateCache = null
$q = null
$filter = null
beforeEach(() ->
module('templates')
module('cases')
inject((_$compile_, _$rootScope_, _$templateCache_, _$q_, _$filter_) ->
$compile = _$compile_
$rootScope = _$rootScope_
$templateCache = _$templateCache_
$q = _$q_
$filter = _$filter_
)
)
describe('contact', () ->
ContactService = null
beforeEach(() ->
inject((_ContactService_) ->
ContactService = _ContactService_
)
)
it('replaces element', () ->
$templateCache.put('/partials/directive_contact.html', '[[ contact.name ]]')
$scope = $rootScope.$new()
$scope.ann = {id: 401, name: "<NAME>"}
$scope.myfields = [{key: 'age', label: "Age"}]
fetch = spyOnPromise($q, $scope, ContactService, 'fetch')
element = $compile('<cp-contact contact="ann" fields="myfields" />')($scope)
$rootScope.$digest()
expect(element.html()).toContain("Ann");
expect(element.isolateScope().contact).toEqual($scope.ann)
expect(element.isolateScope().fields).toEqual([{key: 'age', label: "Age"}])
expect(element.isolateScope().fetched).toEqual(false)
expect(element.isolateScope().popoverIsOpen).toEqual(false)
expect(element.isolateScope().popoverTemplateUrl).toEqual('/partials/popover_contact.html')
element.isolateScope().openPopover()
expect(element.isolateScope().popoverIsOpen).toEqual(true)
fetch.resolve({id: 401, name: "<NAME>", fields:{age: 35}})
expect(element.isolateScope().fetched).toEqual(true)
element.isolateScope().closePopover()
expect(element.isolateScope().popoverIsOpen).toEqual(false)
)
)
#=======================================================================
# Tests for date tooltip
#=======================================================================
describe('cpDate', () ->
it('adds tooltip at the specified position on the date', () ->
$scope = $rootScope.$new()
$scope.time = new Date "December 25, 2016 23:15:00"
template = $compile('<cp-date time="time" tooltip-position="top-left" />')
element = template($scope)[0]
$rootScope.$digest()
autodate = $filter('autodate')
expect(element.textContent).toMatch(autodate($scope.time))
div = element.querySelector('div')
expect(div.hasAttribute("uib-tooltip")).toBe(true)
fulldate = $filter('fulldate')
expect(div.getAttribute("uib-tooltip")).toEqual(fulldate($scope.time))
expect(div.hasAttribute("tooltip-placement")).toBe(true)
expect(div.getAttribute("tooltip-placement")).toEqual("top-left")
)
it('adds tooltip at default position on the date', () ->
$scope = $rootScope.$new()
$scope.time = new Date "December 25, 2016 23:15:00"
template = $compile('<cp-date time="time" />')
element = template($scope)[0]
$rootScope.$digest()
autodate = $filter('autodate')
expect(element.textContent).toMatch(autodate($scope.time))
div = element.querySelector('div')
expect(div.hasAttribute("uib-tooltip")).toBe(true)
fulldate = $filter('fulldate')
expect(div.getAttribute("uib-tooltip")).toEqual(fulldate($scope.time))
expect(div.hasAttribute("tooltip-placement")).toBe(true)
expect(div.getAttribute("tooltip-placement")).toEqual("top-right")
)
)
describe('fieldvalue', () ->
$filter = null
beforeEach(() ->
inject(( _$filter_) ->
$filter = _$filter_
)
)
it('it looksup and formats value based on type', () ->
$scope = $rootScope.$new()
$scope.ann = {id: 401, name: "<NAME>", fields: {nid: 1234567, edd: '2016-07-04T12:59:46.309033Z'}}
$scope.myfields = [
{key: 'nid', label: "NID", value_type:'N'},
{key: 'edd', label: "EDD", value_type:'D'},
{key: 'nickname', label: "<NAME>", value_type:'T'}
]
# check numerical field
element = $compile('<cp-fieldvalue contact="ann" field="myfields[0]" />')($scope)
$rootScope.$digest()
expect(element.isolateScope().contact).toEqual($scope.ann)
expect(element.isolateScope().field).toEqual($scope.myfields[0])
expect(element.isolateScope().value).toEqual("1,234,567")
expect(element.text()).toEqual("1,234,567")
# check date field
element = $compile('<cp-fieldvalue contact="ann" field="myfields[1]" />')($scope)
$rootScope.$digest()
expect(element.text()).toEqual("Jul 4, 2016")
# check field with no value
element = $compile('<cp-fieldvalue contact="ann" field="myfields[2]" />')($scope)
$rootScope.$digest()
expect(element.text()).toEqual("--")
)
)
#=======================================================================
# Tests for URN
#=======================================================================
describe('cpUrn', () ->
it('formats a URN as a link', () ->
$scope = $rootScope.$new()
$scope.urn = 'tel:+11234567890'
el = $compile('<cp-urn urn="urn" />')($scope)[0]
$rootScope.$digest()
link = el.querySelector('a')
expect(link.href).toEqual('tel:+11234567890')
expect(link.textContent).toEqual('+11234567890')
$scope.urn = 'twitter:bobby'
el = $compile('<cp-urn urn="urn" />')($scope)[0]
$rootScope.$digest()
link = el.querySelector('a')
expect(link.href).toEqual('https://twitter.com/bobby')
expect(link.textContent).toEqual('bobby')
$scope.urn = 'mailto:<EMAIL>'
el = $compile('<cp-urn urn="urn" />')($scope)[0]
$rootScope.$digest()
link = el.querySelector('a')
expect(link.href).toEqual('mailto:<EMAIL>')
expect(link.textContent).toEqual('<EMAIL>')
)
)
)
| true | # Unit tests for our Angular directives
describe('directives:', () ->
$compile = null
$rootScope = null
$templateCache = null
$q = null
$filter = null
beforeEach(() ->
module('templates')
module('cases')
inject((_$compile_, _$rootScope_, _$templateCache_, _$q_, _$filter_) ->
$compile = _$compile_
$rootScope = _$rootScope_
$templateCache = _$templateCache_
$q = _$q_
$filter = _$filter_
)
)
describe('contact', () ->
ContactService = null
beforeEach(() ->
inject((_ContactService_) ->
ContactService = _ContactService_
)
)
it('replaces element', () ->
$templateCache.put('/partials/directive_contact.html', '[[ contact.name ]]')
$scope = $rootScope.$new()
$scope.ann = {id: 401, name: "PI:NAME:<NAME>END_PI"}
$scope.myfields = [{key: 'age', label: "Age"}]
fetch = spyOnPromise($q, $scope, ContactService, 'fetch')
element = $compile('<cp-contact contact="ann" fields="myfields" />')($scope)
$rootScope.$digest()
expect(element.html()).toContain("Ann");
expect(element.isolateScope().contact).toEqual($scope.ann)
expect(element.isolateScope().fields).toEqual([{key: 'age', label: "Age"}])
expect(element.isolateScope().fetched).toEqual(false)
expect(element.isolateScope().popoverIsOpen).toEqual(false)
expect(element.isolateScope().popoverTemplateUrl).toEqual('/partials/popover_contact.html')
element.isolateScope().openPopover()
expect(element.isolateScope().popoverIsOpen).toEqual(true)
fetch.resolve({id: 401, name: "PI:NAME:<NAME>END_PI", fields:{age: 35}})
expect(element.isolateScope().fetched).toEqual(true)
element.isolateScope().closePopover()
expect(element.isolateScope().popoverIsOpen).toEqual(false)
)
)
#=======================================================================
# Tests for date tooltip
#=======================================================================
describe('cpDate', () ->
it('adds tooltip at the specified position on the date', () ->
$scope = $rootScope.$new()
$scope.time = new Date "December 25, 2016 23:15:00"
template = $compile('<cp-date time="time" tooltip-position="top-left" />')
element = template($scope)[0]
$rootScope.$digest()
autodate = $filter('autodate')
expect(element.textContent).toMatch(autodate($scope.time))
div = element.querySelector('div')
expect(div.hasAttribute("uib-tooltip")).toBe(true)
fulldate = $filter('fulldate')
expect(div.getAttribute("uib-tooltip")).toEqual(fulldate($scope.time))
expect(div.hasAttribute("tooltip-placement")).toBe(true)
expect(div.getAttribute("tooltip-placement")).toEqual("top-left")
)
it('adds tooltip at default position on the date', () ->
$scope = $rootScope.$new()
$scope.time = new Date "December 25, 2016 23:15:00"
template = $compile('<cp-date time="time" />')
element = template($scope)[0]
$rootScope.$digest()
autodate = $filter('autodate')
expect(element.textContent).toMatch(autodate($scope.time))
div = element.querySelector('div')
expect(div.hasAttribute("uib-tooltip")).toBe(true)
fulldate = $filter('fulldate')
expect(div.getAttribute("uib-tooltip")).toEqual(fulldate($scope.time))
expect(div.hasAttribute("tooltip-placement")).toBe(true)
expect(div.getAttribute("tooltip-placement")).toEqual("top-right")
)
)
describe('fieldvalue', () ->
$filter = null
beforeEach(() ->
inject(( _$filter_) ->
$filter = _$filter_
)
)
it('it looksup and formats value based on type', () ->
$scope = $rootScope.$new()
$scope.ann = {id: 401, name: "PI:NAME:<NAME>END_PI", fields: {nid: 1234567, edd: '2016-07-04T12:59:46.309033Z'}}
$scope.myfields = [
{key: 'nid', label: "NID", value_type:'N'},
{key: 'edd', label: "EDD", value_type:'D'},
{key: 'nickname', label: "PI:NAME:<NAME>END_PI", value_type:'T'}
]
# check numerical field
element = $compile('<cp-fieldvalue contact="ann" field="myfields[0]" />')($scope)
$rootScope.$digest()
expect(element.isolateScope().contact).toEqual($scope.ann)
expect(element.isolateScope().field).toEqual($scope.myfields[0])
expect(element.isolateScope().value).toEqual("1,234,567")
expect(element.text()).toEqual("1,234,567")
# check date field
element = $compile('<cp-fieldvalue contact="ann" field="myfields[1]" />')($scope)
$rootScope.$digest()
expect(element.text()).toEqual("Jul 4, 2016")
# check field with no value
element = $compile('<cp-fieldvalue contact="ann" field="myfields[2]" />')($scope)
$rootScope.$digest()
expect(element.text()).toEqual("--")
)
)
#=======================================================================
# Tests for URN
#=======================================================================
describe('cpUrn', () ->
it('formats a URN as a link', () ->
$scope = $rootScope.$new()
$scope.urn = 'tel:+11234567890'
el = $compile('<cp-urn urn="urn" />')($scope)[0]
$rootScope.$digest()
link = el.querySelector('a')
expect(link.href).toEqual('tel:+11234567890')
expect(link.textContent).toEqual('+11234567890')
$scope.urn = 'twitter:bobby'
el = $compile('<cp-urn urn="urn" />')($scope)[0]
$rootScope.$digest()
link = el.querySelector('a')
expect(link.href).toEqual('https://twitter.com/bobby')
expect(link.textContent).toEqual('bobby')
$scope.urn = 'mailto:PI:EMAIL:<EMAIL>END_PI'
el = $compile('<cp-urn urn="urn" />')($scope)[0]
$rootScope.$digest()
link = el.querySelector('a')
expect(link.href).toEqual('mailto:PI:EMAIL:<EMAIL>END_PI')
expect(link.textContent).toEqual('PI:EMAIL:<EMAIL>END_PI')
)
)
)
|
[
{
"context": " rich text editing jQuery UI widget\n# (c) 2011 Henri Bergius, IKS Consortium\n# Hallo may be freely distrib",
"end": 79,
"score": 0.999855637550354,
"start": 66,
"tag": "NAME",
"value": "Henri Bergius"
}
] | src/plugins/cleanup.coffee | git-j/hallo | 0 | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 Henri Bergius, IKS Consortium
# Hallo may be freely distributed under the MIT license
# Plugin to minimalistic add a table to the editable
((jQuery) ->
jQuery.widget 'IKS.hallocleanup',
dropdownform: null
tmpid: 0
html: null
debug: false
options:
editable: null
toolbar: null
uuid: ''
elements: [
'rows'
'cols'
'border'
]
buttonCssClass: null
populateToolbar: (toolbar) ->
buttonset = jQuery "<span class=\"#{@widgetName}\"></span>"
contentId = "#{@options.uuid}-#{@widgetName}-data"
target = @_prepareDropdown contentId
toolbar.append target
setup= =>
console.log('check nugget') if @debug
#TODO: evaluate problems and removal buttons to the form
return true
@dropdownform = @_prepareButton setup, target
buttonset.append @dropdownform
toolbar.append buttonset
_prepareDropdown: (contentId) ->
contentArea = jQuery "<div id=\"#{contentId}\"><ul></ul></div>"
contentAreaUL = contentArea.find('ul')
addButton = (element,event_handler) =>
button_label = element
button_tooltip = element
if ( window.action_list && window.action_list['hallojs_cleanup_' + element] != undefined )
button_label = window.action_list['hallojs_cleanup_' + element].title
button_tooltip = window.action_list['hallojs_cleanup_' + element].tooltip
el = jQuery "<li><div><button class=\"action_button\" id=\"" + @tmpid+element + "\" title=\"" + button_tooltip+ "\">" + button_label + "</button></div></li>"
#unless containingElement is 'div'
# el.addClass 'disabled'
el.find('button').bind 'click', event_handler
el
contentAreaUL.append addButton "clean_html", =>
@options.editable.storeContentPosition()
@options.editable.undoWaypointStart('cleanup')
console.log('cleanhtml') if @debug
dom = new IDOM()
nugget = new DOMNugget()
#if @domnode
# @domnode.removeSourceDescriptions()
if dom
#utils.removeBadAttributes(@options.editable.element)
#utils.removeBadStyles(@options.editable.element)
#utils.removeCites(@options.editable.element)
#utils.
nugget.prepareTextForEdit(@options.editable.element); # calls dom.clean
@options.editable.element.html(@options.editable.element.html().replace(/ /g,' '));
#@options.editable.element.find('.cite').remove()
@dropdownform.hallodropdownform('hideForm')
@options.editable.store()
nugget.updateSourceDescriptionData(@options.editable.element).done =>
nugget.resetCitations(@options.editable.element).done =>
@options.editable.restoreContentPosition()
@options.editable.undoWaypointCommit()
if ( typeof MathJax != 'undefined' )
MathJax.Hub.Queue(['Typeset',MathJax.Hub])
contentAreaUL.append addButton "clean_plain", =>
@options.editable.storeContentPosition()
@options.editable.undoWaypointStart('cleanup')
dom = new IDOM()
nugget = new DOMNugget()
nugget.prepareTextForEdit(@options.editable.element); # calls dom.clean
dom.plainTextParagraphs(@options.editable.element)
@options.editable.store()
nugget.prepareTextForEdit(@options.editable.element); # calls dom.clean / math prepare
@dropdownform.hallodropdownform('hideForm')
nugget = new DOMNugget()
nugget.updateSourceDescriptionData(@options.editable.element).done =>
nugget.resetCitations(@options.editable.element).done =>
@options.editable.restoreContentPosition()
@options.editable.undoWaypointCommit()
if ( typeof MathJax != 'undefined' )
MathJax.Hub.Queue(['Typeset',MathJax.Hub])
contentArea
_prepareButton: (setup, target) ->
buttonElement = jQuery '<span></span>'
button_label = 'cleanup'
if ( window.action_list && window.action_list['hallojs_cleanup'] != undefined )
button_label = window.action_list['hallojs_cleanup'].title
buttonElement.hallodropdownform
uuid: @options.uuid
editable: @options.editable
label: button_label
command: 'cleanup'
icon: 'icon-text-height'
target: target
setup: setup
cssClass: @options.buttonCssClass
buttonElement
)(jQuery)
| 125876 | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 <NAME>, IKS Consortium
# Hallo may be freely distributed under the MIT license
# Plugin to minimalistic add a table to the editable
((jQuery) ->
jQuery.widget 'IKS.hallocleanup',
dropdownform: null
tmpid: 0
html: null
debug: false
options:
editable: null
toolbar: null
uuid: ''
elements: [
'rows'
'cols'
'border'
]
buttonCssClass: null
populateToolbar: (toolbar) ->
buttonset = jQuery "<span class=\"#{@widgetName}\"></span>"
contentId = "#{@options.uuid}-#{@widgetName}-data"
target = @_prepareDropdown contentId
toolbar.append target
setup= =>
console.log('check nugget') if @debug
#TODO: evaluate problems and removal buttons to the form
return true
@dropdownform = @_prepareButton setup, target
buttonset.append @dropdownform
toolbar.append buttonset
_prepareDropdown: (contentId) ->
contentArea = jQuery "<div id=\"#{contentId}\"><ul></ul></div>"
contentAreaUL = contentArea.find('ul')
addButton = (element,event_handler) =>
button_label = element
button_tooltip = element
if ( window.action_list && window.action_list['hallojs_cleanup_' + element] != undefined )
button_label = window.action_list['hallojs_cleanup_' + element].title
button_tooltip = window.action_list['hallojs_cleanup_' + element].tooltip
el = jQuery "<li><div><button class=\"action_button\" id=\"" + @tmpid+element + "\" title=\"" + button_tooltip+ "\">" + button_label + "</button></div></li>"
#unless containingElement is 'div'
# el.addClass 'disabled'
el.find('button').bind 'click', event_handler
el
contentAreaUL.append addButton "clean_html", =>
@options.editable.storeContentPosition()
@options.editable.undoWaypointStart('cleanup')
console.log('cleanhtml') if @debug
dom = new IDOM()
nugget = new DOMNugget()
#if @domnode
# @domnode.removeSourceDescriptions()
if dom
#utils.removeBadAttributes(@options.editable.element)
#utils.removeBadStyles(@options.editable.element)
#utils.removeCites(@options.editable.element)
#utils.
nugget.prepareTextForEdit(@options.editable.element); # calls dom.clean
@options.editable.element.html(@options.editable.element.html().replace(/ /g,' '));
#@options.editable.element.find('.cite').remove()
@dropdownform.hallodropdownform('hideForm')
@options.editable.store()
nugget.updateSourceDescriptionData(@options.editable.element).done =>
nugget.resetCitations(@options.editable.element).done =>
@options.editable.restoreContentPosition()
@options.editable.undoWaypointCommit()
if ( typeof MathJax != 'undefined' )
MathJax.Hub.Queue(['Typeset',MathJax.Hub])
contentAreaUL.append addButton "clean_plain", =>
@options.editable.storeContentPosition()
@options.editable.undoWaypointStart('cleanup')
dom = new IDOM()
nugget = new DOMNugget()
nugget.prepareTextForEdit(@options.editable.element); # calls dom.clean
dom.plainTextParagraphs(@options.editable.element)
@options.editable.store()
nugget.prepareTextForEdit(@options.editable.element); # calls dom.clean / math prepare
@dropdownform.hallodropdownform('hideForm')
nugget = new DOMNugget()
nugget.updateSourceDescriptionData(@options.editable.element).done =>
nugget.resetCitations(@options.editable.element).done =>
@options.editable.restoreContentPosition()
@options.editable.undoWaypointCommit()
if ( typeof MathJax != 'undefined' )
MathJax.Hub.Queue(['Typeset',MathJax.Hub])
contentArea
_prepareButton: (setup, target) ->
buttonElement = jQuery '<span></span>'
button_label = 'cleanup'
if ( window.action_list && window.action_list['hallojs_cleanup'] != undefined )
button_label = window.action_list['hallojs_cleanup'].title
buttonElement.hallodropdownform
uuid: @options.uuid
editable: @options.editable
label: button_label
command: 'cleanup'
icon: 'icon-text-height'
target: target
setup: setup
cssClass: @options.buttonCssClass
buttonElement
)(jQuery)
| true | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 PI:NAME:<NAME>END_PI, IKS Consortium
# Hallo may be freely distributed under the MIT license
# Plugin to minimalistic add a table to the editable
((jQuery) ->
jQuery.widget 'IKS.hallocleanup',
dropdownform: null
tmpid: 0
html: null
debug: false
options:
editable: null
toolbar: null
uuid: ''
elements: [
'rows'
'cols'
'border'
]
buttonCssClass: null
populateToolbar: (toolbar) ->
buttonset = jQuery "<span class=\"#{@widgetName}\"></span>"
contentId = "#{@options.uuid}-#{@widgetName}-data"
target = @_prepareDropdown contentId
toolbar.append target
setup= =>
console.log('check nugget') if @debug
#TODO: evaluate problems and removal buttons to the form
return true
@dropdownform = @_prepareButton setup, target
buttonset.append @dropdownform
toolbar.append buttonset
_prepareDropdown: (contentId) ->
contentArea = jQuery "<div id=\"#{contentId}\"><ul></ul></div>"
contentAreaUL = contentArea.find('ul')
addButton = (element,event_handler) =>
button_label = element
button_tooltip = element
if ( window.action_list && window.action_list['hallojs_cleanup_' + element] != undefined )
button_label = window.action_list['hallojs_cleanup_' + element].title
button_tooltip = window.action_list['hallojs_cleanup_' + element].tooltip
el = jQuery "<li><div><button class=\"action_button\" id=\"" + @tmpid+element + "\" title=\"" + button_tooltip+ "\">" + button_label + "</button></div></li>"
#unless containingElement is 'div'
# el.addClass 'disabled'
el.find('button').bind 'click', event_handler
el
contentAreaUL.append addButton "clean_html", =>
@options.editable.storeContentPosition()
@options.editable.undoWaypointStart('cleanup')
console.log('cleanhtml') if @debug
dom = new IDOM()
nugget = new DOMNugget()
#if @domnode
# @domnode.removeSourceDescriptions()
if dom
#utils.removeBadAttributes(@options.editable.element)
#utils.removeBadStyles(@options.editable.element)
#utils.removeCites(@options.editable.element)
#utils.
nugget.prepareTextForEdit(@options.editable.element); # calls dom.clean
@options.editable.element.html(@options.editable.element.html().replace(/ /g,' '));
#@options.editable.element.find('.cite').remove()
@dropdownform.hallodropdownform('hideForm')
@options.editable.store()
nugget.updateSourceDescriptionData(@options.editable.element).done =>
nugget.resetCitations(@options.editable.element).done =>
@options.editable.restoreContentPosition()
@options.editable.undoWaypointCommit()
if ( typeof MathJax != 'undefined' )
MathJax.Hub.Queue(['Typeset',MathJax.Hub])
contentAreaUL.append addButton "clean_plain", =>
@options.editable.storeContentPosition()
@options.editable.undoWaypointStart('cleanup')
dom = new IDOM()
nugget = new DOMNugget()
nugget.prepareTextForEdit(@options.editable.element); # calls dom.clean
dom.plainTextParagraphs(@options.editable.element)
@options.editable.store()
nugget.prepareTextForEdit(@options.editable.element); # calls dom.clean / math prepare
@dropdownform.hallodropdownform('hideForm')
nugget = new DOMNugget()
nugget.updateSourceDescriptionData(@options.editable.element).done =>
nugget.resetCitations(@options.editable.element).done =>
@options.editable.restoreContentPosition()
@options.editable.undoWaypointCommit()
if ( typeof MathJax != 'undefined' )
MathJax.Hub.Queue(['Typeset',MathJax.Hub])
contentArea
_prepareButton: (setup, target) ->
buttonElement = jQuery '<span></span>'
button_label = 'cleanup'
if ( window.action_list && window.action_list['hallojs_cleanup'] != undefined )
button_label = window.action_list['hallojs_cleanup'].title
buttonElement.hallodropdownform
uuid: @options.uuid
editable: @options.editable
label: button_label
command: 'cleanup'
icon: 'icon-text-height'
target: target
setup: setup
cssClass: @options.buttonCssClass
buttonElement
)(jQuery)
|
[
{
"context": "####\nAccountsTemplates.configure\n\tconfirmPassword: true,\n\tenablePasswordChange: true,\n\tforbidClientAccoun",
"end": 249,
"score": 0.7077646851539612,
"start": 245,
"tag": "PASSWORD",
"value": "true"
}
] | both/scripts/1_init/accounts.coffee | agottschalk10/worklearn | 0 | ##########################################################
# login and accounts
##########################################################
##########################################################
AccountsTemplates.configure
confirmPassword: true,
enablePasswordChange: true,
forbidClientAccountCreation: false,
overrideLoginErrors: true,
sendVerificationEmail: true,
lowercaseUsername: false,
focusFirstInput: true,
#Appearance
showAddRemoveServices: true,
showForgotPasswordLink: true,
showLabels: true,
showPlaceholders: true,
showResendVerificationEmailLink: true,
# Client-side Validation
continuousValidation: false,
negativeFeedback: false,
negativeValidation: true,
positiveValidation: true,
positiveFeedback: true,
showValidating: true,
# Privacy Policy and Terms of Use
privacyUrl: 'privacy',
termsUrl: 'terms-of-use',
| 206792 | ##########################################################
# login and accounts
##########################################################
##########################################################
AccountsTemplates.configure
confirmPassword: <PASSWORD>,
enablePasswordChange: true,
forbidClientAccountCreation: false,
overrideLoginErrors: true,
sendVerificationEmail: true,
lowercaseUsername: false,
focusFirstInput: true,
#Appearance
showAddRemoveServices: true,
showForgotPasswordLink: true,
showLabels: true,
showPlaceholders: true,
showResendVerificationEmailLink: true,
# Client-side Validation
continuousValidation: false,
negativeFeedback: false,
negativeValidation: true,
positiveValidation: true,
positiveFeedback: true,
showValidating: true,
# Privacy Policy and Terms of Use
privacyUrl: 'privacy',
termsUrl: 'terms-of-use',
| true | ##########################################################
# login and accounts
##########################################################
##########################################################
AccountsTemplates.configure
confirmPassword: PI:PASSWORD:<PASSWORD>END_PI,
enablePasswordChange: true,
forbidClientAccountCreation: false,
overrideLoginErrors: true,
sendVerificationEmail: true,
lowercaseUsername: false,
focusFirstInput: true,
#Appearance
showAddRemoveServices: true,
showForgotPasswordLink: true,
showLabels: true,
showPlaceholders: true,
showResendVerificationEmailLink: true,
# Client-side Validation
continuousValidation: false,
negativeFeedback: false,
negativeValidation: true,
positiveValidation: true,
positiveFeedback: true,
showValidating: true,
# Privacy Policy and Terms of Use
privacyUrl: 'privacy',
termsUrl: 'terms-of-use',
|
[
{
"context": "=====================\n\nplanck = {\n passphrase : \"mmpp\",\n key : \"\"\"\n-----BEGIN PGP PRIVATE KEY BLOCK---",
"end": 288,
"score": 0.9993495941162109,
"start": 284,
"tag": "PASSWORD",
"value": "mmpp"
},
{
"context": "LOCK-----\nVersion: GnuPG/MacGPG2 v2.0.22 (Dar... | test/files/elgamal.iced | samkenxstream/kbpgp | 464 | {KeyManager} = require '../../'
{do_message} = require '../../lib/openpgp/processor'
{burn} = require '../../lib/openpgp/burner'
testing_unixtime = Math.floor(new Date(2014, 2, 21)/1000)
#=================================================================
planck = {
passphrase : "mmpp",
key : """
-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
lQHhBFMGAboRBAC6X5nu5PxK9eaTRTGI1PUu89SYaDCNf4P82ADVwBy2gQSHZAlH
d1esdd5QI2TYvfLBYHelTLk6nfO/JsPFFTPAKiyCA84GO3MBXebs8JBd5VPl3PuY
YXk+xUVui/oE2bnS2PzUIPIilWwN1g6O4Olz+D70uuoGV8Og2krKUkzsRwCg+KcF
fiJsfgw7to/VXdD651DSZ/0D/3N5l1kiFZvttYSu6VymG76NBnPgbRKH3sYguGPj
c8E6GtJ1HrGQiGoiKN3jfYEQcOqil6/A780Yz/3yW6QK3OIJ9mIpNA8uJghWdk9E
3xhm0QrC4e3ECqQgAp5wGTfTaepsvjZxRyvu+xTQje/QMwEk3ElSOfjfq1nzjoE8
15YcBACzroFdReanDhMeRb2xjv8fjr98WqMGVjifPwJ2UEwtV8wPPGDNN63BbhYL
RyRxSrUdP3LDKnnNVocNOjOEGzrRtdKRf3S1cB7b+Tc2rphublG1yGIjDeNZ9E9g
mTrxr+mBm3WyFlBU3vEE+UJ3YLPQ37ai83CItaT22OY5FNAW3v4DAwIBuwNTyCVg
19Z/bQbO5Vv7myq59sSwfpLCcnjaII3oYjRYum32OrmIl1a2qPzOGpF1BfeyfT43
kin3XbQ1TWF4IFBsYW5jayAocGFzc3dvcmQgaXMgJ21tcHAnKSA8cGxhbmNrQGJl
cmxpbi5hYy5kZT6IaAQTEQIAKAUCUwYBugIbAwUJEswDAAYLCQgHAwIGFQgCCQoL
BBYCAwECHgECF4AACgkQkQqdjReS9VtG9ACeKf/N+cRCTEjARwbAWl9VAndRTvIA
mQE+l+Mv2PF8F3TUVVYl9aAXc3JHnQFYBFMGAboQBADSFqRZ8S7vJLXKW7a22iZR
4ezEGM4Rj+3ldbsgs+BHG3qrtILdWFeiXRfh+0XgSJyhZpRfPYeKdF42I0+JvFzF
QE/9pX5LsjeIgeB3P6gMi7IPrF47qWhixQ3F9EvBymlFFCXnJ/9tQsHytIhyXsZH
LD9Vti6bLyz8zkuXbRT8CwADBgP+LPUlmmIuuUu7kYMCLDy5ycRGv/x8WamSZlH3
6TBY44+6xIpzOGf1Aoag+e7b+5pJE5+dFfWhfvZpGn9tdLdimA7DVxl/YCeTxoXL
25YCnOhlqVFfWMnVr7Ml3hX0Hl3WXqRQT45ZR7qzfR+8xUvl6jTwYZzYElGIJxa5
hPreyJv+AwMCAbsDU8glYNfWXpn3WV1KYjnXsZwPA1zOth8DoZBvsNFgpJCxQpfI
PCeAcnTQQaF0NEEfXtNGKsbwYFdHTD7aXvAs2h05FReITwQYEQIADwUCUwYBugIb
DAUJEswDAAAKCRCRCp2NF5L1Wx7xAJ0a2tmT1WhB9+7IEHVkwm0b97EbJQCfcoDT
ZbLGiqgjXIjfEuNACFhveec=
=66In
-----END PGP PRIVATE KEY BLOCK-----
""",
encrypted : [
{
ciphertext : """
-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
hQEOA6GRDo3EkelYEAQAtn66+B8ORT92QlHMY2tVLFbhoLdcRvkG9lM2X0op4iXk
PlgNps2UPPMEdSejVLV16evuUBS392+QqkHFLv9dZG+hheWs5opkWo7gyTZLjtSs
4YesHgjt9zqTg3ZfDjfqA2caDoUx09SvrxZyIggTQ4HsGqcq7CM1bZLWlrnBfNoE
ALCv0ou6I9sKNZazuO7yuAlL93IEE31jncooN2A5iFuM1ZknikYQh1M1PXNpocEb
+RCfDvyXMOVPrmAh6tJTswoimFYOaLCjFX/QIheIplDhsmZ1i5hvlmQBep1XC45i
cPuZ7I3F1pHz+mmfo3EDUpnHuJckMq99B0VAGMf/zAkv0qwB786ul+QxuRsAAIt5
1OnzQLadPGusI9k7gXRIh9VMDTPX06Mys16fR0+LfKTsegzKY5cQzFfnN8SS4sTt
gyA/brLHuHiFc9dSrmryNSw3k3Y7CWmpI1pQrEq9aeYd2qXtmpsWFG7K/uIXtJna
xGF/s+kzNRDrRQAD9xiCjpJaPrNP3FR5mM1m2AcXzOutycvJV8MNicOfqMaq5W1a
X0uqWT6kHA/R7W9wiqmX
=nrqo
-----END PGP MESSAGE-----
""",
plaintext : "My unavailing attempts to somehow reintegrate the action quantum into classical theory extended over several years and caused me much trouble.\n"
}
],
signcrypted : [
{
ciphertext : """
-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
hQEOA6GRDo3EkelYEAP9Eu7momivfWhIXFtkbM9ZmGBiLNP9Doq+jy7IPFMvKanK
7dv6Dv4RFcT+3WiphiWdgUXQwawyLL/2r1DYWw5CJ15RMUfnSVVQJw2k+2fxOyug
cJAXuIYVZ6AYU27NESlBje4cYaXk2kvdbYZ5wHRNGixlnyOmPCxsYDiHSKLHcHME
ALlyvqxpi01ZYW6ZKE58pvs45fj95l7KHZmIqCgzEEKvKk/w2Si0699bs05ldPAw
uO3d2MQP6VsxhzgiAE5B6B/fXpnK5aUuoRmAhJvnVoM2ZAguZTgLLhR2Ma+7cvMd
Da9o3Hzz/T2UBf0qRQ3X9O66WNKe4Xipp++p/V/WJ6u10sB4AWm/Bw16rweXQGpN
/TAVQBfdbACLPuOme3Bv9IZs5q5Ou5UB90kPcyIEyvtE0gujtgU4S1Pdby5Gh2qI
g3qImF1c6q67r16MVLtjt59L81/hpFARGpxI02nKecLXPIXhItsQXf8e7PjVRNLt
mH1vSFZuUunqJI2+6LmjKLSFfPZt0osEyxKQ3tY/F/jBsR3f1pU5U5Ms9FojqtB4
e0X6VqyJrw8xauQJWNfQ1CC1T4Vl/DhX7ObCRwdpaCfh2i+1RyROxMfmvMTSCyQb
Lv972c/jTKdnsTfxWp7zroX1kzzsUUhjV91GnWAtZzKcOyDXlqUZqObVObMD8wpA
CcZLYRrvnqrtjVDtBpbliNOMc+BE2zCot1ZGUFyqkw6pskUxxRXf4xfa0eys2HjG
2DhxByChz0SGgnRO
=haPD
-----END PGP MESSAGE-----
""",
plaintext : "A scientific truth does not triumph by convincing its opponents and making them see the light, but rather because its opponents eventually die and a new generation grows up that is familiar with it.\n"
}
],
quotes : [
"Something something foo foo bar bar should be better no time."
]
}
km = null
#=================================================================
exports.decrypt_msgs = (T, cb) ->
o = planck
opts = now : testing_unixtime
await KeyManager.import_from_armored_pgp { raw : o.key, opts }, defer err, tmp
km = tmp
T.waypoint "key import"
T.no_error err
await km.unlock_pgp o, defer err
T.no_error err
T.waypoint "key unlock"
key = km.find_crypt_pgp_key()
T.assert key?, "found a key'"
for msg,i in o.encrypted
await do_message { armored : msg.ciphertext, keyfetch : km, now : testing_unixtime }, defer err, out
T.no_error err
T.equal out.length, 1, "got 1 literal data packet"
lit = out[0]
T.equal lit.data.toString('utf8'), msg.plaintext, "plaintext came out ok"
signer = lit.get_data_signer()
T.assert not(signer?), "we not were signed"
T.waypoint "decrypted msg #{i}"
for msg,i in o.signcrypted
await do_message { armored : msg.ciphertext, keyfetch : km, now : testing_unixtime }, defer err, out
T.no_error err
T.equal out.length, 1, "got 1 literal data packet"
lit = out[0]
T.equal lit.data.toString('utf8'), msg.plaintext, "plaintext came out ok"
T.waypoint "decrypted/verified msg #{i}"
signer = lit.get_data_signer()
T.assert signer?, "we were signed"
cb()
#=================================================================
exports.elgamal_round_trip = (T,cb) ->
o = planck
opts =
msg : o.quotes[0]
signing_key : km.find_signing_pgp_key()
encryption_key : km.find_crypt_pgp_key()
await burn opts, defer err, asc
T.no_error err
await do_message { armored : asc, keyfetch : km, now : testing_unixtime }, defer err, out
T.no_error err
lit = out[0]
T.assert lit?, "got one out packet"
T.equal lit.data.toString('utf8'), o.quotes[0], "got equality"
T.assert lit.get_data_signer()?, "message was signed"
cb()
#=================================================================
| 165200 | {KeyManager} = require '../../'
{do_message} = require '../../lib/openpgp/processor'
{burn} = require '../../lib/openpgp/burner'
testing_unixtime = Math.floor(new Date(2014, 2, 21)/1000)
#=================================================================
planck = {
passphrase : "<PASSWORD>",
key : """
-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
<KEY>
-----END PGP PRIVATE KEY BLOCK-----
""",
encrypted : [
{
ciphertext : """
-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
<KEY>
=nr<KEY>
-----END PGP MESSAGE-----
""",
plaintext : "My unavailing attempts to somehow reintegrate the action quantum into classical theory extended over several years and caused me much trouble.\n"
}
],
signcrypted : [
{
ciphertext : """
-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
<KEY>
-----END PGP MESSAGE-----
""",
plaintext : "A scientific truth does not triumph by convincing its opponents and making them see the light, but rather because its opponents eventually die and a new generation grows up that is familiar with it.\n"
}
],
quotes : [
"Something something foo foo bar bar should be better no time."
]
}
km = null
#=================================================================
exports.decrypt_msgs = (T, cb) ->
o = planck
opts = now : testing_unixtime
await KeyManager.import_from_armored_pgp { raw : o.key, opts }, defer err, tmp
km = tmp
T.waypoint "key import"
T.no_error err
await km.unlock_pgp o, defer err
T.no_error err
T.waypoint "key unlock"
key = km.find_crypt_pgp_key()
T.assert key?, "found a key'"
for msg,i in o.encrypted
await do_message { armored : msg.ciphertext, keyfetch : km, now : testing_unixtime }, defer err, out
T.no_error err
T.equal out.length, 1, "got 1 literal data packet"
lit = out[0]
T.equal lit.data.toString('utf8'), msg.plaintext, "plaintext came out ok"
signer = lit.get_data_signer()
T.assert not(signer?), "we not were signed"
T.waypoint "decrypted msg #{i}"
for msg,i in o.signcrypted
await do_message { armored : msg.ciphertext, keyfetch : km, now : testing_unixtime }, defer err, out
T.no_error err
T.equal out.length, 1, "got 1 literal data packet"
lit = out[0]
T.equal lit.data.toString('utf8'), msg.plaintext, "plaintext came out ok"
T.waypoint "decrypted/verified msg #{i}"
signer = lit.get_data_signer()
T.assert signer?, "we were signed"
cb()
#=================================================================
exports.elgamal_round_trip = (T,cb) ->
o = planck
opts =
msg : o.quotes[0]
signing_key : km.find_signing_pgp_key()
encryption_key : km.find_crypt_pgp_key()
await burn opts, defer err, asc
T.no_error err
await do_message { armored : asc, keyfetch : km, now : testing_unixtime }, defer err, out
T.no_error err
lit = out[0]
T.assert lit?, "got one out packet"
T.equal lit.data.toString('utf8'), o.quotes[0], "got equality"
T.assert lit.get_data_signer()?, "message was signed"
cb()
#=================================================================
| true | {KeyManager} = require '../../'
{do_message} = require '../../lib/openpgp/processor'
{burn} = require '../../lib/openpgp/burner'
testing_unixtime = Math.floor(new Date(2014, 2, 21)/1000)
#=================================================================
planck = {
passphrase : "PI:PASSWORD:<PASSWORD>END_PI",
key : """
-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
PI:KEY:<KEY>END_PI
-----END PGP PRIVATE KEY BLOCK-----
""",
encrypted : [
{
ciphertext : """
-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
PI:KEY:<KEY>END_PI
=nrPI:KEY:<KEY>END_PI
-----END PGP MESSAGE-----
""",
plaintext : "My unavailing attempts to somehow reintegrate the action quantum into classical theory extended over several years and caused me much trouble.\n"
}
],
signcrypted : [
{
ciphertext : """
-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
PI:KEY:<KEY>END_PI
-----END PGP MESSAGE-----
""",
plaintext : "A scientific truth does not triumph by convincing its opponents and making them see the light, but rather because its opponents eventually die and a new generation grows up that is familiar with it.\n"
}
],
quotes : [
"Something something foo foo bar bar should be better no time."
]
}
km = null
#=================================================================
exports.decrypt_msgs = (T, cb) ->
o = planck
opts = now : testing_unixtime
await KeyManager.import_from_armored_pgp { raw : o.key, opts }, defer err, tmp
km = tmp
T.waypoint "key import"
T.no_error err
await km.unlock_pgp o, defer err
T.no_error err
T.waypoint "key unlock"
key = km.find_crypt_pgp_key()
T.assert key?, "found a key'"
for msg,i in o.encrypted
await do_message { armored : msg.ciphertext, keyfetch : km, now : testing_unixtime }, defer err, out
T.no_error err
T.equal out.length, 1, "got 1 literal data packet"
lit = out[0]
T.equal lit.data.toString('utf8'), msg.plaintext, "plaintext came out ok"
signer = lit.get_data_signer()
T.assert not(signer?), "we not were signed"
T.waypoint "decrypted msg #{i}"
for msg,i in o.signcrypted
await do_message { armored : msg.ciphertext, keyfetch : km, now : testing_unixtime }, defer err, out
T.no_error err
T.equal out.length, 1, "got 1 literal data packet"
lit = out[0]
T.equal lit.data.toString('utf8'), msg.plaintext, "plaintext came out ok"
T.waypoint "decrypted/verified msg #{i}"
signer = lit.get_data_signer()
T.assert signer?, "we were signed"
cb()
#=================================================================
exports.elgamal_round_trip = (T,cb) ->
o = planck
opts =
msg : o.quotes[0]
signing_key : km.find_signing_pgp_key()
encryption_key : km.find_crypt_pgp_key()
await burn opts, defer err, asc
T.no_error err
await do_message { armored : asc, keyfetch : km, now : testing_unixtime }, defer err, out
T.no_error err
lit = out[0]
T.assert lit?, "got one out packet"
T.equal lit.data.toString('utf8'), o.quotes[0], "got equality"
T.assert lit.get_data_signer()?, "message was signed"
cb()
#=================================================================
|
[
{
"context": "# Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>\n#\n# Redistribution and u",
"end": 35,
"score": 0.9998364448547363,
"start": 22,
"tag": "NAME",
"value": "Yusuke Suzuki"
},
{
"context": "# Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>\n#\n# Red... | src/instrumenter.coffee | HBOCodeLabs/ibrik | 0 | # Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
#
# 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.
#
# 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 <COPYRIGHT HOLDER> 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.
coffee = require 'coffee-script'
istanbul = require 'istanbul'
crypto = require 'crypto'
escodegen = require 'escodegen'
estraverse = require 'estraverse'
esprima = require 'esprima'
path = require 'path'
fs = require 'fs'
generateTrackerVar = (filename, omitSuffix) ->
if omitSuffix
return '__cov_'
hash = crypto.createHash 'md5'
hash.update filename
suffix = hash.digest 'base64'
suffix = suffix.replace(/\=/g, '').replace(/\+/g, '_').replace(/\//g, '$')
"__cov_#{suffix}"
class Instrumenter extends istanbul.Instrumenter
constructor: (opt) ->
istanbul.Instrumenter.call this, opt
instrumentSync: (code, filename) ->
filename = filename or "#{Date.now()}.js"
@coverState =
path: filename
s: {}
b: {}
f: {}
fnMap: {}
statementMap: {}
branchMap: {}
@currentState =
trackerVar: generateTrackerVar filename, @omitTrackerSuffix
func: 0
branch: 0
variable: 0
statement: 0
throw new Error 'Code must be string' unless typeof code is 'string'
try
code = coffee.compile code, sourceMap: true
program = esprima.parse(code.js, loc: true)
@attachLocation program, code.sourceMap
catch e
e.message = "Error compiling #{filename}: #{e.message}"
throw e
@walker.startWalk program
codegenOptions = @opts.codeGenerationOptions or format: compact: not this.opts.noCompact
"#{@getPreamble code}\n#{escodegen.generate program, codegenOptions}\n"
# Used to ensure that a module is included in the code coverage report
# (even if it is not loaded during the test)
include: (filename) ->
filename = path.resolve(filename)
code = fs.readFileSync(filename, 'utf8')
@instrumentSync(code, filename)
# Setup istanbul's references for this module
eval("#{@getPreamble null}")
return
attachLocation: (program, sourceMap)->
estraverse.traverse program,
leave: (node, parent) ->
mappedLocation = (location) ->
locArray = sourceMap.sourceLocation([
location.line - 1,
location.column])
line = 0
column = 0
if locArray
line = locArray[0] + 1
column = locArray[1]
return { line: line, column: column }
if node.loc?.start
node.loc.start = mappedLocation(node.loc.start)
if node.loc?.end
node.loc.end = mappedLocation(node.loc.end)
return
module.exports = Instrumenter
# vim: set sw=4 ts=4 et tw=80 :
| 80899 | # Copyright (C) 2012 <NAME> <<EMAIL>>
#
# 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.
#
# 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 <COPYRIGHT HOLDER> 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.
coffee = require 'coffee-script'
istanbul = require 'istanbul'
crypto = require 'crypto'
escodegen = require 'escodegen'
estraverse = require 'estraverse'
esprima = require 'esprima'
path = require 'path'
fs = require 'fs'
generateTrackerVar = (filename, omitSuffix) ->
if omitSuffix
return '__cov_'
hash = crypto.createHash 'md5'
hash.update filename
suffix = hash.digest 'base64'
suffix = suffix.replace(/\=/g, '').replace(/\+/g, '_').replace(/\//g, '$')
"__cov_#{suffix}"
class Instrumenter extends istanbul.Instrumenter
constructor: (opt) ->
istanbul.Instrumenter.call this, opt
instrumentSync: (code, filename) ->
filename = filename or "#{Date.now()}.js"
@coverState =
path: filename
s: {}
b: {}
f: {}
fnMap: {}
statementMap: {}
branchMap: {}
@currentState =
trackerVar: generateTrackerVar filename, @omitTrackerSuffix
func: 0
branch: 0
variable: 0
statement: 0
throw new Error 'Code must be string' unless typeof code is 'string'
try
code = coffee.compile code, sourceMap: true
program = esprima.parse(code.js, loc: true)
@attachLocation program, code.sourceMap
catch e
e.message = "Error compiling #{filename}: #{e.message}"
throw e
@walker.startWalk program
codegenOptions = @opts.codeGenerationOptions or format: compact: not this.opts.noCompact
"#{@getPreamble code}\n#{escodegen.generate program, codegenOptions}\n"
# Used to ensure that a module is included in the code coverage report
# (even if it is not loaded during the test)
include: (filename) ->
filename = path.resolve(filename)
code = fs.readFileSync(filename, 'utf8')
@instrumentSync(code, filename)
# Setup istanbul's references for this module
eval("#{@getPreamble null}")
return
attachLocation: (program, sourceMap)->
estraverse.traverse program,
leave: (node, parent) ->
mappedLocation = (location) ->
locArray = sourceMap.sourceLocation([
location.line - 1,
location.column])
line = 0
column = 0
if locArray
line = locArray[0] + 1
column = locArray[1]
return { line: line, column: column }
if node.loc?.start
node.loc.start = mappedLocation(node.loc.start)
if node.loc?.end
node.loc.end = mappedLocation(node.loc.end)
return
module.exports = Instrumenter
# vim: set sw=4 ts=4 et tw=80 :
| true | # Copyright (C) 2012 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
#
# 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.
#
# 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 <COPYRIGHT HOLDER> 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.
coffee = require 'coffee-script'
istanbul = require 'istanbul'
crypto = require 'crypto'
escodegen = require 'escodegen'
estraverse = require 'estraverse'
esprima = require 'esprima'
path = require 'path'
fs = require 'fs'
generateTrackerVar = (filename, omitSuffix) ->
if omitSuffix
return '__cov_'
hash = crypto.createHash 'md5'
hash.update filename
suffix = hash.digest 'base64'
suffix = suffix.replace(/\=/g, '').replace(/\+/g, '_').replace(/\//g, '$')
"__cov_#{suffix}"
class Instrumenter extends istanbul.Instrumenter
constructor: (opt) ->
istanbul.Instrumenter.call this, opt
instrumentSync: (code, filename) ->
filename = filename or "#{Date.now()}.js"
@coverState =
path: filename
s: {}
b: {}
f: {}
fnMap: {}
statementMap: {}
branchMap: {}
@currentState =
trackerVar: generateTrackerVar filename, @omitTrackerSuffix
func: 0
branch: 0
variable: 0
statement: 0
throw new Error 'Code must be string' unless typeof code is 'string'
try
code = coffee.compile code, sourceMap: true
program = esprima.parse(code.js, loc: true)
@attachLocation program, code.sourceMap
catch e
e.message = "Error compiling #{filename}: #{e.message}"
throw e
@walker.startWalk program
codegenOptions = @opts.codeGenerationOptions or format: compact: not this.opts.noCompact
"#{@getPreamble code}\n#{escodegen.generate program, codegenOptions}\n"
# Used to ensure that a module is included in the code coverage report
# (even if it is not loaded during the test)
include: (filename) ->
filename = path.resolve(filename)
code = fs.readFileSync(filename, 'utf8')
@instrumentSync(code, filename)
# Setup istanbul's references for this module
eval("#{@getPreamble null}")
return
attachLocation: (program, sourceMap)->
estraverse.traverse program,
leave: (node, parent) ->
mappedLocation = (location) ->
locArray = sourceMap.sourceLocation([
location.line - 1,
location.column])
line = 0
column = 0
if locArray
line = locArray[0] + 1
column = locArray[1]
return { line: line, column: column }
if node.loc?.start
node.loc.start = mappedLocation(node.loc.start)
if node.loc?.end
node.loc.end = mappedLocation(node.loc.end)
return
module.exports = Instrumenter
# vim: set sw=4 ts=4 et tw=80 :
|
[
{
"context": " An anode lambda calculus library based on work of Dale Schumacher\n#\n# see: http://www.dalnefre.com/wp/2010/08/evalu",
"end": 86,
"score": 0.9998048543930054,
"start": 71,
"tag": "NAME",
"value": "Dale Schumacher"
},
{
"context": "ressions-part-1-core-lambda-calculus/... | examples/lambda1.coffee | tristanls/anodejs | 3 | #
# lambda1.coffee: An anode lambda calculus library based on work of Dale Schumacher
#
# see: http://www.dalnefre.com/wp/2010/08/evaluating-expressions-part-1-core-lambda-calculus/
#
# (C) 2011 Tristan Slominski
#
anode = require '../lib/anode'
beh = anode.beh
Lambda = exports
# Constants
Lambda.const_expr_beh = beh 'value',
'cust, #eval, _' : ->
@send( @value ).to @cust
# Identifier
Lambda.ident_expr_beh = beh 'ident',
'cust, #eval, env' : ->
@send( @cust, @ident ).to @env
# Environment ( empty )
Lambda.empty_env_beh = beh
'cust, _' : ->
@send( '?' ).to @cust
# Environment
Lambda.env_beh = beh 'ident', 'value', 'next',
'cust, $ident' : ->
@send( @value ).to @cust
'cust, _' : ->
@send( @cust, @_ ).to @next
# Abstraction
Lambda.abs_expr_beh = beh 'ident', 'body_expr',
'cust, #eval, env' : ->
@send(
@create().withBehavior( Lambda.closure_beh @ident, @body_expr, @env )
).to @cust
# 'cust, #eval, env'
# Closure
Lambda.closure_beh = beh 'ident', 'body', 'env',
'cust, #apply, arg' : ->
env2 = @create().withBehavior( Lambda.env_beh @ident, @arg, @env )
@send( @cust, '#eval', env2 ).to @body
# Application
Lambda.app_expr_beh = beh 'abs_expr', 'arg_expr',
'cust, #eval, env' : ->
k_abs = @create().withBehavior( beh( 'env', 'arg_expr', 'cust',
'abs' : ->
k_arg = @create().withBehavior( beh( 'cust', 'abs',
'arg' : ->
@send( @cust, '#apply', @arg ).to @abs
)( @cust, @abs ))
@send( k_arg, '#eval', @env ).to @arg_expr
# 'abs'
)( @env, @arg_expr, @cust ))
@send( k_abs, '#eval', @env ).to @abs_expr
# 'cust, #eval, env' | 68277 | #
# lambda1.coffee: An anode lambda calculus library based on work of <NAME>
#
# see: http://www.dalnefre.com/wp/2010/08/evaluating-expressions-part-1-core-lambda-calculus/
#
# (C) 2011 <NAME>
#
anode = require '../lib/anode'
beh = anode.beh
Lambda = exports
# Constants
Lambda.const_expr_beh = beh 'value',
'cust, #eval, _' : ->
@send( @value ).to @cust
# Identifier
Lambda.ident_expr_beh = beh 'ident',
'cust, #eval, env' : ->
@send( @cust, @ident ).to @env
# Environment ( empty )
Lambda.empty_env_beh = beh
'cust, _' : ->
@send( '?' ).to @cust
# Environment
Lambda.env_beh = beh 'ident', 'value', 'next',
'cust, $ident' : ->
@send( @value ).to @cust
'cust, _' : ->
@send( @cust, @_ ).to @next
# Abstraction
Lambda.abs_expr_beh = beh 'ident', 'body_expr',
'cust, #eval, env' : ->
@send(
@create().withBehavior( Lambda.closure_beh @ident, @body_expr, @env )
).to @cust
# 'cust, #eval, env'
# Closure
Lambda.closure_beh = beh 'ident', 'body', 'env',
'cust, #apply, arg' : ->
env2 = @create().withBehavior( Lambda.env_beh @ident, @arg, @env )
@send( @cust, '#eval', env2 ).to @body
# Application
Lambda.app_expr_beh = beh 'abs_expr', 'arg_expr',
'cust, #eval, env' : ->
k_abs = @create().withBehavior( beh( 'env', 'arg_expr', 'cust',
'abs' : ->
k_arg = @create().withBehavior( beh( 'cust', 'abs',
'arg' : ->
@send( @cust, '#apply', @arg ).to @abs
)( @cust, @abs ))
@send( k_arg, '#eval', @env ).to @arg_expr
# 'abs'
)( @env, @arg_expr, @cust ))
@send( k_abs, '#eval', @env ).to @abs_expr
# 'cust, #eval, env' | true | #
# lambda1.coffee: An anode lambda calculus library based on work of PI:NAME:<NAME>END_PI
#
# see: http://www.dalnefre.com/wp/2010/08/evaluating-expressions-part-1-core-lambda-calculus/
#
# (C) 2011 PI:NAME:<NAME>END_PI
#
anode = require '../lib/anode'
beh = anode.beh
Lambda = exports
# Constants
Lambda.const_expr_beh = beh 'value',
'cust, #eval, _' : ->
@send( @value ).to @cust
# Identifier
Lambda.ident_expr_beh = beh 'ident',
'cust, #eval, env' : ->
@send( @cust, @ident ).to @env
# Environment ( empty )
Lambda.empty_env_beh = beh
'cust, _' : ->
@send( '?' ).to @cust
# Environment
Lambda.env_beh = beh 'ident', 'value', 'next',
'cust, $ident' : ->
@send( @value ).to @cust
'cust, _' : ->
@send( @cust, @_ ).to @next
# Abstraction
Lambda.abs_expr_beh = beh 'ident', 'body_expr',
'cust, #eval, env' : ->
@send(
@create().withBehavior( Lambda.closure_beh @ident, @body_expr, @env )
).to @cust
# 'cust, #eval, env'
# Closure
Lambda.closure_beh = beh 'ident', 'body', 'env',
'cust, #apply, arg' : ->
env2 = @create().withBehavior( Lambda.env_beh @ident, @arg, @env )
@send( @cust, '#eval', env2 ).to @body
# Application
Lambda.app_expr_beh = beh 'abs_expr', 'arg_expr',
'cust, #eval, env' : ->
k_abs = @create().withBehavior( beh( 'env', 'arg_expr', 'cust',
'abs' : ->
k_arg = @create().withBehavior( beh( 'cust', 'abs',
'arg' : ->
@send( @cust, '#apply', @arg ).to @abs
)( @cust, @abs ))
@send( k_arg, '#eval', @env ).to @arg_expr
# 'abs'
)( @env, @arg_expr, @cust ))
@send( k_abs, '#eval', @env ).to @abs_expr
# 'cust, #eval, env' |
[
{
"context": "------------------------------------\n#\n# Author : philippe.billet@noos.fr\n#\n# Gamma function gamma(x)\n# \n#---------------",
"end": 116,
"score": 0.9962747693061829,
"start": 93,
"tag": "EMAIL",
"value": "philippe.billet@noos.fr"
}
] | node_modules/algebrite/sources/gamma.coffee | souzamonteiro/maialexa | 928 | #-----------------------------------------------------------------------------
#
# Author : philippe.billet@noos.fr
#
# Gamma function gamma(x)
#
#-----------------------------------------------------------------------------
Eval_gamma = ->
push(cadr(p1))
Eval()
gamma()
gamma = ->
save()
gammaf()
restore()
gammaf = ->
# double d
p1 = pop()
if (isrational(p1) && MEQUAL(p1.q.a, 1) && MEQUAL(p1.q.b, 2))
if evaluatingAsFloats
push_double(Math.PI)
else
push_symbol(PI)
push_rational(1,2)
power()
return
if (isrational(p1) && MEQUAL(p1.q.a, 3) && MEQUAL(p1.q.b, 2))
if evaluatingAsFloats
push_double(Math.PI)
else
push_symbol(PI)
push_rational(1,2)
power()
push_rational(1,2)
multiply()
return
# if (p1->k == DOUBLE) {
# d = exp(lgamma(p1.d))
# push_double(d)
# return
# }
if (isnegativeterm(p1))
if evaluatingAsFloats
push_double(Math.PI)
else
push_symbol(PI)
push_integer(-1)
multiply()
if evaluatingAsFloats
push_double(Math.PI)
else
push_symbol(PI)
push(p1)
multiply()
sine()
push(p1)
multiply()
push(p1)
negate()
gamma()
multiply()
divide()
return
if (car(p1) == symbol(ADD))
gamma_of_sum()
return
push_symbol(GAMMA)
push(p1)
list(2)
return
gamma_of_sum = ->
p3 = cdr(p1)
if (isrational(car(p3)) && MEQUAL(car(p3).q.a, 1) && MEQUAL(car(p3).q.b, 1))
push(cadr(p3))
push(cadr(p3))
gamma()
multiply()
else
if (isrational(car(p3)) && MEQUAL(car(p3).q.a, -1) && MEQUAL(car(p3).q.b, 1))
push(cadr(p3))
gamma()
push(cadr(p3))
push_integer(-1)
add()
divide()
else
push_symbol(GAMMA)
push(p1)
list(2)
return
| 125653 | #-----------------------------------------------------------------------------
#
# Author : <EMAIL>
#
# Gamma function gamma(x)
#
#-----------------------------------------------------------------------------
Eval_gamma = ->
push(cadr(p1))
Eval()
gamma()
gamma = ->
save()
gammaf()
restore()
gammaf = ->
# double d
p1 = pop()
if (isrational(p1) && MEQUAL(p1.q.a, 1) && MEQUAL(p1.q.b, 2))
if evaluatingAsFloats
push_double(Math.PI)
else
push_symbol(PI)
push_rational(1,2)
power()
return
if (isrational(p1) && MEQUAL(p1.q.a, 3) && MEQUAL(p1.q.b, 2))
if evaluatingAsFloats
push_double(Math.PI)
else
push_symbol(PI)
push_rational(1,2)
power()
push_rational(1,2)
multiply()
return
# if (p1->k == DOUBLE) {
# d = exp(lgamma(p1.d))
# push_double(d)
# return
# }
if (isnegativeterm(p1))
if evaluatingAsFloats
push_double(Math.PI)
else
push_symbol(PI)
push_integer(-1)
multiply()
if evaluatingAsFloats
push_double(Math.PI)
else
push_symbol(PI)
push(p1)
multiply()
sine()
push(p1)
multiply()
push(p1)
negate()
gamma()
multiply()
divide()
return
if (car(p1) == symbol(ADD))
gamma_of_sum()
return
push_symbol(GAMMA)
push(p1)
list(2)
return
gamma_of_sum = ->
p3 = cdr(p1)
if (isrational(car(p3)) && MEQUAL(car(p3).q.a, 1) && MEQUAL(car(p3).q.b, 1))
push(cadr(p3))
push(cadr(p3))
gamma()
multiply()
else
if (isrational(car(p3)) && MEQUAL(car(p3).q.a, -1) && MEQUAL(car(p3).q.b, 1))
push(cadr(p3))
gamma()
push(cadr(p3))
push_integer(-1)
add()
divide()
else
push_symbol(GAMMA)
push(p1)
list(2)
return
| true | #-----------------------------------------------------------------------------
#
# Author : PI:EMAIL:<EMAIL>END_PI
#
# Gamma function gamma(x)
#
#-----------------------------------------------------------------------------
Eval_gamma = ->
push(cadr(p1))
Eval()
gamma()
gamma = ->
save()
gammaf()
restore()
gammaf = ->
# double d
p1 = pop()
if (isrational(p1) && MEQUAL(p1.q.a, 1) && MEQUAL(p1.q.b, 2))
if evaluatingAsFloats
push_double(Math.PI)
else
push_symbol(PI)
push_rational(1,2)
power()
return
if (isrational(p1) && MEQUAL(p1.q.a, 3) && MEQUAL(p1.q.b, 2))
if evaluatingAsFloats
push_double(Math.PI)
else
push_symbol(PI)
push_rational(1,2)
power()
push_rational(1,2)
multiply()
return
# if (p1->k == DOUBLE) {
# d = exp(lgamma(p1.d))
# push_double(d)
# return
# }
if (isnegativeterm(p1))
if evaluatingAsFloats
push_double(Math.PI)
else
push_symbol(PI)
push_integer(-1)
multiply()
if evaluatingAsFloats
push_double(Math.PI)
else
push_symbol(PI)
push(p1)
multiply()
sine()
push(p1)
multiply()
push(p1)
negate()
gamma()
multiply()
divide()
return
if (car(p1) == symbol(ADD))
gamma_of_sum()
return
push_symbol(GAMMA)
push(p1)
list(2)
return
gamma_of_sum = ->
p3 = cdr(p1)
if (isrational(car(p3)) && MEQUAL(car(p3).q.a, 1) && MEQUAL(car(p3).q.b, 1))
push(cadr(p3))
push(cadr(p3))
gamma()
multiply()
else
if (isrational(car(p3)) && MEQUAL(car(p3).q.a, -1) && MEQUAL(car(p3).q.b, 1))
push(cadr(p3))
gamma()
push(cadr(p3))
push_integer(-1)
add()
divide()
else
push_symbol(GAMMA)
push(p1)
list(2)
return
|
[
{
"context": "#\r\n# lib/index.coffee\r\n#\r\n# Copyright (c) 2012 Lee Olayvar <leeolayvar@gmail.com>\r\n# MIT Licensed\r\n#\r\n\r\n\r\n\r\n",
"end": 58,
"score": 0.9998905658721924,
"start": 47,
"tag": "NAME",
"value": "Lee Olayvar"
},
{
"context": "ndex.coffee\r\n#\r\n# Copyright (... | lib/index.coffee | leeola/eggplant | 1 | #
# lib/index.coffee
#
# Copyright (c) 2012 Lee Olayvar <leeolayvar@gmail.com>
# MIT Licensed
#
exports = module.exports = require './eggplant' | 100155 | #
# lib/index.coffee
#
# Copyright (c) 2012 <NAME> <<EMAIL>>
# MIT Licensed
#
exports = module.exports = require './eggplant' | true | #
# lib/index.coffee
#
# Copyright (c) 2012 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# MIT Licensed
#
exports = module.exports = require './eggplant' |
[
{
"context": "amed as \"name\" above\n\t\tcascade: false\n\t,\n\t\tname: 'Author'\n\t\tfield: 'author' # related documents will be po",
"end": 343,
"score": 0.8726648688316345,
"start": 337,
"tag": "NAME",
"value": "Author"
}
] | controllers/admin/article.coffee | winnlab/Optimeal | 0 | Crud = require '../../lib/crud'
crud = new Crud
modelName: 'Article'
relatedModels: [
name: 'ArticleCategory'
field: 'articleCategory' # related documents will be populated into variable, named as "field" variable
findAllInRelated: true # findAll will be returned in variable, named as "name" above
cascade: false
,
name: 'Author'
field: 'author' # related documents will be populated into variable, named as "field" variable
findAllInRelated: true # findAll will be returned in variable, named as "name" above
cascade: false
]
files: [
name: 'img'
replace: true
type: 'string'
]
module.exports.rest = crud.request.bind crud
module.exports.restFile = crud.fileRequest.bind crud | 186025 | Crud = require '../../lib/crud'
crud = new Crud
modelName: 'Article'
relatedModels: [
name: 'ArticleCategory'
field: 'articleCategory' # related documents will be populated into variable, named as "field" variable
findAllInRelated: true # findAll will be returned in variable, named as "name" above
cascade: false
,
name: '<NAME>'
field: 'author' # related documents will be populated into variable, named as "field" variable
findAllInRelated: true # findAll will be returned in variable, named as "name" above
cascade: false
]
files: [
name: 'img'
replace: true
type: 'string'
]
module.exports.rest = crud.request.bind crud
module.exports.restFile = crud.fileRequest.bind crud | true | Crud = require '../../lib/crud'
crud = new Crud
modelName: 'Article'
relatedModels: [
name: 'ArticleCategory'
field: 'articleCategory' # related documents will be populated into variable, named as "field" variable
findAllInRelated: true # findAll will be returned in variable, named as "name" above
cascade: false
,
name: 'PI:NAME:<NAME>END_PI'
field: 'author' # related documents will be populated into variable, named as "field" variable
findAllInRelated: true # findAll will be returned in variable, named as "name" above
cascade: false
]
files: [
name: 'img'
replace: true
type: 'string'
]
module.exports.rest = crud.request.bind crud
module.exports.restFile = crud.fileRequest.bind crud |
[
{
"context": "le('gapi')\n .value 'GoogleApp',\n apiKey: '1234'\n clientId: 'abcd'\n\n\n beforeEach module 'ga",
"end": 249,
"score": 0.9979103207588196,
"start": 245,
"tag": "KEY",
"value": "1234"
},
{
"context": "GoogleApp',\n apiKey: '1234'\n clientId: 'abc... | public/libs/ngGAPI/test/spec/BloggerSpec.coffee | Evezown/evezown_production | 94 | describe 'GAPI', ->
{
GAPI,Blogger,
$httpBackend,baseUrl,
getHeaders,postHeaders,putHeaders,deleteHeaders,patchHeaders,noContentHeaders,
authorization
} = {}
angular.module('gapi')
.value 'GoogleApp',
apiKey: '1234'
clientId: 'abcd'
beforeEach module 'gapi'
beforeEach inject ($injector) ->
GAPI = $injector.get 'GAPI'
$httpBackend = $injector.get '$httpBackend'
GAPI.app = {
oauthToken: {
access_token: '1234abcd'
}
}
getHeaders = deleteHeaders = noContentHeaders =
"Authorization":"Bearer 1234abcd"
"Accept":"application/json, text/plain, */*"
patchHeaders =
"Authorization":"Bearer 1234abcd"
"Accept":"application/json, text/plain, */*"
"Content-Type":"application/json;charset=utf-8"
postHeaders = putHeaders =
"Authorization":"Bearer 1234abcd"
"Accept":"application/json, text/plain, */*"
"Content-Type":"application/json;charset=utf-8"
afterEach ->
$httpBackend.verifyNoOutstandingExpectation()
$httpBackend.verifyNoOutstandingRequest()
describe 'Blogger', ->
beforeEach inject ($injector) ->
Blogger = $injector.get('Blogger')
it 'should refer to the blogger api', ->
expect(Blogger.api).toBe 'blogger'
it 'should refer to version 3', ->
expect(Blogger.version).toBe 'v3'
it 'should refer to the correct url', ->
expect(Blogger.url).toBe 'https://www.googleapis.com/blogger/v3/'
# BLOGS
it 'should get blog by id', ->
url = "#{Blogger.url}blogs/xyz"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getBlogs 'xyz'
$httpBackend.flush()
it 'should get blog by url', ->
url = "#{Blogger.url}blogs/byurl?url=example.blogspot.com"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getBlogByUrl url: 'example.blogspot.com'
$httpBackend.flush()
it 'should list blogs by user', ->
url = "#{Blogger.url}users/xyz/blogs?view=author"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.listBlogsByUser 'xyz', view: 'author'
$httpBackend.flush()
# COMMENTS
it 'should list comments', ->
url = "#{Blogger.url}blogs/123/posts/456/comments?maxResults=5"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.listComments '123', '456', { maxResults: 5 }
$httpBackend.flush()
it 'should get a comment', ->
url = "#{Blogger.url}blogs/123/posts/456/comments/789"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getComments '123', '456', '789'
$httpBackend.flush()
it 'should approve a comment', ->
url = "#{Blogger.url}blogs/123/posts/456/comments/789/approve"
$httpBackend.expectPOST(url, undefined, noContentHeaders).respond null
Blogger.approveComments '123', '456', '789'
$httpBackend.flush()
it 'should delete a comment', ->
url = "#{Blogger.url}blogs/123/posts/456/comments/789"
$httpBackend.expectDELETE(url, deleteHeaders).respond null
Blogger.deleteComments '123', '456', '789'
$httpBackend.flush()
it 'should list comments by blog', ->
url = "#{Blogger.url}blogs/123/comments?maxResults=5"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.listCommentsByBlog '123', maxResults: 5
$httpBackend.flush()
it 'should mark a comment as spam', ->
url = "#{Blogger.url}blogs/123/posts/456/comments/789/spam"
$httpBackend.expectPOST(url, undefined, noContentHeaders).respond null
Blogger.markCommentsAsSpam '123', '456', '789'
$httpBackend.flush()
it 'should remove the content of a comment', ->
url = "#{Blogger.url}blogs/123/posts/456/comments/789/removecontent"
$httpBackend.expectPOST(url, undefined, noContentHeaders).respond null
Blogger.removeContent '123', '456', '789'
$httpBackend.flush()
# PAGES
it 'should list pages', ->
url = "#{Blogger.url}blogs/123/pages?fetchBodies=true"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.listPages '123', fetchBodies: true
$httpBackend.flush()
it 'should get a page', ->
url = "#{Blogger.url}blogs/123/pages/456?view=admin"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.listPages '123', '456', view: 'admin'
$httpBackend.flush()
it 'should delete a page', ->
url = "#{Blogger.url}blogs/123/pages/456"
$httpBackend.expectDELETE(url, deleteHeaders).respond null
Blogger.deletePages '123', '456'
$httpBackend.flush()
it 'should insert a page', ->
url = "#{Blogger.url}blogs/123/pages"
data =
title: 'string'
content: 'string'
$httpBackend.expectPOST(url, data, postHeaders).respond null
Blogger.insertPages '123', data
$httpBackend.flush()
it 'should patch a page', ->
url = "#{Blogger.url}blogs/123/pages/456"
data =
title: 'string'
content: 'string'
$httpBackend.expectPATCH(url, data, patchHeaders).respond null
Blogger.patchPages '123', '456', data
$httpBackend.flush()
it 'should update a page', ->
url = "#{Blogger.url}blogs/123/pages/456"
data =
title: 'string'
content: 'string'
$httpBackend.expectPUT(url, data, putHeaders).respond null
Blogger.updatePages '123', '456', data
$httpBackend.flush()
# POSTS
it 'should list posts', ->
url = "#{Blogger.url}blogs/123/posts?fetchBodies=true"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.listPosts '123', fetchBodies: true
$httpBackend.flush()
it 'should get a post', ->
url = "#{Blogger.url}blogs/123/posts/456?view=admin"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getPosts '123', '456', view: 'admin'
$httpBackend.flush()
it 'should search posts', ->
url = "#{Blogger.url}blogs/123/posts/search?q=terms"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.searchPosts '123', q: 'terms'
$httpBackend.flush()
it 'should insert a post', ->
url = "#{Blogger.url}blogs/123/posts?isDraft=true"
data =
title: 'string'
content: 'string'
$httpBackend.expectPOST(url, data, postHeaders).respond null
Blogger.insertPosts '123', data, { isDraft: true }
$httpBackend.flush()
it 'should delete a post', ->
url = "#{Blogger.url}blogs/123/posts/456"
$httpBackend.expectDELETE(url, deleteHeaders).respond null
Blogger.deletePosts '123', '456'
$httpBackend.flush()
it 'should get posts by path', ->
url = "#{Blogger.url}blogs/123/posts/bypath?path=path%2Fto%2Fpost"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getPostsByPath '123', path: 'path/to/post'
$httpBackend.flush()
it 'should patch a post', ->
url = "#{Blogger.url}blogs/123/posts/456"
data =
title: 'string'
content: 'string'
$httpBackend.expectPATCH(url, data, patchHeaders).respond null
Blogger.patchPosts '123', '456', data
$httpBackend.flush()
it 'should update a post', ->
url = "#{Blogger.url}blogs/123/posts/456"
data =
title: 'string'
content: 'string'
$httpBackend.expectPUT(url, data, putHeaders).respond null
Blogger.updatePosts '123', '456', data
$httpBackend.flush()
it 'should publish a post', ->
url = "#{Blogger.url}blogs/123/posts/456/publish?publishDate=datetime"
$httpBackend.expectPOST(url, undefined, noContentHeaders).respond null
Blogger.publishPosts '123', '456', { publishDate: 'datetime' }
$httpBackend.flush()
it 'should revert a post', ->
url = "#{Blogger.url}blogs/123/posts/456/revert"
$httpBackend.expectPOST(url, undefined, noContentHeaders).respond null
Blogger.revertPosts '123', '456'
$httpBackend.flush()
# USERS
it 'should get a user', ->
url = "#{Blogger.url}users/xyz"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getUsers 'xyz'
$httpBackend.flush()
# BLOGUSERINFOS (yes, that's really what they call it in the docs...)
it 'should get blog and user info', ->
url = "#{Blogger.url}users/xyz/blogs/123?maxPosts=5"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getBlogUserInfos 'xyz', '123', { maxPosts: 5 }
$httpBackend.flush()
# PAGEVIEWS
it 'should get pageviews for a blog', ->
url = "#{Blogger.url}blogs/123/pageviews?range=all"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getPageViews '123', range: 'all'
$httpBackend.flush()
# POSTUSERINFOS
it 'should get post and user info', ->
url = "#{Blogger.url}users/xyz/blogs/123/posts/456?maxComments=5"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getPostUserInfos 'xyz', '123', '456', { maxComments: 5 }
$httpBackend.flush()
it 'should list post and user pairs for a blog', ->
url = "#{Blogger.url}users/xyz/blogs/123/posts?maxResults=5"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.listPostUserInfos 'xyz', '123', { maxResults: 5 }
$httpBackend.flush()
| 19553 | describe 'GAPI', ->
{
GAPI,Blogger,
$httpBackend,baseUrl,
getHeaders,postHeaders,putHeaders,deleteHeaders,patchHeaders,noContentHeaders,
authorization
} = {}
angular.module('gapi')
.value 'GoogleApp',
apiKey: '<KEY>'
clientId: '<KEY>'
beforeEach module 'gapi'
beforeEach inject ($injector) ->
GAPI = $injector.get 'GAPI'
$httpBackend = $injector.get '$httpBackend'
GAPI.app = {
oauthToken: {
access_token: '<KEY> <PASSWORD>'
}
}
getHeaders = deleteHeaders = noContentHeaders =
"Authorization":"Bearer <KEY> <PASSWORD>"
"Accept":"application/json, text/plain, */*"
patchHeaders =
"Authorization":"Bearer <KEY> <PASSWORD>"
"Accept":"application/json, text/plain, */*"
"Content-Type":"application/json;charset=utf-8"
postHeaders = putHeaders =
"Authorization":"Bearer <KEY>"
"Accept":"application/json, text/plain, */*"
"Content-Type":"application/json;charset=utf-8"
afterEach ->
$httpBackend.verifyNoOutstandingExpectation()
$httpBackend.verifyNoOutstandingRequest()
describe 'Blogger', ->
beforeEach inject ($injector) ->
Blogger = $injector.get('Blogger')
it 'should refer to the blogger api', ->
expect(Blogger.api).toBe 'blogger'
it 'should refer to version 3', ->
expect(Blogger.version).toBe 'v3'
it 'should refer to the correct url', ->
expect(Blogger.url).toBe 'https://www.googleapis.com/blogger/v3/'
# BLOGS
it 'should get blog by id', ->
url = "#{Blogger.url}blogs/xyz"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getBlogs 'xyz'
$httpBackend.flush()
it 'should get blog by url', ->
url = "#{Blogger.url}blogs/byurl?url=example.blogspot.com"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getBlogByUrl url: 'example.blogspot.com'
$httpBackend.flush()
it 'should list blogs by user', ->
url = "#{Blogger.url}users/xyz/blogs?view=author"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.listBlogsByUser 'xyz', view: 'author'
$httpBackend.flush()
# COMMENTS
it 'should list comments', ->
url = "#{Blogger.url}blogs/123/posts/456/comments?maxResults=5"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.listComments '123', '456', { maxResults: 5 }
$httpBackend.flush()
it 'should get a comment', ->
url = "#{Blogger.url}blogs/123/posts/456/comments/789"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getComments '123', '456', '789'
$httpBackend.flush()
it 'should approve a comment', ->
url = "#{Blogger.url}blogs/123/posts/456/comments/789/approve"
$httpBackend.expectPOST(url, undefined, noContentHeaders).respond null
Blogger.approveComments '123', '456', '789'
$httpBackend.flush()
it 'should delete a comment', ->
url = "#{Blogger.url}blogs/123/posts/456/comments/789"
$httpBackend.expectDELETE(url, deleteHeaders).respond null
Blogger.deleteComments '123', '456', '789'
$httpBackend.flush()
it 'should list comments by blog', ->
url = "#{Blogger.url}blogs/123/comments?maxResults=5"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.listCommentsByBlog '123', maxResults: 5
$httpBackend.flush()
it 'should mark a comment as spam', ->
url = "#{Blogger.url}blogs/123/posts/456/comments/789/spam"
$httpBackend.expectPOST(url, undefined, noContentHeaders).respond null
Blogger.markCommentsAsSpam '123', '456', '789'
$httpBackend.flush()
it 'should remove the content of a comment', ->
url = "#{Blogger.url}blogs/123/posts/456/comments/789/removecontent"
$httpBackend.expectPOST(url, undefined, noContentHeaders).respond null
Blogger.removeContent '123', '456', '789'
$httpBackend.flush()
# PAGES
it 'should list pages', ->
url = "#{Blogger.url}blogs/123/pages?fetchBodies=true"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.listPages '123', fetchBodies: true
$httpBackend.flush()
it 'should get a page', ->
url = "#{Blogger.url}blogs/123/pages/456?view=admin"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.listPages '123', '456', view: 'admin'
$httpBackend.flush()
it 'should delete a page', ->
url = "#{Blogger.url}blogs/123/pages/456"
$httpBackend.expectDELETE(url, deleteHeaders).respond null
Blogger.deletePages '123', '456'
$httpBackend.flush()
it 'should insert a page', ->
url = "#{Blogger.url}blogs/123/pages"
data =
title: 'string'
content: 'string'
$httpBackend.expectPOST(url, data, postHeaders).respond null
Blogger.insertPages '123', data
$httpBackend.flush()
it 'should patch a page', ->
url = "#{Blogger.url}blogs/123/pages/456"
data =
title: 'string'
content: 'string'
$httpBackend.expectPATCH(url, data, patchHeaders).respond null
Blogger.patchPages '123', '456', data
$httpBackend.flush()
it 'should update a page', ->
url = "#{Blogger.url}blogs/123/pages/456"
data =
title: 'string'
content: 'string'
$httpBackend.expectPUT(url, data, putHeaders).respond null
Blogger.updatePages '123', '456', data
$httpBackend.flush()
# POSTS
it 'should list posts', ->
url = "#{Blogger.url}blogs/123/posts?fetchBodies=true"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.listPosts '123', fetchBodies: true
$httpBackend.flush()
it 'should get a post', ->
url = "#{Blogger.url}blogs/123/posts/456?view=admin"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getPosts '123', '456', view: 'admin'
$httpBackend.flush()
it 'should search posts', ->
url = "#{Blogger.url}blogs/123/posts/search?q=terms"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.searchPosts '123', q: 'terms'
$httpBackend.flush()
it 'should insert a post', ->
url = "#{Blogger.url}blogs/123/posts?isDraft=true"
data =
title: 'string'
content: 'string'
$httpBackend.expectPOST(url, data, postHeaders).respond null
Blogger.insertPosts '123', data, { isDraft: true }
$httpBackend.flush()
it 'should delete a post', ->
url = "#{Blogger.url}blogs/123/posts/456"
$httpBackend.expectDELETE(url, deleteHeaders).respond null
Blogger.deletePosts '123', '456'
$httpBackend.flush()
it 'should get posts by path', ->
url = "#{Blogger.url}blogs/123/posts/bypath?path=path%2Fto%2Fpost"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getPostsByPath '123', path: 'path/to/post'
$httpBackend.flush()
it 'should patch a post', ->
url = "#{Blogger.url}blogs/123/posts/456"
data =
title: 'string'
content: 'string'
$httpBackend.expectPATCH(url, data, patchHeaders).respond null
Blogger.patchPosts '123', '456', data
$httpBackend.flush()
it 'should update a post', ->
url = "#{Blogger.url}blogs/123/posts/456"
data =
title: 'string'
content: 'string'
$httpBackend.expectPUT(url, data, putHeaders).respond null
Blogger.updatePosts '123', '456', data
$httpBackend.flush()
it 'should publish a post', ->
url = "#{Blogger.url}blogs/123/posts/456/publish?publishDate=datetime"
$httpBackend.expectPOST(url, undefined, noContentHeaders).respond null
Blogger.publishPosts '123', '456', { publishDate: 'datetime' }
$httpBackend.flush()
it 'should revert a post', ->
url = "#{Blogger.url}blogs/123/posts/456/revert"
$httpBackend.expectPOST(url, undefined, noContentHeaders).respond null
Blogger.revertPosts '123', '456'
$httpBackend.flush()
# USERS
it 'should get a user', ->
url = "#{Blogger.url}users/xyz"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getUsers 'xyz'
$httpBackend.flush()
# BLOGUSERINFOS (yes, that's really what they call it in the docs...)
it 'should get blog and user info', ->
url = "#{Blogger.url}users/xyz/blogs/123?maxPosts=5"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getBlogUserInfos 'xyz', '123', { maxPosts: 5 }
$httpBackend.flush()
# PAGEVIEWS
it 'should get pageviews for a blog', ->
url = "#{Blogger.url}blogs/123/pageviews?range=all"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getPageViews '123', range: 'all'
$httpBackend.flush()
# POSTUSERINFOS
it 'should get post and user info', ->
url = "#{Blogger.url}users/xyz/blogs/123/posts/456?maxComments=5"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getPostUserInfos 'xyz', '123', '456', { maxComments: 5 }
$httpBackend.flush()
it 'should list post and user pairs for a blog', ->
url = "#{Blogger.url}users/xyz/blogs/123/posts?maxResults=5"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.listPostUserInfos 'xyz', '123', { maxResults: 5 }
$httpBackend.flush()
| true | describe 'GAPI', ->
{
GAPI,Blogger,
$httpBackend,baseUrl,
getHeaders,postHeaders,putHeaders,deleteHeaders,patchHeaders,noContentHeaders,
authorization
} = {}
angular.module('gapi')
.value 'GoogleApp',
apiKey: 'PI:KEY:<KEY>END_PI'
clientId: 'PI:KEY:<KEY>END_PI'
beforeEach module 'gapi'
beforeEach inject ($injector) ->
GAPI = $injector.get 'GAPI'
$httpBackend = $injector.get '$httpBackend'
GAPI.app = {
oauthToken: {
access_token: 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI'
}
}
getHeaders = deleteHeaders = noContentHeaders =
"Authorization":"Bearer PI:PASSWORD:<KEY>END_PI PI:KEY:<PASSWORD>END_PI"
"Accept":"application/json, text/plain, */*"
patchHeaders =
"Authorization":"Bearer PI:PASSWORD:<KEY>END_PI PI:KEY:<PASSWORD>END_PI"
"Accept":"application/json, text/plain, */*"
"Content-Type":"application/json;charset=utf-8"
postHeaders = putHeaders =
"Authorization":"Bearer PI:KEY:<KEY>END_PI"
"Accept":"application/json, text/plain, */*"
"Content-Type":"application/json;charset=utf-8"
afterEach ->
$httpBackend.verifyNoOutstandingExpectation()
$httpBackend.verifyNoOutstandingRequest()
describe 'Blogger', ->
beforeEach inject ($injector) ->
Blogger = $injector.get('Blogger')
it 'should refer to the blogger api', ->
expect(Blogger.api).toBe 'blogger'
it 'should refer to version 3', ->
expect(Blogger.version).toBe 'v3'
it 'should refer to the correct url', ->
expect(Blogger.url).toBe 'https://www.googleapis.com/blogger/v3/'
# BLOGS
it 'should get blog by id', ->
url = "#{Blogger.url}blogs/xyz"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getBlogs 'xyz'
$httpBackend.flush()
it 'should get blog by url', ->
url = "#{Blogger.url}blogs/byurl?url=example.blogspot.com"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getBlogByUrl url: 'example.blogspot.com'
$httpBackend.flush()
it 'should list blogs by user', ->
url = "#{Blogger.url}users/xyz/blogs?view=author"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.listBlogsByUser 'xyz', view: 'author'
$httpBackend.flush()
# COMMENTS
it 'should list comments', ->
url = "#{Blogger.url}blogs/123/posts/456/comments?maxResults=5"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.listComments '123', '456', { maxResults: 5 }
$httpBackend.flush()
it 'should get a comment', ->
url = "#{Blogger.url}blogs/123/posts/456/comments/789"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getComments '123', '456', '789'
$httpBackend.flush()
it 'should approve a comment', ->
url = "#{Blogger.url}blogs/123/posts/456/comments/789/approve"
$httpBackend.expectPOST(url, undefined, noContentHeaders).respond null
Blogger.approveComments '123', '456', '789'
$httpBackend.flush()
it 'should delete a comment', ->
url = "#{Blogger.url}blogs/123/posts/456/comments/789"
$httpBackend.expectDELETE(url, deleteHeaders).respond null
Blogger.deleteComments '123', '456', '789'
$httpBackend.flush()
it 'should list comments by blog', ->
url = "#{Blogger.url}blogs/123/comments?maxResults=5"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.listCommentsByBlog '123', maxResults: 5
$httpBackend.flush()
it 'should mark a comment as spam', ->
url = "#{Blogger.url}blogs/123/posts/456/comments/789/spam"
$httpBackend.expectPOST(url, undefined, noContentHeaders).respond null
Blogger.markCommentsAsSpam '123', '456', '789'
$httpBackend.flush()
it 'should remove the content of a comment', ->
url = "#{Blogger.url}blogs/123/posts/456/comments/789/removecontent"
$httpBackend.expectPOST(url, undefined, noContentHeaders).respond null
Blogger.removeContent '123', '456', '789'
$httpBackend.flush()
# PAGES
it 'should list pages', ->
url = "#{Blogger.url}blogs/123/pages?fetchBodies=true"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.listPages '123', fetchBodies: true
$httpBackend.flush()
it 'should get a page', ->
url = "#{Blogger.url}blogs/123/pages/456?view=admin"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.listPages '123', '456', view: 'admin'
$httpBackend.flush()
it 'should delete a page', ->
url = "#{Blogger.url}blogs/123/pages/456"
$httpBackend.expectDELETE(url, deleteHeaders).respond null
Blogger.deletePages '123', '456'
$httpBackend.flush()
it 'should insert a page', ->
url = "#{Blogger.url}blogs/123/pages"
data =
title: 'string'
content: 'string'
$httpBackend.expectPOST(url, data, postHeaders).respond null
Blogger.insertPages '123', data
$httpBackend.flush()
it 'should patch a page', ->
url = "#{Blogger.url}blogs/123/pages/456"
data =
title: 'string'
content: 'string'
$httpBackend.expectPATCH(url, data, patchHeaders).respond null
Blogger.patchPages '123', '456', data
$httpBackend.flush()
it 'should update a page', ->
url = "#{Blogger.url}blogs/123/pages/456"
data =
title: 'string'
content: 'string'
$httpBackend.expectPUT(url, data, putHeaders).respond null
Blogger.updatePages '123', '456', data
$httpBackend.flush()
# POSTS
it 'should list posts', ->
url = "#{Blogger.url}blogs/123/posts?fetchBodies=true"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.listPosts '123', fetchBodies: true
$httpBackend.flush()
it 'should get a post', ->
url = "#{Blogger.url}blogs/123/posts/456?view=admin"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getPosts '123', '456', view: 'admin'
$httpBackend.flush()
it 'should search posts', ->
url = "#{Blogger.url}blogs/123/posts/search?q=terms"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.searchPosts '123', q: 'terms'
$httpBackend.flush()
it 'should insert a post', ->
url = "#{Blogger.url}blogs/123/posts?isDraft=true"
data =
title: 'string'
content: 'string'
$httpBackend.expectPOST(url, data, postHeaders).respond null
Blogger.insertPosts '123', data, { isDraft: true }
$httpBackend.flush()
it 'should delete a post', ->
url = "#{Blogger.url}blogs/123/posts/456"
$httpBackend.expectDELETE(url, deleteHeaders).respond null
Blogger.deletePosts '123', '456'
$httpBackend.flush()
it 'should get posts by path', ->
url = "#{Blogger.url}blogs/123/posts/bypath?path=path%2Fto%2Fpost"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getPostsByPath '123', path: 'path/to/post'
$httpBackend.flush()
it 'should patch a post', ->
url = "#{Blogger.url}blogs/123/posts/456"
data =
title: 'string'
content: 'string'
$httpBackend.expectPATCH(url, data, patchHeaders).respond null
Blogger.patchPosts '123', '456', data
$httpBackend.flush()
it 'should update a post', ->
url = "#{Blogger.url}blogs/123/posts/456"
data =
title: 'string'
content: 'string'
$httpBackend.expectPUT(url, data, putHeaders).respond null
Blogger.updatePosts '123', '456', data
$httpBackend.flush()
it 'should publish a post', ->
url = "#{Blogger.url}blogs/123/posts/456/publish?publishDate=datetime"
$httpBackend.expectPOST(url, undefined, noContentHeaders).respond null
Blogger.publishPosts '123', '456', { publishDate: 'datetime' }
$httpBackend.flush()
it 'should revert a post', ->
url = "#{Blogger.url}blogs/123/posts/456/revert"
$httpBackend.expectPOST(url, undefined, noContentHeaders).respond null
Blogger.revertPosts '123', '456'
$httpBackend.flush()
# USERS
it 'should get a user', ->
url = "#{Blogger.url}users/xyz"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getUsers 'xyz'
$httpBackend.flush()
# BLOGUSERINFOS (yes, that's really what they call it in the docs...)
it 'should get blog and user info', ->
url = "#{Blogger.url}users/xyz/blogs/123?maxPosts=5"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getBlogUserInfos 'xyz', '123', { maxPosts: 5 }
$httpBackend.flush()
# PAGEVIEWS
it 'should get pageviews for a blog', ->
url = "#{Blogger.url}blogs/123/pageviews?range=all"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getPageViews '123', range: 'all'
$httpBackend.flush()
# POSTUSERINFOS
it 'should get post and user info', ->
url = "#{Blogger.url}users/xyz/blogs/123/posts/456?maxComments=5"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.getPostUserInfos 'xyz', '123', '456', { maxComments: 5 }
$httpBackend.flush()
it 'should list post and user pairs for a blog', ->
url = "#{Blogger.url}users/xyz/blogs/123/posts?maxResults=5"
$httpBackend.expectGET(url, getHeaders).respond null
Blogger.listPostUserInfos 'xyz', '123', { maxResults: 5 }
$httpBackend.flush()
|
[
{
"context": " const ApplicationId = '$1'\n const ApiKey = '$2'\n Bmob.initialize(ApplicationId, ApiKey)\n ",
"end": 169,
"score": 0.47499558329582214,
"start": 166,
"tag": "KEY",
"value": "'$2"
}
] | snippets/bmob.cson | youngjuning/atom-bmob | 0 | '.source.js':
'Bmob全局初始化':
'prefix': 'binit'
'body': """
import Bmob from './utils/bmob.min.js'
const ApplicationId = '$1'
const ApiKey = '$2'
Bmob.initialize(ApplicationId, ApiKey)
$3
"""
'description': '下载和安装BmobSDK'
'descriptionMoreURL': 'http://doc.bmob.cn/data/wechat_app/#bmobsdk'
'页面中引入Bmob对象':
'prefix': 'bmob'
'body': """
import Bmob from '../utils/bmob.min.js'
"""
'description': '下载和安装BmobSDK'
'descriptionMoreURL': 'http://doc.bmob.cn/data/wechat_app/#bmobsdk'
'初始化Websoket通讯':
'prefix': 'bmobwebsocket'
'body': """
const BmobSocketIo = require('utils/bmobSocketIo.js').BmobSocketIo
BmobSocketIo.initialize(ApplicationId)
"""
'description': 'WebSocket 通讯(聊天)'
'descriptionMoreURL': 'http://doc.bmob.cn/data/wechat_app/index.html#websocket'
'对应页面引入BmobSocketIo':
'prefix': 'bmobsocketio'
'body': """
const BmobSocketIo = require('../../utils/bmobSocketIo.js').BmobSocketIo
"""
'description': 'WebSocket 通讯(聊天)'
'descriptionMoreURL': 'http://doc.bmob.cn/data/wechat_app/index.html#websocket'
'在页面进入第一次时初始化BmobSocketIo':
'prefix': 'bmobsocketioinit'
'body': 'BmobScoketIo.init()'
'description': 'WebSocket 通讯(聊天)'
'descriptionMoreURL': 'http://doc.bmob.cn/data/wechat_app/index.html#websocket'
'创建Bmob.Object的子类_Article':
'prefix': 'barticle'
'body': """
let $1 = Bmob.Object.extend('_Article')
"""
'description': '使用图文素材'
'descriptionMoreURL': 'http://doc.bmob.cn/data/wechat_app/develop_doc/#_6'
| 208436 | '.source.js':
'Bmob全局初始化':
'prefix': 'binit'
'body': """
import Bmob from './utils/bmob.min.js'
const ApplicationId = '$1'
const ApiKey = <KEY>'
Bmob.initialize(ApplicationId, ApiKey)
$3
"""
'description': '下载和安装BmobSDK'
'descriptionMoreURL': 'http://doc.bmob.cn/data/wechat_app/#bmobsdk'
'页面中引入Bmob对象':
'prefix': 'bmob'
'body': """
import Bmob from '../utils/bmob.min.js'
"""
'description': '下载和安装BmobSDK'
'descriptionMoreURL': 'http://doc.bmob.cn/data/wechat_app/#bmobsdk'
'初始化Websoket通讯':
'prefix': 'bmobwebsocket'
'body': """
const BmobSocketIo = require('utils/bmobSocketIo.js').BmobSocketIo
BmobSocketIo.initialize(ApplicationId)
"""
'description': 'WebSocket 通讯(聊天)'
'descriptionMoreURL': 'http://doc.bmob.cn/data/wechat_app/index.html#websocket'
'对应页面引入BmobSocketIo':
'prefix': 'bmobsocketio'
'body': """
const BmobSocketIo = require('../../utils/bmobSocketIo.js').BmobSocketIo
"""
'description': 'WebSocket 通讯(聊天)'
'descriptionMoreURL': 'http://doc.bmob.cn/data/wechat_app/index.html#websocket'
'在页面进入第一次时初始化BmobSocketIo':
'prefix': 'bmobsocketioinit'
'body': 'BmobScoketIo.init()'
'description': 'WebSocket 通讯(聊天)'
'descriptionMoreURL': 'http://doc.bmob.cn/data/wechat_app/index.html#websocket'
'创建Bmob.Object的子类_Article':
'prefix': 'barticle'
'body': """
let $1 = Bmob.Object.extend('_Article')
"""
'description': '使用图文素材'
'descriptionMoreURL': 'http://doc.bmob.cn/data/wechat_app/develop_doc/#_6'
| true | '.source.js':
'Bmob全局初始化':
'prefix': 'binit'
'body': """
import Bmob from './utils/bmob.min.js'
const ApplicationId = '$1'
const ApiKey = PI:KEY:<KEY>END_PI'
Bmob.initialize(ApplicationId, ApiKey)
$3
"""
'description': '下载和安装BmobSDK'
'descriptionMoreURL': 'http://doc.bmob.cn/data/wechat_app/#bmobsdk'
'页面中引入Bmob对象':
'prefix': 'bmob'
'body': """
import Bmob from '../utils/bmob.min.js'
"""
'description': '下载和安装BmobSDK'
'descriptionMoreURL': 'http://doc.bmob.cn/data/wechat_app/#bmobsdk'
'初始化Websoket通讯':
'prefix': 'bmobwebsocket'
'body': """
const BmobSocketIo = require('utils/bmobSocketIo.js').BmobSocketIo
BmobSocketIo.initialize(ApplicationId)
"""
'description': 'WebSocket 通讯(聊天)'
'descriptionMoreURL': 'http://doc.bmob.cn/data/wechat_app/index.html#websocket'
'对应页面引入BmobSocketIo':
'prefix': 'bmobsocketio'
'body': """
const BmobSocketIo = require('../../utils/bmobSocketIo.js').BmobSocketIo
"""
'description': 'WebSocket 通讯(聊天)'
'descriptionMoreURL': 'http://doc.bmob.cn/data/wechat_app/index.html#websocket'
'在页面进入第一次时初始化BmobSocketIo':
'prefix': 'bmobsocketioinit'
'body': 'BmobScoketIo.init()'
'description': 'WebSocket 通讯(聊天)'
'descriptionMoreURL': 'http://doc.bmob.cn/data/wechat_app/index.html#websocket'
'创建Bmob.Object的子类_Article':
'prefix': 'barticle'
'body': """
let $1 = Bmob.Object.extend('_Article')
"""
'description': '使用图文素材'
'descriptionMoreURL': 'http://doc.bmob.cn/data/wechat_app/develop_doc/#_6'
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9990379214286804,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-stream-push-strings.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.
MyStream = (options) ->
Readable.call this, options
@_chunks = 3
return
common = require("../common")
assert = require("assert")
Readable = require("stream").Readable
util = require("util")
util.inherits MyStream, Readable
MyStream::_read = (n) ->
switch @_chunks--
when 0
@push null
when 1
setTimeout (->
@push "last chunk"
return
).bind(this), 100
when 2
@push "second to last chunk"
when 3
process.nextTick (->
@push "first chunk"
return
).bind(this)
else
throw new Error("?")
return
ms = new MyStream()
results = []
ms.on "readable", ->
chunk = undefined
results.push chunk + "" while null isnt (chunk = ms.read())
return
expect = [
"first chunksecond to last chunk"
"last chunk"
]
process.on "exit", ->
assert.equal ms._chunks, -1
assert.deepEqual results, expect
console.log "ok"
return
| 128708 | # 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.
MyStream = (options) ->
Readable.call this, options
@_chunks = 3
return
common = require("../common")
assert = require("assert")
Readable = require("stream").Readable
util = require("util")
util.inherits MyStream, Readable
MyStream::_read = (n) ->
switch @_chunks--
when 0
@push null
when 1
setTimeout (->
@push "last chunk"
return
).bind(this), 100
when 2
@push "second to last chunk"
when 3
process.nextTick (->
@push "first chunk"
return
).bind(this)
else
throw new Error("?")
return
ms = new MyStream()
results = []
ms.on "readable", ->
chunk = undefined
results.push chunk + "" while null isnt (chunk = ms.read())
return
expect = [
"first chunksecond to last chunk"
"last chunk"
]
process.on "exit", ->
assert.equal ms._chunks, -1
assert.deepEqual results, expect
console.log "ok"
return
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
MyStream = (options) ->
Readable.call this, options
@_chunks = 3
return
common = require("../common")
assert = require("assert")
Readable = require("stream").Readable
util = require("util")
util.inherits MyStream, Readable
MyStream::_read = (n) ->
switch @_chunks--
when 0
@push null
when 1
setTimeout (->
@push "last chunk"
return
).bind(this), 100
when 2
@push "second to last chunk"
when 3
process.nextTick (->
@push "first chunk"
return
).bind(this)
else
throw new Error("?")
return
ms = new MyStream()
results = []
ms.on "readable", ->
chunk = undefined
results.push chunk + "" while null isnt (chunk = ms.read())
return
expect = [
"first chunksecond to last chunk"
"last chunk"
]
process.on "exit", ->
assert.equal ms._chunks, -1
assert.deepEqual results, expect
console.log "ok"
return
|
[
{
"context": "********\n# JSImage - image handle class\n# Coded by Hajime Oh-yake 2013.03.26\n#*************************************",
"end": 99,
"score": 0.9998957514762878,
"start": 85,
"tag": "NAME",
"value": "Hajime Oh-yake"
}
] | JSKit/01_JSImage.coffee | digitarhythm/codeJS | 0 | #*****************************************
# JSImage - image handle class
# Coded by Hajime Oh-yake 2013.03.26
#*****************************************
class JSImage extends JSObject
constructor: (imagename) ->
super()
if (imagename?)
@imageNamed(imagename)
imageNamed: (@_imagepath) ->
imageWriteToSavedPicture:(fname, action)->
$.post "syslibs/library.php",
mode: "savePicture"
imagepath: @_imagepath
fpath: fname
,(ret)=>
if (action?)
action(ret)
| 166491 | #*****************************************
# JSImage - image handle class
# Coded by <NAME> 2013.03.26
#*****************************************
class JSImage extends JSObject
constructor: (imagename) ->
super()
if (imagename?)
@imageNamed(imagename)
imageNamed: (@_imagepath) ->
imageWriteToSavedPicture:(fname, action)->
$.post "syslibs/library.php",
mode: "savePicture"
imagepath: @_imagepath
fpath: fname
,(ret)=>
if (action?)
action(ret)
| true | #*****************************************
# JSImage - image handle class
# Coded by PI:NAME:<NAME>END_PI 2013.03.26
#*****************************************
class JSImage extends JSObject
constructor: (imagename) ->
super()
if (imagename?)
@imageNamed(imagename)
imageNamed: (@_imagepath) ->
imageWriteToSavedPicture:(fname, action)->
$.post "syslibs/library.php",
mode: "savePicture"
imagepath: @_imagepath
fpath: fname
,(ret)=>
if (action?)
action(ret)
|
[
{
"context": "ate:paused;\ndisplay:none;\n}\n\n\n\n/* \n *Contact me at zashworth2@gmail.com\n *Github link https://github.com/ashworth-zach\n *",
"end": 2098,
"score": 0.9999268651008606,
"start": 2078,
"tag": "EMAIL",
"value": "zashworth2@gmail.com"
},
{
"context": "worth2@gmail.co... | static/coffeescript/index.coffee | ashworth-zach/SelfCodingLandingPage | 1 | styles = """
body {
background-color: #1a1c24; color: #fff;
font-size: 13px; line-height: 1.4;
-webkit-font-smoothing: subpixel-antialiased;
}
.container{
height:100px;
}
pre em:not(.comment) { font-style: normal; }
.comment { color: #00b3ff; }
.selector { color: #00fdd3; }
.selector .key { color: #66ff00; }
.key { color: #ffffff; }
.value { color: #3787ff; }
pre {
box-shadow:20px 20px 50px 15px grey;
position: fixed; width: 48%;
top: 30px; bottom: 30px; left: 52%;
transition: left 500ms;
overflow: auto;
background-color: #313744; color: #a6c3d4;
border: 1px solid white;
padding: 24px 12px;
box-sizing: border-box;
border-radius: 3px;
transform: skewY(2deg);
}
.container{
box-shadow:20px 20px 50px 15px grey;
background-color:blue;
background-color:lime;
background-color:yellow;
background-color:red;
background-color: #313744; color: #a6c3d4;
position: fixed; width: 48%;
top: 30px; bottom: 30px; left: 0%;
transition: left 500ms;
overflow: auto;
border: 1px solid white;
padding: 24px 12px;
box-sizing: border-box;
border-radius: 3px;
transform: skewY(-2deg);
height:90%;
}
:root {
--size: 140px;
--speed: 5s;
}
.Frontend::before{
color:white;
content:"Frontend";
}
.github::before{color:white;content:"See my pinned repositories on github for projects";}
.react::before{content:"React";}
.angular::before{content:"Angular";}
.js::before{content:"Javascript and JQuery";}
.backend::before{color:white;content:"Backend"}
.flask::before{content:"Flask";}
.django::before{content:"Django";}
.asp::before{content:".Net, and Entity framework";}
.mean::before{content:"Full stack MEAN";}
.databases::before{color:white;content:"Databases";}
.mongo::before{content:"MongoDB";}
.mysql::before{content:"MySQL";}
a{
display:block;
}
.typewriter h1 {
animation-play-state:running;
}
.loader:before{
animation-play-state:paused;
display:none;
}
.loader:after{
animation-play-state:paused;
display:none;
}
.loader{
animation-play-state:paused;
display:none;
}
/*
*Contact me at zashworth2@gmail.com
*Github link https://github.com/ashworth-zach
*CodePen https://codepen.io/ashworth-zach
*/
"""
writeStyleChar = (which) ->
# begin wrapping open comments
if which == '/' && openComment == false
openComment = true
styles = $('#style-text').html() + which
else if which == '/' && openComment == true
openComment = false
styles = $('#style-text').html().replace(/(\/[^\/]*\*)$/, '<em class="comment">$1/</em>')
# wrap style declaration
else if which == ':'
styles = $('#style-text').html().replace(/([a-zA-Z- ^\n]*)$/, '<em class="key">$1</em>:')
# wrap style value
else if which == ';'
styles = $('#style-text').html().replace(/([^:]*)$/, '<em class="value">$1</em>;')
# wrap selector
else if which == '{'
styles = $('#style-text').html().replace(/(.*)$/, '<em class="selector">$1</em>{')
else
styles = $('#style-text').html() + which
$('#style-text').html styles
$('#style-tag').append which
writeStyles = (message, index, interval) ->
if index < message.length
pre = document.getElementById 'style-text'
pre.scrollTop = pre.scrollHeight
writeStyleChar message[index++]
setTimeout (->
writeStyles message, index, interval
), interval
# appending the tags I'll need.
$('body').append """
<style id="style-tag"></style>
<pre id="style-text"></pre>
"""
# faster typing in small iframe on codepen homepage
# time = if window.innerWidth <= 578 then 4 else 16
# starting it off
writeStyles(styles, 0, 1)
| 190130 | styles = """
body {
background-color: #1a1c24; color: #fff;
font-size: 13px; line-height: 1.4;
-webkit-font-smoothing: subpixel-antialiased;
}
.container{
height:100px;
}
pre em:not(.comment) { font-style: normal; }
.comment { color: #00b3ff; }
.selector { color: #00fdd3; }
.selector .key { color: #66ff00; }
.key { color: #ffffff; }
.value { color: #3787ff; }
pre {
box-shadow:20px 20px 50px 15px grey;
position: fixed; width: 48%;
top: 30px; bottom: 30px; left: 52%;
transition: left 500ms;
overflow: auto;
background-color: #313744; color: #a6c3d4;
border: 1px solid white;
padding: 24px 12px;
box-sizing: border-box;
border-radius: 3px;
transform: skewY(2deg);
}
.container{
box-shadow:20px 20px 50px 15px grey;
background-color:blue;
background-color:lime;
background-color:yellow;
background-color:red;
background-color: #313744; color: #a6c3d4;
position: fixed; width: 48%;
top: 30px; bottom: 30px; left: 0%;
transition: left 500ms;
overflow: auto;
border: 1px solid white;
padding: 24px 12px;
box-sizing: border-box;
border-radius: 3px;
transform: skewY(-2deg);
height:90%;
}
:root {
--size: 140px;
--speed: 5s;
}
.Frontend::before{
color:white;
content:"Frontend";
}
.github::before{color:white;content:"See my pinned repositories on github for projects";}
.react::before{content:"React";}
.angular::before{content:"Angular";}
.js::before{content:"Javascript and JQuery";}
.backend::before{color:white;content:"Backend"}
.flask::before{content:"Flask";}
.django::before{content:"Django";}
.asp::before{content:".Net, and Entity framework";}
.mean::before{content:"Full stack MEAN";}
.databases::before{color:white;content:"Databases";}
.mongo::before{content:"MongoDB";}
.mysql::before{content:"MySQL";}
a{
display:block;
}
.typewriter h1 {
animation-play-state:running;
}
.loader:before{
animation-play-state:paused;
display:none;
}
.loader:after{
animation-play-state:paused;
display:none;
}
.loader{
animation-play-state:paused;
display:none;
}
/*
*Contact me at <EMAIL>
*Github link https://github.com/ashworth-zach
*CodePen https://codepen.io/ashworth-zach
*/
"""
writeStyleChar = (which) ->
# begin wrapping open comments
if which == '/' && openComment == false
openComment = true
styles = $('#style-text').html() + which
else if which == '/' && openComment == true
openComment = false
styles = $('#style-text').html().replace(/(\/[^\/]*\*)$/, '<em class="comment">$1/</em>')
# wrap style declaration
else if which == ':'
styles = $('#style-text').html().replace(/([a-zA-Z- ^\n]*)$/, '<em class="key">$1</em>:')
# wrap style value
else if which == ';'
styles = $('#style-text').html().replace(/([^:]*)$/, '<em class="value">$1</em>;')
# wrap selector
else if which == '{'
styles = $('#style-text').html().replace(/(.*)$/, '<em class="selector">$1</em>{')
else
styles = $('#style-text').html() + which
$('#style-text').html styles
$('#style-tag').append which
writeStyles = (message, index, interval) ->
if index < message.length
pre = document.getElementById 'style-text'
pre.scrollTop = pre.scrollHeight
writeStyleChar message[index++]
setTimeout (->
writeStyles message, index, interval
), interval
# appending the tags I'll need.
$('body').append """
<style id="style-tag"></style>
<pre id="style-text"></pre>
"""
# faster typing in small iframe on codepen homepage
# time = if window.innerWidth <= 578 then 4 else 16
# starting it off
writeStyles(styles, 0, 1)
| true | styles = """
body {
background-color: #1a1c24; color: #fff;
font-size: 13px; line-height: 1.4;
-webkit-font-smoothing: subpixel-antialiased;
}
.container{
height:100px;
}
pre em:not(.comment) { font-style: normal; }
.comment { color: #00b3ff; }
.selector { color: #00fdd3; }
.selector .key { color: #66ff00; }
.key { color: #ffffff; }
.value { color: #3787ff; }
pre {
box-shadow:20px 20px 50px 15px grey;
position: fixed; width: 48%;
top: 30px; bottom: 30px; left: 52%;
transition: left 500ms;
overflow: auto;
background-color: #313744; color: #a6c3d4;
border: 1px solid white;
padding: 24px 12px;
box-sizing: border-box;
border-radius: 3px;
transform: skewY(2deg);
}
.container{
box-shadow:20px 20px 50px 15px grey;
background-color:blue;
background-color:lime;
background-color:yellow;
background-color:red;
background-color: #313744; color: #a6c3d4;
position: fixed; width: 48%;
top: 30px; bottom: 30px; left: 0%;
transition: left 500ms;
overflow: auto;
border: 1px solid white;
padding: 24px 12px;
box-sizing: border-box;
border-radius: 3px;
transform: skewY(-2deg);
height:90%;
}
:root {
--size: 140px;
--speed: 5s;
}
.Frontend::before{
color:white;
content:"Frontend";
}
.github::before{color:white;content:"See my pinned repositories on github for projects";}
.react::before{content:"React";}
.angular::before{content:"Angular";}
.js::before{content:"Javascript and JQuery";}
.backend::before{color:white;content:"Backend"}
.flask::before{content:"Flask";}
.django::before{content:"Django";}
.asp::before{content:".Net, and Entity framework";}
.mean::before{content:"Full stack MEAN";}
.databases::before{color:white;content:"Databases";}
.mongo::before{content:"MongoDB";}
.mysql::before{content:"MySQL";}
a{
display:block;
}
.typewriter h1 {
animation-play-state:running;
}
.loader:before{
animation-play-state:paused;
display:none;
}
.loader:after{
animation-play-state:paused;
display:none;
}
.loader{
animation-play-state:paused;
display:none;
}
/*
*Contact me at PI:EMAIL:<EMAIL>END_PI
*Github link https://github.com/ashworth-zach
*CodePen https://codepen.io/ashworth-zach
*/
"""
writeStyleChar = (which) ->
# begin wrapping open comments
if which == '/' && openComment == false
openComment = true
styles = $('#style-text').html() + which
else if which == '/' && openComment == true
openComment = false
styles = $('#style-text').html().replace(/(\/[^\/]*\*)$/, '<em class="comment">$1/</em>')
# wrap style declaration
else if which == ':'
styles = $('#style-text').html().replace(/([a-zA-Z- ^\n]*)$/, '<em class="key">$1</em>:')
# wrap style value
else if which == ';'
styles = $('#style-text').html().replace(/([^:]*)$/, '<em class="value">$1</em>;')
# wrap selector
else if which == '{'
styles = $('#style-text').html().replace(/(.*)$/, '<em class="selector">$1</em>{')
else
styles = $('#style-text').html() + which
$('#style-text').html styles
$('#style-tag').append which
writeStyles = (message, index, interval) ->
if index < message.length
pre = document.getElementById 'style-text'
pre.scrollTop = pre.scrollHeight
writeStyleChar message[index++]
setTimeout (->
writeStyles message, index, interval
), interval
# appending the tags I'll need.
$('body').append """
<style id="style-tag"></style>
<pre id="style-text"></pre>
"""
# faster typing in small iframe on codepen homepage
# time = if window.innerWidth <= 578 then 4 else 16
# starting it off
writeStyles(styles, 0, 1)
|
[
{
"context": "dModel extends Backbone.Model\n idAttribute: 'eyeDee'\n url: 'eyes/'\n model = new Nonstandar",
"end": 2380,
"score": 0.6830521821975708,
"start": 2377,
"tag": "NAME",
"value": "eye"
},
{
"context": "del extends Backbone.Model\n idAttribute: 'eyeDee'\n... | spec/integration_spec.coffee | GerHobbelt/Backbone.dualStorage | 0 | {backboneSync, localsync, dualSync, localStorage} = window
{collection, model} = {}
beforeEach ->
backboneSync.calls = []
localsync 'clear', {}, ignoreCallbacks: true, storeName: 'eyes/'
collection = new Backbone.Collection
id: 123
vision: 'crystal'
collection.url = 'eyes/'
model = collection.models[0]
describe 'using Backbone.sync directly', ->
it 'should save and retrieve data', ->
{successCallback, errorCallback} = {}
saved = false
runs ->
localStorage.clear()
successCallback = jasmine.createSpy('success').andCallFake -> saved = true
errorCallback = jasmine.createSpy('error')
dualsync 'create', model, success: successCallback, error: errorCallback
waitsFor (-> saved), "The success callback for 'create' should have been called", 100
runs ->
expect(backboneSync.calls.length).toEqual(1)
expect(successCallback).toHaveBeenCalled()
expect(errorCallback).not.toHaveBeenCalled()
expect(localStorage.length).toBeGreaterThan(0)
fetched = false
runs ->
successCallback = jasmine.createSpy('success').andCallFake callbackTranslator.forBackboneCaller (resp) ->
fetched = true
expect(resp.vision).toEqual('crystal')
errorCallback = jasmine.createSpy('error')
dualsync 'read', model, success: successCallback, error: errorCallback
waitsFor (-> fetched), "The success callback for 'read' should have been called", 100
runs ->
expect(backboneSync.calls.length).toEqual(2)
expect(successCallback).toHaveBeenCalled()
expect(errorCallback).not.toHaveBeenCalled()
describe 'using backbone models and retrieving from local storage', ->
it "fetches a model after saving it", ->
saved = false
runs ->
model.save {}, success: -> saved = true
waitsFor (-> saved), "The success callback for 'save' should have been called", 100
fetched = false
retrievedModel = new Backbone.Model id: 123
retrievedModel.collection = collection
runs ->
retrievedModel.fetch remote: false, success: -> fetched = true
waitsFor (-> fetched), "The success callback for 'fetch' should have been called", 100
runs ->
expect(retrievedModel.get('vision')).toEqual('crystal')
it "works with an idAttribute other than 'id'", ->
class NonstandardModel extends Backbone.Model
idAttribute: 'eyeDee'
url: 'eyes/'
model = new NonstandardModel eyeDee: 123, vision: 'crystal'
saved = false
runs ->
model.save {}, success: -> saved = true
waitsFor (-> saved), "The success callback for 'save' should have been called", 100
fetched = false
retrievedModel = new NonstandardModel eyeDee: 123
runs ->
retrievedModel.fetch remote: false, success: -> fetched = true
waitsFor (-> fetched), "The success callback for 'fetch' should have been called", 100
runs ->
expect(retrievedModel.get('vision')).toEqual('crystal')
describe 'using backbone collections and retrieving from local storage', ->
it 'loads a collection after adding several models to it', ->
saved = 0
runs ->
for id in [1..3]
newModel = new Backbone.Model id: id
newModel.collection = collection
newModel.save {}, success: -> saved += 1
waitsFor (-> saved == 3), "The success callback for 'save' should have been called for id ##{id}", 100
fetched = false
runs ->
collection.fetch remote: false, success: -> fetched = true
waitsFor (-> fetched), "The success callback for 'fetch' should have been called", 100
runs ->
expect(collection.length).toEqual(3)
expect(collection.map (model) -> model.id).toEqual [1,2,3]
describe 'success and error callback parameters', ->
it "passes back the response into the remote method's callback", ->
callbackResponse = null
runs ->
model.remote = true
model.fetch success: (args...) -> callbackResponse = args
waitsFor (-> callbackResponse), "The success callback for 'fetch' should have been called", 100
runs ->
expect(callbackResponse[0]).toEqual model
expect(callbackResponse[1]).toEqual model.attributes
| 49041 | {backboneSync, localsync, dualSync, localStorage} = window
{collection, model} = {}
beforeEach ->
backboneSync.calls = []
localsync 'clear', {}, ignoreCallbacks: true, storeName: 'eyes/'
collection = new Backbone.Collection
id: 123
vision: 'crystal'
collection.url = 'eyes/'
model = collection.models[0]
describe 'using Backbone.sync directly', ->
it 'should save and retrieve data', ->
{successCallback, errorCallback} = {}
saved = false
runs ->
localStorage.clear()
successCallback = jasmine.createSpy('success').andCallFake -> saved = true
errorCallback = jasmine.createSpy('error')
dualsync 'create', model, success: successCallback, error: errorCallback
waitsFor (-> saved), "The success callback for 'create' should have been called", 100
runs ->
expect(backboneSync.calls.length).toEqual(1)
expect(successCallback).toHaveBeenCalled()
expect(errorCallback).not.toHaveBeenCalled()
expect(localStorage.length).toBeGreaterThan(0)
fetched = false
runs ->
successCallback = jasmine.createSpy('success').andCallFake callbackTranslator.forBackboneCaller (resp) ->
fetched = true
expect(resp.vision).toEqual('crystal')
errorCallback = jasmine.createSpy('error')
dualsync 'read', model, success: successCallback, error: errorCallback
waitsFor (-> fetched), "The success callback for 'read' should have been called", 100
runs ->
expect(backboneSync.calls.length).toEqual(2)
expect(successCallback).toHaveBeenCalled()
expect(errorCallback).not.toHaveBeenCalled()
describe 'using backbone models and retrieving from local storage', ->
it "fetches a model after saving it", ->
saved = false
runs ->
model.save {}, success: -> saved = true
waitsFor (-> saved), "The success callback for 'save' should have been called", 100
fetched = false
retrievedModel = new Backbone.Model id: 123
retrievedModel.collection = collection
runs ->
retrievedModel.fetch remote: false, success: -> fetched = true
waitsFor (-> fetched), "The success callback for 'fetch' should have been called", 100
runs ->
expect(retrievedModel.get('vision')).toEqual('crystal')
it "works with an idAttribute other than 'id'", ->
class NonstandardModel extends Backbone.Model
idAttribute: '<NAME>Dee'
url: 'eyes/'
model = new NonstandardModel eyeDee: 123, vision: 'crystal'
saved = false
runs ->
model.save {}, success: -> saved = true
waitsFor (-> saved), "The success callback for 'save' should have been called", 100
fetched = false
retrievedModel = new NonstandardModel eyeDee: 123
runs ->
retrievedModel.fetch remote: false, success: -> fetched = true
waitsFor (-> fetched), "The success callback for 'fetch' should have been called", 100
runs ->
expect(retrievedModel.get('vision')).toEqual('crystal')
describe 'using backbone collections and retrieving from local storage', ->
it 'loads a collection after adding several models to it', ->
saved = 0
runs ->
for id in [1..3]
newModel = new Backbone.Model id: id
newModel.collection = collection
newModel.save {}, success: -> saved += 1
waitsFor (-> saved == 3), "The success callback for 'save' should have been called for id ##{id}", 100
fetched = false
runs ->
collection.fetch remote: false, success: -> fetched = true
waitsFor (-> fetched), "The success callback for 'fetch' should have been called", 100
runs ->
expect(collection.length).toEqual(3)
expect(collection.map (model) -> model.id).toEqual [1,2,3]
describe 'success and error callback parameters', ->
it "passes back the response into the remote method's callback", ->
callbackResponse = null
runs ->
model.remote = true
model.fetch success: (args...) -> callbackResponse = args
waitsFor (-> callbackResponse), "The success callback for 'fetch' should have been called", 100
runs ->
expect(callbackResponse[0]).toEqual model
expect(callbackResponse[1]).toEqual model.attributes
| true | {backboneSync, localsync, dualSync, localStorage} = window
{collection, model} = {}
beforeEach ->
backboneSync.calls = []
localsync 'clear', {}, ignoreCallbacks: true, storeName: 'eyes/'
collection = new Backbone.Collection
id: 123
vision: 'crystal'
collection.url = 'eyes/'
model = collection.models[0]
describe 'using Backbone.sync directly', ->
it 'should save and retrieve data', ->
{successCallback, errorCallback} = {}
saved = false
runs ->
localStorage.clear()
successCallback = jasmine.createSpy('success').andCallFake -> saved = true
errorCallback = jasmine.createSpy('error')
dualsync 'create', model, success: successCallback, error: errorCallback
waitsFor (-> saved), "The success callback for 'create' should have been called", 100
runs ->
expect(backboneSync.calls.length).toEqual(1)
expect(successCallback).toHaveBeenCalled()
expect(errorCallback).not.toHaveBeenCalled()
expect(localStorage.length).toBeGreaterThan(0)
fetched = false
runs ->
successCallback = jasmine.createSpy('success').andCallFake callbackTranslator.forBackboneCaller (resp) ->
fetched = true
expect(resp.vision).toEqual('crystal')
errorCallback = jasmine.createSpy('error')
dualsync 'read', model, success: successCallback, error: errorCallback
waitsFor (-> fetched), "The success callback for 'read' should have been called", 100
runs ->
expect(backboneSync.calls.length).toEqual(2)
expect(successCallback).toHaveBeenCalled()
expect(errorCallback).not.toHaveBeenCalled()
describe 'using backbone models and retrieving from local storage', ->
it "fetches a model after saving it", ->
saved = false
runs ->
model.save {}, success: -> saved = true
waitsFor (-> saved), "The success callback for 'save' should have been called", 100
fetched = false
retrievedModel = new Backbone.Model id: 123
retrievedModel.collection = collection
runs ->
retrievedModel.fetch remote: false, success: -> fetched = true
waitsFor (-> fetched), "The success callback for 'fetch' should have been called", 100
runs ->
expect(retrievedModel.get('vision')).toEqual('crystal')
it "works with an idAttribute other than 'id'", ->
class NonstandardModel extends Backbone.Model
idAttribute: 'PI:NAME:<NAME>END_PIDee'
url: 'eyes/'
model = new NonstandardModel eyeDee: 123, vision: 'crystal'
saved = false
runs ->
model.save {}, success: -> saved = true
waitsFor (-> saved), "The success callback for 'save' should have been called", 100
fetched = false
retrievedModel = new NonstandardModel eyeDee: 123
runs ->
retrievedModel.fetch remote: false, success: -> fetched = true
waitsFor (-> fetched), "The success callback for 'fetch' should have been called", 100
runs ->
expect(retrievedModel.get('vision')).toEqual('crystal')
describe 'using backbone collections and retrieving from local storage', ->
it 'loads a collection after adding several models to it', ->
saved = 0
runs ->
for id in [1..3]
newModel = new Backbone.Model id: id
newModel.collection = collection
newModel.save {}, success: -> saved += 1
waitsFor (-> saved == 3), "The success callback for 'save' should have been called for id ##{id}", 100
fetched = false
runs ->
collection.fetch remote: false, success: -> fetched = true
waitsFor (-> fetched), "The success callback for 'fetch' should have been called", 100
runs ->
expect(collection.length).toEqual(3)
expect(collection.map (model) -> model.id).toEqual [1,2,3]
describe 'success and error callback parameters', ->
it "passes back the response into the remote method's callback", ->
callbackResponse = null
runs ->
model.remote = true
model.fetch success: (args...) -> callbackResponse = args
waitsFor (-> callbackResponse), "The success callback for 'fetch' should have been called", 100
runs ->
expect(callbackResponse[0]).toEqual model
expect(callbackResponse[1]).toEqual model.attributes
|
[
{
"context": "@name\n header: {rows: 1}\n mainKeyName: \"数据名\"\n columnToKey: {'*':'{{columnHeader}}'}\n ",
"end": 1985,
"score": 0.7663877010345459,
"start": 1982,
"tag": "KEY",
"value": "数据名"
}
] | analyze/singletons.coffee | Tostig0916/hqcoffee | 2 | path = require 'path'
{JSONUtils} = require './jsonUtils'
StormDB = require 'stormdb'
# 抽象class 将共性放在此处
# 所有从Excel转换而来的JSON辅助文件,均为一对一关系,故均使用class一侧编程
class StormDBSingleton extends JSONUtils
# 只有从Excel转换来的JSON才可以将参数 rebuild 设置为 true
@fetchSingleJSON: (funcOpts={}) ->
{rebuild=false} = funcOpts
opts = @options()
if rebuild
opts.needToRewrite = true
@_json = @getJSON(opts)
else
@_json ?= @getJSON(opts)
@reversedJSON: ->
dictionary = @fetchSingleJSON()
# 维度指标
redict = {}
for key, value of dictionary
(redict[value] ?= []).push(key)
#console.log {redict}
redict
@_addPairs: (funcOpts={}) ->
# keep 则保存json 文件
{dict,keep=false} = funcOpts
@fetchSingleJSON(funcOpts)
for key, value of dict when key isnt value
@_json[key] ?= value
# 注意,可能会混乱
if keep
opts = @options()
opts.needToRewrite = true
opts.obj = @_json
@write2JSON(opts)
return @_json
# 依赖结构形态,使用前先观察一下结构是否一致
@renameKey: (funcOpts) ->
{dict, theClass} = funcOpts
###
{
'2016年': 'y2016'
'2017年': 'y2017'
'2018年': 'y2018'
'2019年': 'y2019'
'2020年': 'y2020'
'2021年': 'y2021'
}
###
obj = theClass.dbValue()
for unit, collection of obj
for indicator, data of collection
for key, value of data
if dict[key]?
theClass.dbSet("#{unit}.#{indicator}.#{dict[key]}", value)
theClass.dbDelete("#{unit}.#{indicator}.#{key}")
theClass.dbSave()
@normalKeyName: ({mainKey}) =>
# keep 则保存json文件
别名库.ajustedName({name:mainKey,keep:true})
@options: ->
class AnyGlobalSingleton extends StormDBSingleton
@_dbPath: ->
path.join __dirname, "..", "data","JSON" ,"#{@name}.json"
@options: ->
# 此处不可以记入变量,是否影响子法随宜重新定义?
@_options ?= {
folder: 'data'
basename: @name
header: {rows: 1}
mainKeyName: "数据名"
columnToKey: {'*':'{{columnHeader}}'}
sheetStubs: true
needToRewrite: true
unwrap: true #false
renaming: @normalKeyName
}
# 别名正名对照及转换
class 别名库 extends AnyGlobalSingleton
# 获取正名,同时会增补更新别名表
@ajustedName: (funcOpts={}) ->
{name,keep=false} = funcOpts
json = @fetchSingleJSON()
switch
when (correctName = json[name])?
console.log {name, correctName}
correctName
else switch
# 正名须去掉黑三角等特殊中英文字符,否则不能作为function 名字
when /[*↑↓()(、)/▲\ ]/i.test(name)
console.log("#{name}: 命名不应含顿号") if /、/i.test(name)
cleanName = (each for each in name when not /[*↑↓()(、)/▲\ ]/.test(each)).join('')
unless (correctName = json[cleanName])?
dict = {"#{name}":"#{cleanName}"}
@_addPairs({dict,keep}) #unless /、/i.test(name)
#console.log {name, correctName}
correctName ? cleanName
else
name
# 别名库自己无须改名
@normalKeyName: ({mainKey}) =>
return mainKey
@_dbPath: ->
path.join __dirname, "..", "data","JSON" ,"别名库.json"
@options: ->
super()
@_options.basename = '别名库'
@_options.needToRewrite = false
@_options.rebuild = false
return @_options
@fetchSingleJSON: (funcOpts={}) ->
{rebuild=false} = funcOpts
opts = @options()
opts.needToRewrite = false
if rebuild
@_json = @getJSON(opts)
else
@_json ?= @getJSON(opts)
# 此表为 singleton,只有一个instance,故可使用类侧定义
###
# 指标维度表
class 三级指标对应二级指标 extends AnyGlobalSingleton
class 指标导向库 extends AnyGlobalSingleton
@导向指标集: ->
@dbRevertedValue()
###
class 名字ID库 extends AnyGlobalSingleton
class 简称库 extends AnyGlobalSingleton
module.exports = {
StormDBSingleton
#AnyGlobalSingleton
别名库
名字ID库
}
| 36741 | path = require 'path'
{JSONUtils} = require './jsonUtils'
StormDB = require 'stormdb'
# 抽象class 将共性放在此处
# 所有从Excel转换而来的JSON辅助文件,均为一对一关系,故均使用class一侧编程
class StormDBSingleton extends JSONUtils
# 只有从Excel转换来的JSON才可以将参数 rebuild 设置为 true
@fetchSingleJSON: (funcOpts={}) ->
{rebuild=false} = funcOpts
opts = @options()
if rebuild
opts.needToRewrite = true
@_json = @getJSON(opts)
else
@_json ?= @getJSON(opts)
@reversedJSON: ->
dictionary = @fetchSingleJSON()
# 维度指标
redict = {}
for key, value of dictionary
(redict[value] ?= []).push(key)
#console.log {redict}
redict
@_addPairs: (funcOpts={}) ->
# keep 则保存json 文件
{dict,keep=false} = funcOpts
@fetchSingleJSON(funcOpts)
for key, value of dict when key isnt value
@_json[key] ?= value
# 注意,可能会混乱
if keep
opts = @options()
opts.needToRewrite = true
opts.obj = @_json
@write2JSON(opts)
return @_json
# 依赖结构形态,使用前先观察一下结构是否一致
@renameKey: (funcOpts) ->
{dict, theClass} = funcOpts
###
{
'2016年': 'y2016'
'2017年': 'y2017'
'2018年': 'y2018'
'2019年': 'y2019'
'2020年': 'y2020'
'2021年': 'y2021'
}
###
obj = theClass.dbValue()
for unit, collection of obj
for indicator, data of collection
for key, value of data
if dict[key]?
theClass.dbSet("#{unit}.#{indicator}.#{dict[key]}", value)
theClass.dbDelete("#{unit}.#{indicator}.#{key}")
theClass.dbSave()
@normalKeyName: ({mainKey}) =>
# keep 则保存json文件
别名库.ajustedName({name:mainKey,keep:true})
@options: ->
class AnyGlobalSingleton extends StormDBSingleton
@_dbPath: ->
path.join __dirname, "..", "data","JSON" ,"#{@name}.json"
@options: ->
# 此处不可以记入变量,是否影响子法随宜重新定义?
@_options ?= {
folder: 'data'
basename: @name
header: {rows: 1}
mainKeyName: "<KEY>"
columnToKey: {'*':'{{columnHeader}}'}
sheetStubs: true
needToRewrite: true
unwrap: true #false
renaming: @normalKeyName
}
# 别名正名对照及转换
class 别名库 extends AnyGlobalSingleton
# 获取正名,同时会增补更新别名表
@ajustedName: (funcOpts={}) ->
{name,keep=false} = funcOpts
json = @fetchSingleJSON()
switch
when (correctName = json[name])?
console.log {name, correctName}
correctName
else switch
# 正名须去掉黑三角等特殊中英文字符,否则不能作为function 名字
when /[*↑↓()(、)/▲\ ]/i.test(name)
console.log("#{name}: 命名不应含顿号") if /、/i.test(name)
cleanName = (each for each in name when not /[*↑↓()(、)/▲\ ]/.test(each)).join('')
unless (correctName = json[cleanName])?
dict = {"#{name}":"#{cleanName}"}
@_addPairs({dict,keep}) #unless /、/i.test(name)
#console.log {name, correctName}
correctName ? cleanName
else
name
# 别名库自己无须改名
@normalKeyName: ({mainKey}) =>
return mainKey
@_dbPath: ->
path.join __dirname, "..", "data","JSON" ,"别名库.json"
@options: ->
super()
@_options.basename = '别名库'
@_options.needToRewrite = false
@_options.rebuild = false
return @_options
@fetchSingleJSON: (funcOpts={}) ->
{rebuild=false} = funcOpts
opts = @options()
opts.needToRewrite = false
if rebuild
@_json = @getJSON(opts)
else
@_json ?= @getJSON(opts)
# 此表为 singleton,只有一个instance,故可使用类侧定义
###
# 指标维度表
class 三级指标对应二级指标 extends AnyGlobalSingleton
class 指标导向库 extends AnyGlobalSingleton
@导向指标集: ->
@dbRevertedValue()
###
class 名字ID库 extends AnyGlobalSingleton
class 简称库 extends AnyGlobalSingleton
module.exports = {
StormDBSingleton
#AnyGlobalSingleton
别名库
名字ID库
}
| true | path = require 'path'
{JSONUtils} = require './jsonUtils'
StormDB = require 'stormdb'
# 抽象class 将共性放在此处
# 所有从Excel转换而来的JSON辅助文件,均为一对一关系,故均使用class一侧编程
class StormDBSingleton extends JSONUtils
# 只有从Excel转换来的JSON才可以将参数 rebuild 设置为 true
@fetchSingleJSON: (funcOpts={}) ->
{rebuild=false} = funcOpts
opts = @options()
if rebuild
opts.needToRewrite = true
@_json = @getJSON(opts)
else
@_json ?= @getJSON(opts)
@reversedJSON: ->
dictionary = @fetchSingleJSON()
# 维度指标
redict = {}
for key, value of dictionary
(redict[value] ?= []).push(key)
#console.log {redict}
redict
@_addPairs: (funcOpts={}) ->
# keep 则保存json 文件
{dict,keep=false} = funcOpts
@fetchSingleJSON(funcOpts)
for key, value of dict when key isnt value
@_json[key] ?= value
# 注意,可能会混乱
if keep
opts = @options()
opts.needToRewrite = true
opts.obj = @_json
@write2JSON(opts)
return @_json
# 依赖结构形态,使用前先观察一下结构是否一致
@renameKey: (funcOpts) ->
{dict, theClass} = funcOpts
###
{
'2016年': 'y2016'
'2017年': 'y2017'
'2018年': 'y2018'
'2019年': 'y2019'
'2020年': 'y2020'
'2021年': 'y2021'
}
###
obj = theClass.dbValue()
for unit, collection of obj
for indicator, data of collection
for key, value of data
if dict[key]?
theClass.dbSet("#{unit}.#{indicator}.#{dict[key]}", value)
theClass.dbDelete("#{unit}.#{indicator}.#{key}")
theClass.dbSave()
@normalKeyName: ({mainKey}) =>
# keep 则保存json文件
别名库.ajustedName({name:mainKey,keep:true})
@options: ->
class AnyGlobalSingleton extends StormDBSingleton
@_dbPath: ->
path.join __dirname, "..", "data","JSON" ,"#{@name}.json"
@options: ->
# 此处不可以记入变量,是否影响子法随宜重新定义?
@_options ?= {
folder: 'data'
basename: @name
header: {rows: 1}
mainKeyName: "PI:KEY:<KEY>END_PI"
columnToKey: {'*':'{{columnHeader}}'}
sheetStubs: true
needToRewrite: true
unwrap: true #false
renaming: @normalKeyName
}
# 别名正名对照及转换
class 别名库 extends AnyGlobalSingleton
# 获取正名,同时会增补更新别名表
@ajustedName: (funcOpts={}) ->
{name,keep=false} = funcOpts
json = @fetchSingleJSON()
switch
when (correctName = json[name])?
console.log {name, correctName}
correctName
else switch
# 正名须去掉黑三角等特殊中英文字符,否则不能作为function 名字
when /[*↑↓()(、)/▲\ ]/i.test(name)
console.log("#{name}: 命名不应含顿号") if /、/i.test(name)
cleanName = (each for each in name when not /[*↑↓()(、)/▲\ ]/.test(each)).join('')
unless (correctName = json[cleanName])?
dict = {"#{name}":"#{cleanName}"}
@_addPairs({dict,keep}) #unless /、/i.test(name)
#console.log {name, correctName}
correctName ? cleanName
else
name
# 别名库自己无须改名
@normalKeyName: ({mainKey}) =>
return mainKey
@_dbPath: ->
path.join __dirname, "..", "data","JSON" ,"别名库.json"
@options: ->
super()
@_options.basename = '别名库'
@_options.needToRewrite = false
@_options.rebuild = false
return @_options
@fetchSingleJSON: (funcOpts={}) ->
{rebuild=false} = funcOpts
opts = @options()
opts.needToRewrite = false
if rebuild
@_json = @getJSON(opts)
else
@_json ?= @getJSON(opts)
# 此表为 singleton,只有一个instance,故可使用类侧定义
###
# 指标维度表
class 三级指标对应二级指标 extends AnyGlobalSingleton
class 指标导向库 extends AnyGlobalSingleton
@导向指标集: ->
@dbRevertedValue()
###
class 名字ID库 extends AnyGlobalSingleton
class 简称库 extends AnyGlobalSingleton
module.exports = {
StormDBSingleton
#AnyGlobalSingleton
别名库
名字ID库
}
|
[
{
"context": "ashTable = require('../HashTable')\n\nsomeNames = [\"David\", \"Jennifer\", \"Donnie\", \"Raymond\",\n \"",
"end": 56,
"score": 0.9998560547828674,
"start": 51,
"tag": "NAME",
"value": "David"
},
{
"context": "= require('../HashTable')\n\nsomeNames = [\"Davi... | HashTable/test/method.coffee | youqingkui/DataStructure | 0 | HashTable = require('../HashTable')
someNames = ["David", "Jennifer", "Donnie", "Raymond",
"Cynthia", "Mike", "Clayton", "Danny", "Jonathan"]
hTable = new HashTable()
for i in someNames
hTable.put i
hTable.showDistro() | 61121 | HashTable = require('../HashTable')
someNames = ["<NAME>", "<NAME>", "<NAME>", "<NAME>",
"<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>"]
hTable = new HashTable()
for i in someNames
hTable.put i
hTable.showDistro() | true | HashTable = require('../HashTable')
someNames = ["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", "PI:NAME:<NAME>END_PI"]
hTable = new HashTable()
for i in someNames
hTable.put i
hTable.showDistro() |
[
{
"context": "yHelper'\n\n #general pathes\n DS_URL: \"http://127.0.0.1\"\n DS_PORT: 9101\n DI_PORT: 9102\n\n #specif",
"end": 684,
"score": 0.9960315227508545,
"start": 675,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "username = process.env.NAME\n ... | server/lib/dataSystem.coffee | poupotte/cozy-databrowser | 0 | CoreClass = require './../helpers/CoreClass'
#********************************************************
#******************** CLASS DataSystem ******************
#********************************************************
#@description : used to communicate with the cozy data-system
class DataSystem extends CoreClass
#------------------ CONSTRUCTOR CONSTANTS ----------------
@CLASS_NAME: "DataSystem"
#------------------ PROTOTYPE CONSTANTS ----------------
#required dependencies
JSON_CLIENT: require('request-json').JsonClient
ASYNC: require 'async'
ARRAY_HELPER: require './../helpers/oArrayHelper'
#general pathes
DS_URL: "http://127.0.0.1"
DS_PORT: 9101
DI_PORT: 9102
#specific paths
PATH:
data: '/data/'
request: '/request/'
all: '/all/'
search: '/data/search/'
index: '/data/index/'
destroyAll : '/all/destroy/'
doctypes:
getall: '/doctypes'
getsums: '/request/doctypes/getsums/'
getallbyorigin : '/request/doctypes/getallbyorigin/'
metadoctype:
getallbyrelated: '/request/metadoctype/getallbyrelated/'
application:
getpermissions: '/request/application/getpermissions/'
#common error messages
ERR_MSG:
retrieveData : 'Error : Server error occurred while retrieving data.'
removeData : 'Error : Server error occurred while removing data.'
unknownDoctype : 'Error : You try to access to an unknown doctype.'
unknownParamaters : 'Error : Unknown research parameters'
unknownId : 'Error : Document ID parameter not found.'
#----------------- OBJECT PARAMETERS ---------------
constructor: ->
#------ SETTED
@clientDS = new @JSON_CLIENT @DS_URL + ':' + @DS_PORT
@registeredPatterns = {}
@isSilent = false
#------ SUB-PROCESS
#Authentification
if process.env.NODE_ENV is "production"
username = process.env.NAME
password = process.env.TOKEN
@clientDS.setBasicAuth username, password
#-------------- OBJECT METHODS ----------------------
#---- PREPARATION METHODS
prepareDballRequests: (doctypes = []) ->
setupRequestsAll = []
#prepare parameters
for doctypeName, index in doctypes
#prepare request (as a closure)
((doctypeName)=>
setupRequestsAll.push (callback) =>
doctypeName = doctypeName.toLowerCase()
path = @PATH.request + doctypeName + @PATH.all
viewFunctions =
map: (doc) ->
if doc.docType?
if doc.docType.toLowerCase() is '__pattern__'
emit doc._id, doc
@manageRequest path, viewFunctions, callback, doctypeName
)(doctypeName)
return setupRequestsAll
#---- REQUEST METHODS
manageRequest: (path, viewFunctions, callback, pattern = '') ->
# convert map/reduce to string and replace optional pattern
for key, func of viewFunctions
funcAsString = func.toString()
if pattern isnt ''
viewFunctions[key] = funcAsString.replace '__pattern__', pattern
else
viewFunctions[key] = funcAsString
#create request
@clientDS.put path, viewFunctions, (error, response, body) =>
if error
unless @silent then @_logErrorInConsole error
callback error
else
if pattern isnt ''
@registeredPatterns[pattern] = true
callback null, body
getView: (path, callback, params = {}) ->
@postData path, callback, params
getDoctypes: (callback) ->
@getData @PATH.doctypes.getall, callback
getPermissions : (callback) ->
@getView @PATH.application.getpermissions, callback
getDoctypesByOrigin : (callback) ->
viewCallback = (error, body) ->
if error?
callback error
else
newArray = []
allObj = {}
for couple in body
if couple.key?
if allObj[couple.key[0]]?
allObj[couple.key[0]].push couple.key[1]
else
allObj[couple.key[0]] = []
allObj[couple.key[0]].push couple.key[1]
for objName, obj of allObj
newObj = {}
newObj['key'] = objName
newObj['value'] = obj
newArray.push newObj
callback null, newArray
@getView @PATH.doctypes.getallbyorigin, viewCallback, group: true
getDoctypesByApplication: (callback) ->
@getPermissions (error, applications) ->
if error?
callback error
else
doctypes = []
for app in applications
appName = app.key.toLowerCase()
doctypeName = []
for objName, obj of app.value
doctypeName.push objName.toLowerCase()
doctypes.push
'key' : appName
'value' : doctypeName
callback null, doctypes
indexId: (id, aFields, callback = null) ->
fields = {"fields": aFields}
@clientDS.post @PATH.index + id, fields, (error, response, body) =>
if error or response.statusCode isnt 200
error = error || new Error body.error
unless @silent then @_logErrorInConsole error
if callback? then callback error
else
if callback? then callback null, body
clearIndexer: (callback) ->
@deleteData '/data/index/clear-all/', callback
deleteById: (id, callback) ->
@deleteData @PATH.data + id + '/', callback
deleteAllByDoctype : (doctype, callback) ->
@putData @PATH.request + doctype + @PATH.destroyAll, {}, callback
#---- CRUD HTTTP METHODS
putData: (path, params, callback) ->
@clientDS.put path, params, (error, response, body) =>
if error
error = error
unless @silent then @_logErrorInConsole error
callback error
else
callback null, body
getData: (path, callback) ->
@clientDS.get path, (error, response, body) =>
if error or response.statusCode isnt 200
error = error || new Error body.error
unless @silent then @_logErrorInConsole error
callback error
else
callback null, body
postData: (path, callback, params = {}) ->
@clientDS.post path, params, (error, response, body) =>
if error or response.statusCode isnt 200
error = error || new Error body.error
unless @silent then @_logErrorInConsole error
callback error
else
if not body.length?
body = @formatBody body
callback null, body
deleteData: (path, callback) ->
@clientDS.del path, (error, response, body) =>
status = response.statusCode
if error or (status isnt 204 and status isnt 200)
error = error || new Error body.error
unless @silent then @_logErrorInConsole error
callback error
else
callback null, body
#---- FORMAT METHODS
formatBody: (body) ->
formattedBody = []
if body.rows? and body.rows.length > 0
for row in body.rows
formattedRow = {}
if row._id? then formattedRow['id'] = row._id
if row.docType? then formattedRow['key'] = row.docType
formattedRow['value'] = row
formattedBody.push formattedRow
return formattedBody
#---- VALIDATION METHODS
areValidDoctypes: (doctypes, callback = null) ->
@getDoctypes (error, registered) =>
errorMsg = null
areValid = true
bError = false
if error
errorMsg = @ERR_MSG.retrieveData
console.log error
bError = true
else
#compare given doctype and existing doctype for security
for unregistered in doctypes
if not @ARRAY_HELPER.isInArray unregistered, registered
bError = true
errorMsg = @ERR_MSG.unknownDoctype
break
areValid = not bError
if callback? then callback areValid, errorMsg
#---- GET LOCALE
getLocale: (callback = null) ->
defaultLocale = 'en'
@getView @PATH.request + 'cozyinstance' + @PATH.all, (err, instances) ->
locale = instances?[0]?.value.locale or defaultLocale
callback null, locale
#********************************************************
module.exports = new DataSystem() | 143544 | CoreClass = require './../helpers/CoreClass'
#********************************************************
#******************** CLASS DataSystem ******************
#********************************************************
#@description : used to communicate with the cozy data-system
class DataSystem extends CoreClass
#------------------ CONSTRUCTOR CONSTANTS ----------------
@CLASS_NAME: "DataSystem"
#------------------ PROTOTYPE CONSTANTS ----------------
#required dependencies
JSON_CLIENT: require('request-json').JsonClient
ASYNC: require 'async'
ARRAY_HELPER: require './../helpers/oArrayHelper'
#general pathes
DS_URL: "http://127.0.0.1"
DS_PORT: 9101
DI_PORT: 9102
#specific paths
PATH:
data: '/data/'
request: '/request/'
all: '/all/'
search: '/data/search/'
index: '/data/index/'
destroyAll : '/all/destroy/'
doctypes:
getall: '/doctypes'
getsums: '/request/doctypes/getsums/'
getallbyorigin : '/request/doctypes/getallbyorigin/'
metadoctype:
getallbyrelated: '/request/metadoctype/getallbyrelated/'
application:
getpermissions: '/request/application/getpermissions/'
#common error messages
ERR_MSG:
retrieveData : 'Error : Server error occurred while retrieving data.'
removeData : 'Error : Server error occurred while removing data.'
unknownDoctype : 'Error : You try to access to an unknown doctype.'
unknownParamaters : 'Error : Unknown research parameters'
unknownId : 'Error : Document ID parameter not found.'
#----------------- OBJECT PARAMETERS ---------------
constructor: ->
#------ SETTED
@clientDS = new @JSON_CLIENT @DS_URL + ':' + @DS_PORT
@registeredPatterns = {}
@isSilent = false
#------ SUB-PROCESS
#Authentification
if process.env.NODE_ENV is "production"
username = process.env.NAME
password = <PASSWORD>
@clientDS.setBasicAuth username, password
#-------------- OBJECT METHODS ----------------------
#---- PREPARATION METHODS
prepareDballRequests: (doctypes = []) ->
setupRequestsAll = []
#prepare parameters
for doctypeName, index in doctypes
#prepare request (as a closure)
((doctypeName)=>
setupRequestsAll.push (callback) =>
doctypeName = doctypeName.toLowerCase()
path = @PATH.request + doctypeName + @PATH.all
viewFunctions =
map: (doc) ->
if doc.docType?
if doc.docType.toLowerCase() is '__pattern__'
emit doc._id, doc
@manageRequest path, viewFunctions, callback, doctypeName
)(doctypeName)
return setupRequestsAll
#---- REQUEST METHODS
manageRequest: (path, viewFunctions, callback, pattern = '') ->
# convert map/reduce to string and replace optional pattern
for key, func of viewFunctions
funcAsString = func.toString()
if pattern isnt ''
viewFunctions[key] = funcAsString.replace '__pattern__', pattern
else
viewFunctions[key] = funcAsString
#create request
@clientDS.put path, viewFunctions, (error, response, body) =>
if error
unless @silent then @_logErrorInConsole error
callback error
else
if pattern isnt ''
@registeredPatterns[pattern] = true
callback null, body
getView: (path, callback, params = {}) ->
@postData path, callback, params
getDoctypes: (callback) ->
@getData @PATH.doctypes.getall, callback
getPermissions : (callback) ->
@getView @PATH.application.getpermissions, callback
getDoctypesByOrigin : (callback) ->
viewCallback = (error, body) ->
if error?
callback error
else
newArray = []
allObj = {}
for couple in body
if couple.key?
if allObj[couple.key[0]]?
allObj[couple.key[0]].push couple.key[1]
else
allObj[couple.key[0]] = []
allObj[couple.key[0]].push couple.key[1]
for objName, obj of allObj
newObj = {}
newObj['key'] = objName
newObj['value'] = obj
newArray.push newObj
callback null, newArray
@getView @PATH.doctypes.getallbyorigin, viewCallback, group: true
getDoctypesByApplication: (callback) ->
@getPermissions (error, applications) ->
if error?
callback error
else
doctypes = []
for app in applications
appName = app.key.toLowerCase()
doctypeName = []
for objName, obj of app.value
doctypeName.push objName.toLowerCase()
doctypes.push
'key' : appName
'value' : doctypeName
callback null, doctypes
indexId: (id, aFields, callback = null) ->
fields = {"fields": aFields}
@clientDS.post @PATH.index + id, fields, (error, response, body) =>
if error or response.statusCode isnt 200
error = error || new Error body.error
unless @silent then @_logErrorInConsole error
if callback? then callback error
else
if callback? then callback null, body
clearIndexer: (callback) ->
@deleteData '/data/index/clear-all/', callback
deleteById: (id, callback) ->
@deleteData @PATH.data + id + '/', callback
deleteAllByDoctype : (doctype, callback) ->
@putData @PATH.request + doctype + @PATH.destroyAll, {}, callback
#---- CRUD HTTTP METHODS
putData: (path, params, callback) ->
@clientDS.put path, params, (error, response, body) =>
if error
error = error
unless @silent then @_logErrorInConsole error
callback error
else
callback null, body
getData: (path, callback) ->
@clientDS.get path, (error, response, body) =>
if error or response.statusCode isnt 200
error = error || new Error body.error
unless @silent then @_logErrorInConsole error
callback error
else
callback null, body
postData: (path, callback, params = {}) ->
@clientDS.post path, params, (error, response, body) =>
if error or response.statusCode isnt 200
error = error || new Error body.error
unless @silent then @_logErrorInConsole error
callback error
else
if not body.length?
body = @formatBody body
callback null, body
deleteData: (path, callback) ->
@clientDS.del path, (error, response, body) =>
status = response.statusCode
if error or (status isnt 204 and status isnt 200)
error = error || new Error body.error
unless @silent then @_logErrorInConsole error
callback error
else
callback null, body
#---- FORMAT METHODS
formatBody: (body) ->
formattedBody = []
if body.rows? and body.rows.length > 0
for row in body.rows
formattedRow = {}
if row._id? then formattedRow['id'] = row._id
if row.docType? then formattedRow['key'] = row.docType
formattedRow['value'] = row
formattedBody.push formattedRow
return formattedBody
#---- VALIDATION METHODS
areValidDoctypes: (doctypes, callback = null) ->
@getDoctypes (error, registered) =>
errorMsg = null
areValid = true
bError = false
if error
errorMsg = @ERR_MSG.retrieveData
console.log error
bError = true
else
#compare given doctype and existing doctype for security
for unregistered in doctypes
if not @ARRAY_HELPER.isInArray unregistered, registered
bError = true
errorMsg = @ERR_MSG.unknownDoctype
break
areValid = not bError
if callback? then callback areValid, errorMsg
#---- GET LOCALE
getLocale: (callback = null) ->
defaultLocale = 'en'
@getView @PATH.request + 'cozyinstance' + @PATH.all, (err, instances) ->
locale = instances?[0]?.value.locale or defaultLocale
callback null, locale
#********************************************************
module.exports = new DataSystem() | true | CoreClass = require './../helpers/CoreClass'
#********************************************************
#******************** CLASS DataSystem ******************
#********************************************************
#@description : used to communicate with the cozy data-system
class DataSystem extends CoreClass
#------------------ CONSTRUCTOR CONSTANTS ----------------
@CLASS_NAME: "DataSystem"
#------------------ PROTOTYPE CONSTANTS ----------------
#required dependencies
JSON_CLIENT: require('request-json').JsonClient
ASYNC: require 'async'
ARRAY_HELPER: require './../helpers/oArrayHelper'
#general pathes
DS_URL: "http://127.0.0.1"
DS_PORT: 9101
DI_PORT: 9102
#specific paths
PATH:
data: '/data/'
request: '/request/'
all: '/all/'
search: '/data/search/'
index: '/data/index/'
destroyAll : '/all/destroy/'
doctypes:
getall: '/doctypes'
getsums: '/request/doctypes/getsums/'
getallbyorigin : '/request/doctypes/getallbyorigin/'
metadoctype:
getallbyrelated: '/request/metadoctype/getallbyrelated/'
application:
getpermissions: '/request/application/getpermissions/'
#common error messages
ERR_MSG:
retrieveData : 'Error : Server error occurred while retrieving data.'
removeData : 'Error : Server error occurred while removing data.'
unknownDoctype : 'Error : You try to access to an unknown doctype.'
unknownParamaters : 'Error : Unknown research parameters'
unknownId : 'Error : Document ID parameter not found.'
#----------------- OBJECT PARAMETERS ---------------
constructor: ->
#------ SETTED
@clientDS = new @JSON_CLIENT @DS_URL + ':' + @DS_PORT
@registeredPatterns = {}
@isSilent = false
#------ SUB-PROCESS
#Authentification
if process.env.NODE_ENV is "production"
username = process.env.NAME
password = PI:PASSWORD:<PASSWORD>END_PI
@clientDS.setBasicAuth username, password
#-------------- OBJECT METHODS ----------------------
#---- PREPARATION METHODS
prepareDballRequests: (doctypes = []) ->
setupRequestsAll = []
#prepare parameters
for doctypeName, index in doctypes
#prepare request (as a closure)
((doctypeName)=>
setupRequestsAll.push (callback) =>
doctypeName = doctypeName.toLowerCase()
path = @PATH.request + doctypeName + @PATH.all
viewFunctions =
map: (doc) ->
if doc.docType?
if doc.docType.toLowerCase() is '__pattern__'
emit doc._id, doc
@manageRequest path, viewFunctions, callback, doctypeName
)(doctypeName)
return setupRequestsAll
#---- REQUEST METHODS
manageRequest: (path, viewFunctions, callback, pattern = '') ->
# convert map/reduce to string and replace optional pattern
for key, func of viewFunctions
funcAsString = func.toString()
if pattern isnt ''
viewFunctions[key] = funcAsString.replace '__pattern__', pattern
else
viewFunctions[key] = funcAsString
#create request
@clientDS.put path, viewFunctions, (error, response, body) =>
if error
unless @silent then @_logErrorInConsole error
callback error
else
if pattern isnt ''
@registeredPatterns[pattern] = true
callback null, body
getView: (path, callback, params = {}) ->
@postData path, callback, params
getDoctypes: (callback) ->
@getData @PATH.doctypes.getall, callback
getPermissions : (callback) ->
@getView @PATH.application.getpermissions, callback
getDoctypesByOrigin : (callback) ->
viewCallback = (error, body) ->
if error?
callback error
else
newArray = []
allObj = {}
for couple in body
if couple.key?
if allObj[couple.key[0]]?
allObj[couple.key[0]].push couple.key[1]
else
allObj[couple.key[0]] = []
allObj[couple.key[0]].push couple.key[1]
for objName, obj of allObj
newObj = {}
newObj['key'] = objName
newObj['value'] = obj
newArray.push newObj
callback null, newArray
@getView @PATH.doctypes.getallbyorigin, viewCallback, group: true
getDoctypesByApplication: (callback) ->
@getPermissions (error, applications) ->
if error?
callback error
else
doctypes = []
for app in applications
appName = app.key.toLowerCase()
doctypeName = []
for objName, obj of app.value
doctypeName.push objName.toLowerCase()
doctypes.push
'key' : appName
'value' : doctypeName
callback null, doctypes
indexId: (id, aFields, callback = null) ->
fields = {"fields": aFields}
@clientDS.post @PATH.index + id, fields, (error, response, body) =>
if error or response.statusCode isnt 200
error = error || new Error body.error
unless @silent then @_logErrorInConsole error
if callback? then callback error
else
if callback? then callback null, body
clearIndexer: (callback) ->
@deleteData '/data/index/clear-all/', callback
deleteById: (id, callback) ->
@deleteData @PATH.data + id + '/', callback
deleteAllByDoctype : (doctype, callback) ->
@putData @PATH.request + doctype + @PATH.destroyAll, {}, callback
#---- CRUD HTTTP METHODS
putData: (path, params, callback) ->
@clientDS.put path, params, (error, response, body) =>
if error
error = error
unless @silent then @_logErrorInConsole error
callback error
else
callback null, body
getData: (path, callback) ->
@clientDS.get path, (error, response, body) =>
if error or response.statusCode isnt 200
error = error || new Error body.error
unless @silent then @_logErrorInConsole error
callback error
else
callback null, body
postData: (path, callback, params = {}) ->
@clientDS.post path, params, (error, response, body) =>
if error or response.statusCode isnt 200
error = error || new Error body.error
unless @silent then @_logErrorInConsole error
callback error
else
if not body.length?
body = @formatBody body
callback null, body
deleteData: (path, callback) ->
@clientDS.del path, (error, response, body) =>
status = response.statusCode
if error or (status isnt 204 and status isnt 200)
error = error || new Error body.error
unless @silent then @_logErrorInConsole error
callback error
else
callback null, body
#---- FORMAT METHODS
formatBody: (body) ->
formattedBody = []
if body.rows? and body.rows.length > 0
for row in body.rows
formattedRow = {}
if row._id? then formattedRow['id'] = row._id
if row.docType? then formattedRow['key'] = row.docType
formattedRow['value'] = row
formattedBody.push formattedRow
return formattedBody
#---- VALIDATION METHODS
areValidDoctypes: (doctypes, callback = null) ->
@getDoctypes (error, registered) =>
errorMsg = null
areValid = true
bError = false
if error
errorMsg = @ERR_MSG.retrieveData
console.log error
bError = true
else
#compare given doctype and existing doctype for security
for unregistered in doctypes
if not @ARRAY_HELPER.isInArray unregistered, registered
bError = true
errorMsg = @ERR_MSG.unknownDoctype
break
areValid = not bError
if callback? then callback areValid, errorMsg
#---- GET LOCALE
getLocale: (callback = null) ->
defaultLocale = 'en'
@getView @PATH.request + 'cozyinstance' + @PATH.all, (err, instances) ->
locale = instances?[0]?.value.locale or defaultLocale
callback null, locale
#********************************************************
module.exports = new DataSystem() |
[
{
"context": "ue, I will append it to end\n #console.log(\"pridavam\")\n order_by_array.pop() if order_by_array.le",
"end": 1655,
"score": 0.6626817584037781,
"start": 1649,
"tag": "NAME",
"value": "idavam"
}
] | app/assets/javascripts/backbone_js/ladas_table_sorting.js.coffee | Ladas/application-backbone | 1 | class TableSorting
@max_together = 2
@change_sorting: (form_id, order_by_value, dir, obj) ->
order_by_value = order_by_value.toLowerCase()
dir = dir.toLowerCase()
order_by_id = '#' + form_id + '_order_by'
default_order_by_val = $('#' + form_id + '_default_order_by').val().toLowerCase()
order_by_array = $(order_by_id).val().toLowerCase().split(",")
#console.log(order_by_value)
#console.log(dir)
#console.log(order_by_array)
if (order_by_array.indexOf(order_by_value + " " + dir) >= 0)
# the value is already there, if I click on it again I want to cancel the sorting by element value
#console.log("mazu")
index = order_by_array.indexOf(order_by_value + " " + dir)
order_by_array.splice(index, 1)
if (order_by_array.length <= 0)
# the ordering is empty I will fill it with default
order_by_array.push(default_order_by_val)
#console.log(order_by_array)
else if ((dir == "desc" && order_by_array.indexOf(order_by_value + " asc") >= 0) || (dir == "asc" && order_by_array.indexOf(order_by_value + " desc") >= 0))
# there is other variant of the column desc or asc, I will swith it to the other variant
#console.log("menim dir")
if (dir == "desc")
index = order_by_array.indexOf(order_by_value + " asc")
order_by_array[index] = order_by_value + " desc"
else
index = order_by_array.indexOf(order_by_value + " desc")
order_by_array[index] = order_by_value + " asc"
#console.log(order_by_array)
else # i am not ordering by element value, I will append it to end
#console.log("pridavam")
order_by_array.pop() if order_by_array.length >= TableSorting.max_together
order_by_array.push(order_by_value + " " + dir)
$("#" + form_id + " .sort_button").each (index, element) =>
$(element).removeClass("btn-success")
#$(element).addClass("inactive") # give all disabled class
new_order_by_val = ""
for element in order_by_array
if (new_order_by_val != "")
new_order_by_val += ","
#console.log(element)
new_order_by_val += element
order_by_button_id = "#" + element.replace(" ", "___").replace(".", "___")
#console.log(order_by_button_id)
#$(order_by_button_id).removeClass("inactive")
$(order_by_button_id).addClass("btn-success")
#console.log(new_order_by_val)
$(order_by_id).val(new_order_by_val)
#$('#' + form_id).submit()
form_submit_watcher(form_id)
@force_change_sorting: (form_id, order_by_value, dir, obj) ->
order_by_value = order_by_value.toLowerCase()
dir = dir.toLowerCase()
order_by_id = '#' + form_id + '_order_by'
$("#" + form_id + " .sort_button").each (index, element) =>
$(element).removeClass("btn-success")
#$(element).addClass("inactive") # give all disabled class
element = order_by_value + " " + dir
order_by_button_id = "#" + element.replace(" ", "___").replace(".", "___")
#$(order_by_button_id).removeClass("inactive")
$(order_by_button_id).addClass("btn-success")
$(order_by_id).val(element)
#$('#' + form_id).submit()
form_submit_watcher(form_id)
@force_toggled_change_sorting: (form_id, order_by_value, obj) ->
order_by_value = order_by_value.toLowerCase()
parent_th = $(obj)
if parent_th.hasClass("sorted")
if parent_th.hasClass("sorted_asc")
dir = "desc"
else
dir = "asc"
else
dir = "asc"
order_by_id = '#' + form_id + '_order_by'
$("#" + form_id + " .sorting_th").each (index, element) =>
$(element).removeClass("sorted").removeClass("sorted_desc").removeClass("sorted_asc")
$(element).removeClass("sorted_desc_hover").removeClass("sorted_asc_hover")
element = order_by_value + " " + dir
order_by_button_class = "." + element.replace(" ", "___").replace(".", "___")
#$(order_by_button_id).removeClass("inactive")
$(order_by_button_class).addClass("sorted").addClass("sorted_" + dir)
;
$(order_by_id).val(element)
#$('#' + form_id).submit()
form_submit_watcher(form_id)
@mouse_over_hover_sorting: (form_id, order_by_value, obj) ->
order_by_value = order_by_value.toLowerCase()
parent_th = $(obj)
if parent_th.hasClass("sorted")
if parent_th.hasClass("sorted_asc")
dir = "desc"
else
dir = "asc"
else
dir = "asc"
order_by_id = '#' + form_id + '_order_by'
$("#" + form_id + " .sorting_th").each (index, element) =>
$(element).removeClass("sorted_desc_hover").removeClass("sorted_asc_hover")
element = order_by_value + " " + dir
order_by_button_class = "." + element.replace(" ", "___").replace(".", "___")
#$(order_by_button_id).removeClass("inactive")
$(order_by_button_class).addClass("sorted_" + dir + "_hover")
@mouse_out_hover_sorting: (form_id, order_by_value, obj) ->
order_by_value = order_by_value.toLowerCase()
parent_th = $(obj)
if parent_th.hasClass("sorted")
if parent_th.hasClass("sorted_asc")
dir = "desc"
else
dir = "asc"
else
dir = "asc"
order_by_id = '#' + form_id + '_order_by'
$("#" + form_id + " .sorting_th").each (index, element) =>
$(element).removeClass("sorted_desc_hover").removeClass("sorted_asc_hover")
window.TableSorting = TableSorting
| 200130 | class TableSorting
@max_together = 2
@change_sorting: (form_id, order_by_value, dir, obj) ->
order_by_value = order_by_value.toLowerCase()
dir = dir.toLowerCase()
order_by_id = '#' + form_id + '_order_by'
default_order_by_val = $('#' + form_id + '_default_order_by').val().toLowerCase()
order_by_array = $(order_by_id).val().toLowerCase().split(",")
#console.log(order_by_value)
#console.log(dir)
#console.log(order_by_array)
if (order_by_array.indexOf(order_by_value + " " + dir) >= 0)
# the value is already there, if I click on it again I want to cancel the sorting by element value
#console.log("mazu")
index = order_by_array.indexOf(order_by_value + " " + dir)
order_by_array.splice(index, 1)
if (order_by_array.length <= 0)
# the ordering is empty I will fill it with default
order_by_array.push(default_order_by_val)
#console.log(order_by_array)
else if ((dir == "desc" && order_by_array.indexOf(order_by_value + " asc") >= 0) || (dir == "asc" && order_by_array.indexOf(order_by_value + " desc") >= 0))
# there is other variant of the column desc or asc, I will swith it to the other variant
#console.log("menim dir")
if (dir == "desc")
index = order_by_array.indexOf(order_by_value + " asc")
order_by_array[index] = order_by_value + " desc"
else
index = order_by_array.indexOf(order_by_value + " desc")
order_by_array[index] = order_by_value + " asc"
#console.log(order_by_array)
else # i am not ordering by element value, I will append it to end
#console.log("pr<NAME>")
order_by_array.pop() if order_by_array.length >= TableSorting.max_together
order_by_array.push(order_by_value + " " + dir)
$("#" + form_id + " .sort_button").each (index, element) =>
$(element).removeClass("btn-success")
#$(element).addClass("inactive") # give all disabled class
new_order_by_val = ""
for element in order_by_array
if (new_order_by_val != "")
new_order_by_val += ","
#console.log(element)
new_order_by_val += element
order_by_button_id = "#" + element.replace(" ", "___").replace(".", "___")
#console.log(order_by_button_id)
#$(order_by_button_id).removeClass("inactive")
$(order_by_button_id).addClass("btn-success")
#console.log(new_order_by_val)
$(order_by_id).val(new_order_by_val)
#$('#' + form_id).submit()
form_submit_watcher(form_id)
@force_change_sorting: (form_id, order_by_value, dir, obj) ->
order_by_value = order_by_value.toLowerCase()
dir = dir.toLowerCase()
order_by_id = '#' + form_id + '_order_by'
$("#" + form_id + " .sort_button").each (index, element) =>
$(element).removeClass("btn-success")
#$(element).addClass("inactive") # give all disabled class
element = order_by_value + " " + dir
order_by_button_id = "#" + element.replace(" ", "___").replace(".", "___")
#$(order_by_button_id).removeClass("inactive")
$(order_by_button_id).addClass("btn-success")
$(order_by_id).val(element)
#$('#' + form_id).submit()
form_submit_watcher(form_id)
@force_toggled_change_sorting: (form_id, order_by_value, obj) ->
order_by_value = order_by_value.toLowerCase()
parent_th = $(obj)
if parent_th.hasClass("sorted")
if parent_th.hasClass("sorted_asc")
dir = "desc"
else
dir = "asc"
else
dir = "asc"
order_by_id = '#' + form_id + '_order_by'
$("#" + form_id + " .sorting_th").each (index, element) =>
$(element).removeClass("sorted").removeClass("sorted_desc").removeClass("sorted_asc")
$(element).removeClass("sorted_desc_hover").removeClass("sorted_asc_hover")
element = order_by_value + " " + dir
order_by_button_class = "." + element.replace(" ", "___").replace(".", "___")
#$(order_by_button_id).removeClass("inactive")
$(order_by_button_class).addClass("sorted").addClass("sorted_" + dir)
;
$(order_by_id).val(element)
#$('#' + form_id).submit()
form_submit_watcher(form_id)
@mouse_over_hover_sorting: (form_id, order_by_value, obj) ->
order_by_value = order_by_value.toLowerCase()
parent_th = $(obj)
if parent_th.hasClass("sorted")
if parent_th.hasClass("sorted_asc")
dir = "desc"
else
dir = "asc"
else
dir = "asc"
order_by_id = '#' + form_id + '_order_by'
$("#" + form_id + " .sorting_th").each (index, element) =>
$(element).removeClass("sorted_desc_hover").removeClass("sorted_asc_hover")
element = order_by_value + " " + dir
order_by_button_class = "." + element.replace(" ", "___").replace(".", "___")
#$(order_by_button_id).removeClass("inactive")
$(order_by_button_class).addClass("sorted_" + dir + "_hover")
@mouse_out_hover_sorting: (form_id, order_by_value, obj) ->
order_by_value = order_by_value.toLowerCase()
parent_th = $(obj)
if parent_th.hasClass("sorted")
if parent_th.hasClass("sorted_asc")
dir = "desc"
else
dir = "asc"
else
dir = "asc"
order_by_id = '#' + form_id + '_order_by'
$("#" + form_id + " .sorting_th").each (index, element) =>
$(element).removeClass("sorted_desc_hover").removeClass("sorted_asc_hover")
window.TableSorting = TableSorting
| true | class TableSorting
@max_together = 2
@change_sorting: (form_id, order_by_value, dir, obj) ->
order_by_value = order_by_value.toLowerCase()
dir = dir.toLowerCase()
order_by_id = '#' + form_id + '_order_by'
default_order_by_val = $('#' + form_id + '_default_order_by').val().toLowerCase()
order_by_array = $(order_by_id).val().toLowerCase().split(",")
#console.log(order_by_value)
#console.log(dir)
#console.log(order_by_array)
if (order_by_array.indexOf(order_by_value + " " + dir) >= 0)
# the value is already there, if I click on it again I want to cancel the sorting by element value
#console.log("mazu")
index = order_by_array.indexOf(order_by_value + " " + dir)
order_by_array.splice(index, 1)
if (order_by_array.length <= 0)
# the ordering is empty I will fill it with default
order_by_array.push(default_order_by_val)
#console.log(order_by_array)
else if ((dir == "desc" && order_by_array.indexOf(order_by_value + " asc") >= 0) || (dir == "asc" && order_by_array.indexOf(order_by_value + " desc") >= 0))
# there is other variant of the column desc or asc, I will swith it to the other variant
#console.log("menim dir")
if (dir == "desc")
index = order_by_array.indexOf(order_by_value + " asc")
order_by_array[index] = order_by_value + " desc"
else
index = order_by_array.indexOf(order_by_value + " desc")
order_by_array[index] = order_by_value + " asc"
#console.log(order_by_array)
else # i am not ordering by element value, I will append it to end
#console.log("prPI:NAME:<NAME>END_PI")
order_by_array.pop() if order_by_array.length >= TableSorting.max_together
order_by_array.push(order_by_value + " " + dir)
$("#" + form_id + " .sort_button").each (index, element) =>
$(element).removeClass("btn-success")
#$(element).addClass("inactive") # give all disabled class
new_order_by_val = ""
for element in order_by_array
if (new_order_by_val != "")
new_order_by_val += ","
#console.log(element)
new_order_by_val += element
order_by_button_id = "#" + element.replace(" ", "___").replace(".", "___")
#console.log(order_by_button_id)
#$(order_by_button_id).removeClass("inactive")
$(order_by_button_id).addClass("btn-success")
#console.log(new_order_by_val)
$(order_by_id).val(new_order_by_val)
#$('#' + form_id).submit()
form_submit_watcher(form_id)
@force_change_sorting: (form_id, order_by_value, dir, obj) ->
order_by_value = order_by_value.toLowerCase()
dir = dir.toLowerCase()
order_by_id = '#' + form_id + '_order_by'
$("#" + form_id + " .sort_button").each (index, element) =>
$(element).removeClass("btn-success")
#$(element).addClass("inactive") # give all disabled class
element = order_by_value + " " + dir
order_by_button_id = "#" + element.replace(" ", "___").replace(".", "___")
#$(order_by_button_id).removeClass("inactive")
$(order_by_button_id).addClass("btn-success")
$(order_by_id).val(element)
#$('#' + form_id).submit()
form_submit_watcher(form_id)
@force_toggled_change_sorting: (form_id, order_by_value, obj) ->
order_by_value = order_by_value.toLowerCase()
parent_th = $(obj)
if parent_th.hasClass("sorted")
if parent_th.hasClass("sorted_asc")
dir = "desc"
else
dir = "asc"
else
dir = "asc"
order_by_id = '#' + form_id + '_order_by'
$("#" + form_id + " .sorting_th").each (index, element) =>
$(element).removeClass("sorted").removeClass("sorted_desc").removeClass("sorted_asc")
$(element).removeClass("sorted_desc_hover").removeClass("sorted_asc_hover")
element = order_by_value + " " + dir
order_by_button_class = "." + element.replace(" ", "___").replace(".", "___")
#$(order_by_button_id).removeClass("inactive")
$(order_by_button_class).addClass("sorted").addClass("sorted_" + dir)
;
$(order_by_id).val(element)
#$('#' + form_id).submit()
form_submit_watcher(form_id)
@mouse_over_hover_sorting: (form_id, order_by_value, obj) ->
order_by_value = order_by_value.toLowerCase()
parent_th = $(obj)
if parent_th.hasClass("sorted")
if parent_th.hasClass("sorted_asc")
dir = "desc"
else
dir = "asc"
else
dir = "asc"
order_by_id = '#' + form_id + '_order_by'
$("#" + form_id + " .sorting_th").each (index, element) =>
$(element).removeClass("sorted_desc_hover").removeClass("sorted_asc_hover")
element = order_by_value + " " + dir
order_by_button_class = "." + element.replace(" ", "___").replace(".", "___")
#$(order_by_button_id).removeClass("inactive")
$(order_by_button_class).addClass("sorted_" + dir + "_hover")
@mouse_out_hover_sorting: (form_id, order_by_value, obj) ->
order_by_value = order_by_value.toLowerCase()
parent_th = $(obj)
if parent_th.hasClass("sorted")
if parent_th.hasClass("sorted_asc")
dir = "desc"
else
dir = "asc"
else
dir = "asc"
order_by_id = '#' + form_id + '_order_by'
$("#" + form_id + " .sorting_th").each (index, element) =>
$(element).removeClass("sorted_desc_hover").removeClass("sorted_asc_hover")
window.TableSorting = TableSorting
|
[
{
"context": "'#contact_form')\n#\n# contact_form_dv.run()\n#\n# Wael Nasreddine <wael.nasreddine@gmail.com>\nwindow.FormDefaultVal",
"end": 263,
"score": 0.9998992085456848,
"start": 248,
"tag": "NAME",
"value": "Wael Nasreddine"
},
{
"context": "\n# contact_form_dv.run()\n#... | lib/assets/javascripts/form_default_values/main.js.coffee | TechnoGate/contao_template | 0 | # This class provides some helpfull methods to hide the default text
# on view and show the text on blue if it is equal to the default text
#
# Usage:
# contact_form_dv = new FormDefaultValues('#contact_form')
#
# contact_form_dv.run()
#
# Wael Nasreddine <wael.nasreddine@gmail.com>
window.FormDefaultValues = class FormDefaultValues
# Constructor
# @param [String] The dom of the parent node of all inputs and text areas
constructor: (@domId) ->
@default_values = {}
# Run binds some methods to watch the inputs of type text
# and textareas
run: ->
($ @domId).find('input[type="text"], textarea').each (i, el) =>
@watch_element(el)
# Watch element
#
# @param [String] The element
watch_element: (el) =>
name = ($ el).attr('name')
# Find the default value either as the inputs val or a label
default_value = ($ el).val()
unless default_value
id = ($ el).attr('id')
default_value = ($ el).parentsUntil('form').parent().find("label[for='#{id}']").html()
# Set the initial value of the input
($ el).val(default_value)
# Store the default value in a instance variable
@default_values[name] = default_value
# Bind the focus event
($ el).focus =>
if ($ el).val() == @default_values[name]
($ el).val('')
# Bind the blur event
($ el).blur =>
if ($ el).val() == ''
($ el).val(@default_values[name])
| 37733 | # This class provides some helpfull methods to hide the default text
# on view and show the text on blue if it is equal to the default text
#
# Usage:
# contact_form_dv = new FormDefaultValues('#contact_form')
#
# contact_form_dv.run()
#
# <NAME> <<EMAIL>>
window.FormDefaultValues = class FormDefaultValues
# Constructor
# @param [String] The dom of the parent node of all inputs and text areas
constructor: (@domId) ->
@default_values = {}
# Run binds some methods to watch the inputs of type text
# and textareas
run: ->
($ @domId).find('input[type="text"], textarea').each (i, el) =>
@watch_element(el)
# Watch element
#
# @param [String] The element
watch_element: (el) =>
name = ($ el).attr('name')
# Find the default value either as the inputs val or a label
default_value = ($ el).val()
unless default_value
id = ($ el).attr('id')
default_value = ($ el).parentsUntil('form').parent().find("label[for='#{id}']").html()
# Set the initial value of the input
($ el).val(default_value)
# Store the default value in a instance variable
@default_values[name] = default_value
# Bind the focus event
($ el).focus =>
if ($ el).val() == @default_values[name]
($ el).val('')
# Bind the blur event
($ el).blur =>
if ($ el).val() == ''
($ el).val(@default_values[name])
| true | # This class provides some helpfull methods to hide the default text
# on view and show the text on blue if it is equal to the default text
#
# Usage:
# contact_form_dv = new FormDefaultValues('#contact_form')
#
# contact_form_dv.run()
#
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
window.FormDefaultValues = class FormDefaultValues
# Constructor
# @param [String] The dom of the parent node of all inputs and text areas
constructor: (@domId) ->
@default_values = {}
# Run binds some methods to watch the inputs of type text
# and textareas
run: ->
($ @domId).find('input[type="text"], textarea').each (i, el) =>
@watch_element(el)
# Watch element
#
# @param [String] The element
watch_element: (el) =>
name = ($ el).attr('name')
# Find the default value either as the inputs val or a label
default_value = ($ el).val()
unless default_value
id = ($ el).attr('id')
default_value = ($ el).parentsUntil('form').parent().find("label[for='#{id}']").html()
# Set the initial value of the input
($ el).val(default_value)
# Store the default value in a instance variable
@default_values[name] = default_value
# Bind the focus event
($ el).focus =>
if ($ el).val() == @default_values[name]
($ el).val('')
# Bind the blur event
($ el).blur =>
if ($ el).val() == ''
($ el).val(@default_values[name])
|
[
{
"context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistri",
"end": 42,
"score": 0.9998412132263184,
"start": 24,
"tag": "NAME",
"value": "Alexander Cherniuk"
},
{
"context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmai... | library/gearbox/application.coffee | ts33kr/granite | 6 | ###
Copyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
assert = require "assert"
{Pinpoint} = require "../gearbox/pinpoint"
{Exchange} = require "../gearbox/exchange"
{Policies} = require "../gearbox/policies"
{Navigate} = require "../gearbox/navigate"
{GrandCentral} = require "../gearbox/central"
{Localized} = require "../shipped/localized"
{Bilateral} = require "../membrane/bilateral"
{Auxiliaries} = require "../membrane/auxes"
{Preflight} = require "../membrane/preflight"
# This abstract compound is designed to be the starting point in a
# clearly disambigued tree of inheritance for the application and
# the framework services. This particular abstraction is marking
# an application, which is one of entrypoints within the concept
# of `Single Page Applications`. This component encompases all
# of the functionality need for providing a good `root` service.
module.exports.Application = class Application extends Preflight
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# These declarations below are implantations of the abstracted
# components by the means of the dynamic recomposition system.
# Please take a look at the `Composition` class implementation
# for all sorts of information on the composition system itself.
# Each of these will be dynamicall integrated in class hierarchy.
# P.S. These are the secondary essentials for every active comp.
@implanting Localized, Pinpoint, Exchange, GrandCentral
# These declarations below are implantations of the abstracted
# components by the means of the dynamic recomposition system.
# Please take a look at the `Composition` class implementation
# for all sorts of information on the composition system itself.
# Each of these will be dynamicall integrated in class hierarchy.
# P.S. These are the core definitions for every active component.
@implanting Auxiliaries, Bilateral, Policies, Navigate
# This method is synchronized over the `attached` event of the
# kernel that gets fired once some component has been booted.
# Method monitors all the attachment events, and every time it
# checks if all the components has been booted. Once it so, it
# broadcasts `completed` event via the root. The event will be
# repeated after connection restoring, however a special event
# `completed-once` is guaranteed to be fired one time only.
waitCompletion: @synchronize "attached", (service) ->
broken = "could not find essential functions"
signature = "got an incorrect event signature"
ecosystem = "can not detect current ecosystem"
m = "Booting sequence has been completed at %s"
assert _.isObject(service or null), signature
assert _.isArray(@ecosystem or no), ecosystem
assert _.isFunction(@broadcast or no), broken
isDup = (service) -> _.isString service.duplex
isCom = (service) -> try service.setInOrder?()
duplexed = _.filter @ecosystem or [], isDup
completed = _.every @ecosystem or [], isCom
return unless completed # boot not finished
@broadcast "completed" # notify of completed
@broadcast "completed-once" unless @$complete
assert identify = this.constructor.identify()
logger.debug m.green, identify.green.bold
this.$complete = yes # was completed once
| 36617 | ###
Copyright (c) 2013, <NAME> <<EMAIL>>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
assert = require "assert"
{Pinpoint} = require "../gearbox/pinpoint"
{Exchange} = require "../gearbox/exchange"
{Policies} = require "../gearbox/policies"
{Navigate} = require "../gearbox/navigate"
{GrandCentral} = require "../gearbox/central"
{Localized} = require "../shipped/localized"
{Bilateral} = require "../membrane/bilateral"
{Auxiliaries} = require "../membrane/auxes"
{Preflight} = require "../membrane/preflight"
# This abstract compound is designed to be the starting point in a
# clearly disambigued tree of inheritance for the application and
# the framework services. This particular abstraction is marking
# an application, which is one of entrypoints within the concept
# of `Single Page Applications`. This component encompases all
# of the functionality need for providing a good `root` service.
module.exports.Application = class Application extends Preflight
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# These declarations below are implantations of the abstracted
# components by the means of the dynamic recomposition system.
# Please take a look at the `Composition` class implementation
# for all sorts of information on the composition system itself.
# Each of these will be dynamicall integrated in class hierarchy.
# P.S. These are the secondary essentials for every active comp.
@implanting Localized, Pinpoint, Exchange, GrandCentral
# These declarations below are implantations of the abstracted
# components by the means of the dynamic recomposition system.
# Please take a look at the `Composition` class implementation
# for all sorts of information on the composition system itself.
# Each of these will be dynamicall integrated in class hierarchy.
# P.S. These are the core definitions for every active component.
@implanting Auxiliaries, Bilateral, Policies, Navigate
# This method is synchronized over the `attached` event of the
# kernel that gets fired once some component has been booted.
# Method monitors all the attachment events, and every time it
# checks if all the components has been booted. Once it so, it
# broadcasts `completed` event via the root. The event will be
# repeated after connection restoring, however a special event
# `completed-once` is guaranteed to be fired one time only.
waitCompletion: @synchronize "attached", (service) ->
broken = "could not find essential functions"
signature = "got an incorrect event signature"
ecosystem = "can not detect current ecosystem"
m = "Booting sequence has been completed at %s"
assert _.isObject(service or null), signature
assert _.isArray(@ecosystem or no), ecosystem
assert _.isFunction(@broadcast or no), broken
isDup = (service) -> _.isString service.duplex
isCom = (service) -> try service.setInOrder?()
duplexed = _.filter @ecosystem or [], isDup
completed = _.every @ecosystem or [], isCom
return unless completed # boot not finished
@broadcast "completed" # notify of completed
@broadcast "completed-once" unless @$complete
assert identify = this.constructor.identify()
logger.debug m.green, identify.green.bold
this.$complete = yes # was completed once
| true | ###
Copyright (c) 2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
assert = require "assert"
{Pinpoint} = require "../gearbox/pinpoint"
{Exchange} = require "../gearbox/exchange"
{Policies} = require "../gearbox/policies"
{Navigate} = require "../gearbox/navigate"
{GrandCentral} = require "../gearbox/central"
{Localized} = require "../shipped/localized"
{Bilateral} = require "../membrane/bilateral"
{Auxiliaries} = require "../membrane/auxes"
{Preflight} = require "../membrane/preflight"
# This abstract compound is designed to be the starting point in a
# clearly disambigued tree of inheritance for the application and
# the framework services. This particular abstraction is marking
# an application, which is one of entrypoints within the concept
# of `Single Page Applications`. This component encompases all
# of the functionality need for providing a good `root` service.
module.exports.Application = class Application extends Preflight
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# These declarations below are implantations of the abstracted
# components by the means of the dynamic recomposition system.
# Please take a look at the `Composition` class implementation
# for all sorts of information on the composition system itself.
# Each of these will be dynamicall integrated in class hierarchy.
# P.S. These are the secondary essentials for every active comp.
@implanting Localized, Pinpoint, Exchange, GrandCentral
# These declarations below are implantations of the abstracted
# components by the means of the dynamic recomposition system.
# Please take a look at the `Composition` class implementation
# for all sorts of information on the composition system itself.
# Each of these will be dynamicall integrated in class hierarchy.
# P.S. These are the core definitions for every active component.
@implanting Auxiliaries, Bilateral, Policies, Navigate
# This method is synchronized over the `attached` event of the
# kernel that gets fired once some component has been booted.
# Method monitors all the attachment events, and every time it
# checks if all the components has been booted. Once it so, it
# broadcasts `completed` event via the root. The event will be
# repeated after connection restoring, however a special event
# `completed-once` is guaranteed to be fired one time only.
waitCompletion: @synchronize "attached", (service) ->
broken = "could not find essential functions"
signature = "got an incorrect event signature"
ecosystem = "can not detect current ecosystem"
m = "Booting sequence has been completed at %s"
assert _.isObject(service or null), signature
assert _.isArray(@ecosystem or no), ecosystem
assert _.isFunction(@broadcast or no), broken
isDup = (service) -> _.isString service.duplex
isCom = (service) -> try service.setInOrder?()
duplexed = _.filter @ecosystem or [], isDup
completed = _.every @ecosystem or [], isCom
return unless completed # boot not finished
@broadcast "completed" # notify of completed
@broadcast "completed-once" unless @$complete
assert identify = this.constructor.identify()
logger.debug m.green, identify.green.bold
this.$complete = yes # was completed once
|
[
{
"context": "oGLib\n# Module | Stat Methods\n# Author | Sherif Emabrak\n# Description | The boundary method partitions th",
"end": 163,
"score": 0.9998717308044434,
"start": 149,
"tag": "NAME",
"value": "Sherif Emabrak"
}
] | src/lib/statistics/bin/boundry.coffee | Sherif-Embarak/gp-test | 0 | # ------------------------------------------------------------------------------
# Project | GoGLib
# Module | Stat Methods
# Author | Sherif Emabrak
# Description | The boundary method partitions the plane with irregular polygons that are
# usually derived from geographic boundary or shape files.
# ------------------------------------------------------------------------------
boundry = () -> | 151536 | # ------------------------------------------------------------------------------
# Project | GoGLib
# Module | Stat Methods
# Author | <NAME>
# Description | The boundary method partitions the plane with irregular polygons that are
# usually derived from geographic boundary or shape files.
# ------------------------------------------------------------------------------
boundry = () -> | true | # ------------------------------------------------------------------------------
# Project | GoGLib
# Module | Stat Methods
# Author | PI:NAME:<NAME>END_PI
# Description | The boundary method partitions the plane with irregular polygons that are
# usually derived from geographic boundary or shape files.
# ------------------------------------------------------------------------------
boundry = () -> |
[
{
"context": "tkey: \"threshold-\"\n endkey: \"threshold-\\ufff0\"\n .then (result) ->\n docsToDelete = for r",
"end": 240,
"score": 0.6095776557922363,
"start": 238,
"tag": "KEY",
"value": "f0"
}
] | _attachments/app/models/Issues.coffee | jongoz/coconut-analytice | 3 | _ = require 'underscore'
$ = require 'jquery'
moment = require 'moment'
Reports = require './Reports'
class Issues
@resetEpidemicThreshold = =>
Coconut.database.allDocs
startkey: "threshold-"
endkey: "threshold-\ufff0"
.then (result) ->
docsToDelete = for row in result.rows
_id: row.id
_rev: row.value.rev
_deleted: true
console.log "Resetting epidemic thresholds: Removing #{docsToDelete.length} thresholds."
Coconut.database.bulkDocs docsToDelete
.catch (error) -> console.error error
@updateEpidemicAlertsAndAlarmsForLastXDaysShowResult = (days) =>
@updateEpidemicAlertsAndAlarmsForLastXDays days,
success: (result) ->
$("body").html result
@updateEpidemicAlertsAndAlarmsForLastXDays = (days, options) =>
new Promise (resolve, reject) =>
allResults = {}
for daysAgo in [days..0]
console.log "Days remaining to check: #{daysAgo}"
endDate = moment().subtract(daysAgo, 'days').format("YYYY-MM-DD")
_(allResults).extend (await Issues.updateEpidemicAlertsAndAlarms
save: if options?.save? then options.save else true
endDate: endDate
.catch (error) -> console.error error
)
resolve(allResults)
@updateEpidemicAlertsAndAlarms = (options) =>
new Promise (resolve, reject) ->
endDate = options?.endDate or moment().subtract(2,'days').format("YYYY-MM-DD")
thresholds = (await Coconut.reportingDatabase.get "epidemic_thresholds"
.catch =>
console.log "Thresholds missing, so creating it in the database"
thresholds = {
"_id": "epidemic_thresholds"
"data":
"7-days": [
{
type: "Alert"
aggregationArea: "facility"
indicator: "Has Notification"
threshold: 10
}
{
type: "Alert"
aggregationArea: "shehia"
indicator: "Number Positive Individuals Under 5"
threshold: 5
}
{
type: "Alert"
aggregationArea: "shehia"
indicator: "Number Positive Individuals"
threshold: 10
}
]
"14-days": [
{
type: "Alarm"
aggregationArea: "facility"
indicator: "Has Notification"
threshold: 20
}
{
type: "Alarm"
aggregationArea: "shehia"
indicator: "Number Positive Individuals Under 5"
threshold: 10
}
{
type: "Alarm"
aggregationArea: "shehia"
indicator: "Number Positive Individuals"
threshold: 20
}
]
}
await Coconut.reportingDatabase.put thresholds
Promise.resolve thresholds
).data
docsToSave = {}
for range, thresholdsForRange of thresholds
[amountOfTime,timeUnit] = range.split(/-/)
startDate = moment(endDate).subtract(amountOfTime,timeUnit).format("YYYY-MM-DD")
yearAndIsoWeekOfEndDate = moment(endDate).format("GGGG-WW")
console.log "#{startDate} - #{endDate}"
aggregatedResults = await Reports.positiveCasesAggregated
thresholds: thresholdsForRange
startDate: startDate
endDate: endDate
.catch (error) ->
console.error "ERROR"
console.error error
for aggregationAreaType, r1 of aggregatedResults
for aggregationArea, r2 of r1
for indicator, r3 of r2
if r3.length > 9
console.log "#{aggregationAreaType} #{aggregationArea} #{indicator} #{r3.length}"
for threshold in thresholdsForRange
aggregationArea = threshold.aggregationArea
for locationName, indicatorData of aggregatedResults[aggregationArea]
# console.log "#{indicatorData[threshold.indicator]?.length} > #{threshold.threshold}"
if indicatorData[threshold.indicator]?.length > threshold.threshold
id = "threshold-#{yearAndIsoWeekOfEndDate}-#{threshold.type}-#{range}-#{aggregationArea}-#{threshold.indicator}.#{locationName}"
console.log id
#id = "threshold-#{startDate}--#{endDate}-#{threshold.type}-#{range}-#{aggregationArea}-#{threshold.indicator}.#{locationName}"
docsToSave[id] =
_id: id
Range: range
LocationType: aggregationArea
ThresholdName: threshold.indicator
ThresholdType: threshold.type
LocationName: locationName
District: indicatorData[threshold.indicator][0].district
StartDate: startDate
EndDate: endDate
YearWeekEndDate: yearAndIsoWeekOfEndDate
Amount: indicatorData[threshold.indicator].length
Threshold: threshold.threshold
"Threshold Description": "#{threshold.type}: #{aggregationArea} with #{threshold.threshold} or more '#{threshold.indicator}' within #{range}"
Description: "#{aggregationArea}: #{locationName}, Cases: #{indicatorData[threshold.indicator].length}, Period: #{startDate} - #{endDate}"
Links: _(indicatorData[threshold.indicator]).pluck "link"
"Date Created": moment().format("YYYY-MM-DD HH:mm:ss")
AdditionalIncidents: []
docsToSave[id][aggregationArea] = locationName
# In case of alarm, then remove the alert that was also created
for id, docToSave of docsToSave
#console.log id
if docToSave.ThresholdType is "Alarm"
#console.log "Removing #{id.replace(/Alarm/, "Alert")} since we also crossed alarm threshold"
delete docsToSave[docToSave._id.replace(/Alarm/,"Alert")]
existingThresholdForSameWeek = await Coconut.database.get docToSave._id
.catch (error) => # Threshold doesn't exist, so don't do anything
if existingThresholdForSameWeek # don't save the new one
# Add additional information
existingThresholdForSameWeek.AdditionalIncidents.push
StartDate: docsToSave[docToSave._id].StartDate
EndDate: docsToSave[docToSave._id].EndDate
Amount: docsToSave[docToSave._id].Amount
Links: docsToSave[docToSave._id].Links
docsToSave[docToSave._id] = existingThresholdForSameWeek
###
# Note that this is inside the thresholds loop so that we have the right amountOfTime and timeUnit
Coconut.database.allDocs
startkey: "threshold-#{moment(startDate).subtract(2*amountOfTime,timeUnit).format("GGGG-WW")}"
endkey: "threshold-#{yearAndIsoWeekOfEndDate}"
.then (result) ->
_(docsToSave).each (docToSave) ->
#console.debug "Checking for existing thresholds that match #{docToSave._id}"
if (_(result.rows).some (existingThreshold) ->
# If after removing the date, the ids match, then it's a duplicate
existingThresholdIdNoDates = existingThreshold.id.replace(/\d\d\d\d-\d\d-\d\d/g,"")
docToSaveIdNoDates = docToSave._id.replace(/\d\d\d\d-\d\d-\d\d/g,"")
return true if existingThresholdIdNoDates is docToSaveIdNoDates
# If an alarm has already been created, don't also create an Alert
if docToSave.ThresholdType is "Alert"
return true if existingThresholdIdNoDates.replace(/Alarm/,"") is docToSaveIdNoDates.replace(/Alert/,"")
return false
)
delete docsToSave[docToSave._id]
Promise.resolve()
.catch (error) -> console.error error
###
unless options.save
#console.log "RESULT:"
#console.log JSON.stringify docsToSave, null, 1
#console.log "Not saving."
return resolve(docsToSave)
await Coconut.database.bulkDocs _(docsToSave).values()
.catch (error) -> console.error error
resolve(docsToSave)
module.exports = Issues
| 15571 | _ = require 'underscore'
$ = require 'jquery'
moment = require 'moment'
Reports = require './Reports'
class Issues
@resetEpidemicThreshold = =>
Coconut.database.allDocs
startkey: "threshold-"
endkey: "threshold-\uff<KEY>"
.then (result) ->
docsToDelete = for row in result.rows
_id: row.id
_rev: row.value.rev
_deleted: true
console.log "Resetting epidemic thresholds: Removing #{docsToDelete.length} thresholds."
Coconut.database.bulkDocs docsToDelete
.catch (error) -> console.error error
@updateEpidemicAlertsAndAlarmsForLastXDaysShowResult = (days) =>
@updateEpidemicAlertsAndAlarmsForLastXDays days,
success: (result) ->
$("body").html result
@updateEpidemicAlertsAndAlarmsForLastXDays = (days, options) =>
new Promise (resolve, reject) =>
allResults = {}
for daysAgo in [days..0]
console.log "Days remaining to check: #{daysAgo}"
endDate = moment().subtract(daysAgo, 'days').format("YYYY-MM-DD")
_(allResults).extend (await Issues.updateEpidemicAlertsAndAlarms
save: if options?.save? then options.save else true
endDate: endDate
.catch (error) -> console.error error
)
resolve(allResults)
@updateEpidemicAlertsAndAlarms = (options) =>
new Promise (resolve, reject) ->
endDate = options?.endDate or moment().subtract(2,'days').format("YYYY-MM-DD")
thresholds = (await Coconut.reportingDatabase.get "epidemic_thresholds"
.catch =>
console.log "Thresholds missing, so creating it in the database"
thresholds = {
"_id": "epidemic_thresholds"
"data":
"7-days": [
{
type: "Alert"
aggregationArea: "facility"
indicator: "Has Notification"
threshold: 10
}
{
type: "Alert"
aggregationArea: "shehia"
indicator: "Number Positive Individuals Under 5"
threshold: 5
}
{
type: "Alert"
aggregationArea: "shehia"
indicator: "Number Positive Individuals"
threshold: 10
}
]
"14-days": [
{
type: "Alarm"
aggregationArea: "facility"
indicator: "Has Notification"
threshold: 20
}
{
type: "Alarm"
aggregationArea: "shehia"
indicator: "Number Positive Individuals Under 5"
threshold: 10
}
{
type: "Alarm"
aggregationArea: "shehia"
indicator: "Number Positive Individuals"
threshold: 20
}
]
}
await Coconut.reportingDatabase.put thresholds
Promise.resolve thresholds
).data
docsToSave = {}
for range, thresholdsForRange of thresholds
[amountOfTime,timeUnit] = range.split(/-/)
startDate = moment(endDate).subtract(amountOfTime,timeUnit).format("YYYY-MM-DD")
yearAndIsoWeekOfEndDate = moment(endDate).format("GGGG-WW")
console.log "#{startDate} - #{endDate}"
aggregatedResults = await Reports.positiveCasesAggregated
thresholds: thresholdsForRange
startDate: startDate
endDate: endDate
.catch (error) ->
console.error "ERROR"
console.error error
for aggregationAreaType, r1 of aggregatedResults
for aggregationArea, r2 of r1
for indicator, r3 of r2
if r3.length > 9
console.log "#{aggregationAreaType} #{aggregationArea} #{indicator} #{r3.length}"
for threshold in thresholdsForRange
aggregationArea = threshold.aggregationArea
for locationName, indicatorData of aggregatedResults[aggregationArea]
# console.log "#{indicatorData[threshold.indicator]?.length} > #{threshold.threshold}"
if indicatorData[threshold.indicator]?.length > threshold.threshold
id = "threshold-#{yearAndIsoWeekOfEndDate}-#{threshold.type}-#{range}-#{aggregationArea}-#{threshold.indicator}.#{locationName}"
console.log id
#id = "threshold-#{startDate}--#{endDate}-#{threshold.type}-#{range}-#{aggregationArea}-#{threshold.indicator}.#{locationName}"
docsToSave[id] =
_id: id
Range: range
LocationType: aggregationArea
ThresholdName: threshold.indicator
ThresholdType: threshold.type
LocationName: locationName
District: indicatorData[threshold.indicator][0].district
StartDate: startDate
EndDate: endDate
YearWeekEndDate: yearAndIsoWeekOfEndDate
Amount: indicatorData[threshold.indicator].length
Threshold: threshold.threshold
"Threshold Description": "#{threshold.type}: #{aggregationArea} with #{threshold.threshold} or more '#{threshold.indicator}' within #{range}"
Description: "#{aggregationArea}: #{locationName}, Cases: #{indicatorData[threshold.indicator].length}, Period: #{startDate} - #{endDate}"
Links: _(indicatorData[threshold.indicator]).pluck "link"
"Date Created": moment().format("YYYY-MM-DD HH:mm:ss")
AdditionalIncidents: []
docsToSave[id][aggregationArea] = locationName
# In case of alarm, then remove the alert that was also created
for id, docToSave of docsToSave
#console.log id
if docToSave.ThresholdType is "Alarm"
#console.log "Removing #{id.replace(/Alarm/, "Alert")} since we also crossed alarm threshold"
delete docsToSave[docToSave._id.replace(/Alarm/,"Alert")]
existingThresholdForSameWeek = await Coconut.database.get docToSave._id
.catch (error) => # Threshold doesn't exist, so don't do anything
if existingThresholdForSameWeek # don't save the new one
# Add additional information
existingThresholdForSameWeek.AdditionalIncidents.push
StartDate: docsToSave[docToSave._id].StartDate
EndDate: docsToSave[docToSave._id].EndDate
Amount: docsToSave[docToSave._id].Amount
Links: docsToSave[docToSave._id].Links
docsToSave[docToSave._id] = existingThresholdForSameWeek
###
# Note that this is inside the thresholds loop so that we have the right amountOfTime and timeUnit
Coconut.database.allDocs
startkey: "threshold-#{moment(startDate).subtract(2*amountOfTime,timeUnit).format("GGGG-WW")}"
endkey: "threshold-#{yearAndIsoWeekOfEndDate}"
.then (result) ->
_(docsToSave).each (docToSave) ->
#console.debug "Checking for existing thresholds that match #{docToSave._id}"
if (_(result.rows).some (existingThreshold) ->
# If after removing the date, the ids match, then it's a duplicate
existingThresholdIdNoDates = existingThreshold.id.replace(/\d\d\d\d-\d\d-\d\d/g,"")
docToSaveIdNoDates = docToSave._id.replace(/\d\d\d\d-\d\d-\d\d/g,"")
return true if existingThresholdIdNoDates is docToSaveIdNoDates
# If an alarm has already been created, don't also create an Alert
if docToSave.ThresholdType is "Alert"
return true if existingThresholdIdNoDates.replace(/Alarm/,"") is docToSaveIdNoDates.replace(/Alert/,"")
return false
)
delete docsToSave[docToSave._id]
Promise.resolve()
.catch (error) -> console.error error
###
unless options.save
#console.log "RESULT:"
#console.log JSON.stringify docsToSave, null, 1
#console.log "Not saving."
return resolve(docsToSave)
await Coconut.database.bulkDocs _(docsToSave).values()
.catch (error) -> console.error error
resolve(docsToSave)
module.exports = Issues
| true | _ = require 'underscore'
$ = require 'jquery'
moment = require 'moment'
Reports = require './Reports'
class Issues
@resetEpidemicThreshold = =>
Coconut.database.allDocs
startkey: "threshold-"
endkey: "threshold-\uffPI:KEY:<KEY>END_PI"
.then (result) ->
docsToDelete = for row in result.rows
_id: row.id
_rev: row.value.rev
_deleted: true
console.log "Resetting epidemic thresholds: Removing #{docsToDelete.length} thresholds."
Coconut.database.bulkDocs docsToDelete
.catch (error) -> console.error error
@updateEpidemicAlertsAndAlarmsForLastXDaysShowResult = (days) =>
@updateEpidemicAlertsAndAlarmsForLastXDays days,
success: (result) ->
$("body").html result
@updateEpidemicAlertsAndAlarmsForLastXDays = (days, options) =>
new Promise (resolve, reject) =>
allResults = {}
for daysAgo in [days..0]
console.log "Days remaining to check: #{daysAgo}"
endDate = moment().subtract(daysAgo, 'days').format("YYYY-MM-DD")
_(allResults).extend (await Issues.updateEpidemicAlertsAndAlarms
save: if options?.save? then options.save else true
endDate: endDate
.catch (error) -> console.error error
)
resolve(allResults)
@updateEpidemicAlertsAndAlarms = (options) =>
new Promise (resolve, reject) ->
endDate = options?.endDate or moment().subtract(2,'days').format("YYYY-MM-DD")
thresholds = (await Coconut.reportingDatabase.get "epidemic_thresholds"
.catch =>
console.log "Thresholds missing, so creating it in the database"
thresholds = {
"_id": "epidemic_thresholds"
"data":
"7-days": [
{
type: "Alert"
aggregationArea: "facility"
indicator: "Has Notification"
threshold: 10
}
{
type: "Alert"
aggregationArea: "shehia"
indicator: "Number Positive Individuals Under 5"
threshold: 5
}
{
type: "Alert"
aggregationArea: "shehia"
indicator: "Number Positive Individuals"
threshold: 10
}
]
"14-days": [
{
type: "Alarm"
aggregationArea: "facility"
indicator: "Has Notification"
threshold: 20
}
{
type: "Alarm"
aggregationArea: "shehia"
indicator: "Number Positive Individuals Under 5"
threshold: 10
}
{
type: "Alarm"
aggregationArea: "shehia"
indicator: "Number Positive Individuals"
threshold: 20
}
]
}
await Coconut.reportingDatabase.put thresholds
Promise.resolve thresholds
).data
docsToSave = {}
for range, thresholdsForRange of thresholds
[amountOfTime,timeUnit] = range.split(/-/)
startDate = moment(endDate).subtract(amountOfTime,timeUnit).format("YYYY-MM-DD")
yearAndIsoWeekOfEndDate = moment(endDate).format("GGGG-WW")
console.log "#{startDate} - #{endDate}"
aggregatedResults = await Reports.positiveCasesAggregated
thresholds: thresholdsForRange
startDate: startDate
endDate: endDate
.catch (error) ->
console.error "ERROR"
console.error error
for aggregationAreaType, r1 of aggregatedResults
for aggregationArea, r2 of r1
for indicator, r3 of r2
if r3.length > 9
console.log "#{aggregationAreaType} #{aggregationArea} #{indicator} #{r3.length}"
for threshold in thresholdsForRange
aggregationArea = threshold.aggregationArea
for locationName, indicatorData of aggregatedResults[aggregationArea]
# console.log "#{indicatorData[threshold.indicator]?.length} > #{threshold.threshold}"
if indicatorData[threshold.indicator]?.length > threshold.threshold
id = "threshold-#{yearAndIsoWeekOfEndDate}-#{threshold.type}-#{range}-#{aggregationArea}-#{threshold.indicator}.#{locationName}"
console.log id
#id = "threshold-#{startDate}--#{endDate}-#{threshold.type}-#{range}-#{aggregationArea}-#{threshold.indicator}.#{locationName}"
docsToSave[id] =
_id: id
Range: range
LocationType: aggregationArea
ThresholdName: threshold.indicator
ThresholdType: threshold.type
LocationName: locationName
District: indicatorData[threshold.indicator][0].district
StartDate: startDate
EndDate: endDate
YearWeekEndDate: yearAndIsoWeekOfEndDate
Amount: indicatorData[threshold.indicator].length
Threshold: threshold.threshold
"Threshold Description": "#{threshold.type}: #{aggregationArea} with #{threshold.threshold} or more '#{threshold.indicator}' within #{range}"
Description: "#{aggregationArea}: #{locationName}, Cases: #{indicatorData[threshold.indicator].length}, Period: #{startDate} - #{endDate}"
Links: _(indicatorData[threshold.indicator]).pluck "link"
"Date Created": moment().format("YYYY-MM-DD HH:mm:ss")
AdditionalIncidents: []
docsToSave[id][aggregationArea] = locationName
# In case of alarm, then remove the alert that was also created
for id, docToSave of docsToSave
#console.log id
if docToSave.ThresholdType is "Alarm"
#console.log "Removing #{id.replace(/Alarm/, "Alert")} since we also crossed alarm threshold"
delete docsToSave[docToSave._id.replace(/Alarm/,"Alert")]
existingThresholdForSameWeek = await Coconut.database.get docToSave._id
.catch (error) => # Threshold doesn't exist, so don't do anything
if existingThresholdForSameWeek # don't save the new one
# Add additional information
existingThresholdForSameWeek.AdditionalIncidents.push
StartDate: docsToSave[docToSave._id].StartDate
EndDate: docsToSave[docToSave._id].EndDate
Amount: docsToSave[docToSave._id].Amount
Links: docsToSave[docToSave._id].Links
docsToSave[docToSave._id] = existingThresholdForSameWeek
###
# Note that this is inside the thresholds loop so that we have the right amountOfTime and timeUnit
Coconut.database.allDocs
startkey: "threshold-#{moment(startDate).subtract(2*amountOfTime,timeUnit).format("GGGG-WW")}"
endkey: "threshold-#{yearAndIsoWeekOfEndDate}"
.then (result) ->
_(docsToSave).each (docToSave) ->
#console.debug "Checking for existing thresholds that match #{docToSave._id}"
if (_(result.rows).some (existingThreshold) ->
# If after removing the date, the ids match, then it's a duplicate
existingThresholdIdNoDates = existingThreshold.id.replace(/\d\d\d\d-\d\d-\d\d/g,"")
docToSaveIdNoDates = docToSave._id.replace(/\d\d\d\d-\d\d-\d\d/g,"")
return true if existingThresholdIdNoDates is docToSaveIdNoDates
# If an alarm has already been created, don't also create an Alert
if docToSave.ThresholdType is "Alert"
return true if existingThresholdIdNoDates.replace(/Alarm/,"") is docToSaveIdNoDates.replace(/Alert/,"")
return false
)
delete docsToSave[docToSave._id]
Promise.resolve()
.catch (error) -> console.error error
###
unless options.save
#console.log "RESULT:"
#console.log JSON.stringify docsToSave, null, 1
#console.log "Not saving."
return resolve(docsToSave)
await Coconut.database.bulkDocs _(docsToSave).values()
.catch (error) -> console.error error
resolve(docsToSave)
module.exports = Issues
|
[
{
"context": ">\n selfRoom = @room\n selfRoom.user.say('alice', '@hubot bcycle')\n setTimeout(() ->\n ",
"end": 1390,
"score": 0.9945741891860962,
"start": 1385,
"tag": "USERNAME",
"value": "alice"
},
{
"context": " expect(selfRoom.messages).to.eql [\n ... | test/bcycle-finder_test.coffee | stephenyeargin/hubot-bcycle-finder | 2 | Helper = require('hubot-test-helper')
chai = require 'chai'
nock = require 'nock'
expect = chai.expect
helper = new Helper('../src/bcycle-finder.coffee')
describe 'hubot-bcycle-finder', ->
beforeEach ->
nock.disableNetConnect()
nock('https://gbfs.bcycle.com')
.get('/bcycle_nashville/system_information.json')
.replyWithFile(200, __dirname + '/fixtures/system_information.json')
nock('https://gbfs.bcycle.com')
.get('/bcycle_nashville/system_pricing_plans.json')
.replyWithFile(200, __dirname + '/fixtures/system_pricing_plans.json')
nock('https://gbfs.bcycle.com')
.get('/bcycle_nashville/station_information.json')
.replyWithFile(200, __dirname + '/fixtures/station_information.json')
nock('https://gbfs.bcycle.com')
.get('/bcycle_nashville/station_status.json')
.replyWithFile(200, __dirname + '/fixtures/station_status.json')
afterEach ->
nock.cleanAll()
# hubot bcycle
context 'default stations tests', ->
beforeEach ->
process.env.BCYCLE_CITY = 'nashville'
process.env.BCYCLE_DEFAULT_STATIONS='2162,2165'
@room = helper.createRoom()
afterEach ->
@room.destroy()
delete process.env.BCYCLE_CITY
delete process.env.BCYCLE_DEFAULT_STATIONS
it 'returns the status of the default stations', (done) ->
selfRoom = @room
selfRoom.user.say('alice', '@hubot bcycle')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot bcycle']
['hubot', "#2162 - Commerce & 2nd Ave N\n> Active | Bikes: 12 | Docks: 3\n#2165 - Church St between 4th & 5th Ave N\n> Active | Bikes: 1 | Docks: 8"]
]
done()
catch err
done err
return
, 1000)
context 'regular tests', ->
beforeEach ->
process.env.BCYCLE_CITY = 'nashville'
@room = helper.createRoom()
afterEach ->
@room.destroy()
delete process.env.BCYCLE_CITY
it 'returns error message if no default stations set', (done) ->
selfRoom = @room
selfRoom.user.say('alice', '@hubot bcycle')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot bcycle']
['hubot', 'You do not have any BCYCLE_DEFAULT_STATIONS configured.']
['hubot', 'Use `hubot bcycle search <query>` to find stations.']
]
done()
catch err
done err
return
, 1000)
# hubot bcycle list
it 'gets a listing of stations in the city', (done) ->
selfRoom = @room
selfRoom.user.say('alice', '@hubot bcycle list')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot bcycle list']
['hubot', '#2162 - Commerce & 2nd Ave N']
['hubot', '#2165 - Church St between 4th & 5th Ave N']
['hubot', '#2166 - Public Square : 3rd Ave N & Union St']
['hubot', '#2168 - Cumberland Park']
['hubot', '#2169 - 6th Ave N & Union St']
['hubot', '#2170 - The Gulch : 11th Ave S & Pine St']
['hubot', '#2171 - Music Row Roundabout : 16th Ave S']
['hubot', '#2173 - 9th Ave S & Demonbreun St']
['hubot', '#2175 - Wedgewood Ave & 21st Ave S']
['hubot', '#2176 - 57 Peabody St']
['hubot', '#2177 - 5 Points East Nashville : S 11th St']
['hubot', '#2179 - Nashville Farmers\' Market']
['hubot', '#2180 - Germantown: 5th Ave & Monroe St']
['hubot', '#2181 - 3rd Ave S & Symphony Pl']
['hubot', '#2516 - 12th Ave S & Elmwood']
['hubot', '#2684 - Church St. and 20th Ave N']
['hubot', '#2973 - 2017 Belmont Blvd']
['hubot', '#2975 - Junior Gilliam Way & 5th Ave N']
['hubot', '#3456 - 40th Ave. N and Charlotte Ave.']
['hubot', '#3467 - Charlotte Ave and 46th Ave N']
['hubot', '#3568 - 200 21st Ave South']
['hubot', '#3613 - 715 Porter Road']
]
done()
catch err
done err
return
, 1000)
# hubot bcycle me <station id>
it 'returns the status for a given station', (done) ->
selfRoom = @room
selfRoom.user.say('alice', '@hubot bcycle me 2162')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot bcycle me 2162']
['hubot', '#2162 - Commerce & 2nd Ave N\n> Active | Bikes: 12 | Docks: 3']
]
done()
catch err
done err
return
, 1000)
# hubot bcycle search <query>
it 'searches the listing of stations', (done) ->
selfRoom = @room
selfRoom.user.say('alice', '@hubot bcycle search church st')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot bcycle search church st']
['hubot', '#2165 - Church St between 4th & 5th Ave N']
['hubot', '#2684 - Church St. and 20th Ave N']
]
done()
catch err
done err
return
, 1000)
# hubot bcycle info
it 'returns information about your program', (done) ->
selfRoom = @room
selfRoom.user.say('alice', '@hubot bcycle info')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot bcycle info']
['hubot', 'Nashville BCycle | https://nashville.bcycle.com | 844-982-4533 | Nashville@bcycle.com']
]
done()
catch err
done err
return
, 1000)
# hubot bcycle price
it 'returns pricing plan information', (done) ->
selfRoom = @room
selfRoom.user.say('alice', '@hubot bcycle price')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot bcycle price']
['hubot', "Single Ride Pass Online ($5) - $5 per 30 minutes. Total minutes calculated and billed the following day.\nGuest Pass ($25) - Unlimited 120-minute rides in a 3-Day period. Additional rental fee of $3 per 30 minutes for rides longer than 120 minutes.\nMonthly Pass ($20) - Enjoy unlimited 60-minute rides for 30 days! Rides longer than 60 minutes are subject to a usage fee of $3 per additional 30 minutes.\nAnnual Pass ($120) - Enjoy unlimited 120-minute rides for a year! *Limited time offer of 120-minutes.* Rides longer than 120 minutes are subject to a usage fee of $3 per additional 30 minutes.\nSingle Ride Pass ($5) - $5 per 30 minutes. Total minutes calculated and billed the following day."]
]
done()
catch err
done err
return
, 1000)
| 57272 | Helper = require('hubot-test-helper')
chai = require 'chai'
nock = require 'nock'
expect = chai.expect
helper = new Helper('../src/bcycle-finder.coffee')
describe 'hubot-bcycle-finder', ->
beforeEach ->
nock.disableNetConnect()
nock('https://gbfs.bcycle.com')
.get('/bcycle_nashville/system_information.json')
.replyWithFile(200, __dirname + '/fixtures/system_information.json')
nock('https://gbfs.bcycle.com')
.get('/bcycle_nashville/system_pricing_plans.json')
.replyWithFile(200, __dirname + '/fixtures/system_pricing_plans.json')
nock('https://gbfs.bcycle.com')
.get('/bcycle_nashville/station_information.json')
.replyWithFile(200, __dirname + '/fixtures/station_information.json')
nock('https://gbfs.bcycle.com')
.get('/bcycle_nashville/station_status.json')
.replyWithFile(200, __dirname + '/fixtures/station_status.json')
afterEach ->
nock.cleanAll()
# hubot bcycle
context 'default stations tests', ->
beforeEach ->
process.env.BCYCLE_CITY = 'nashville'
process.env.BCYCLE_DEFAULT_STATIONS='2162,2165'
@room = helper.createRoom()
afterEach ->
@room.destroy()
delete process.env.BCYCLE_CITY
delete process.env.BCYCLE_DEFAULT_STATIONS
it 'returns the status of the default stations', (done) ->
selfRoom = @room
selfRoom.user.say('alice', '@hubot bcycle')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot bcycle']
['hubot', "#2162 - Commerce & 2nd Ave N\n> Active | Bikes: 12 | Docks: 3\n#2165 - Church St between 4th & 5th Ave N\n> Active | Bikes: 1 | Docks: 8"]
]
done()
catch err
done err
return
, 1000)
context 'regular tests', ->
beforeEach ->
process.env.BCYCLE_CITY = 'nashville'
@room = helper.createRoom()
afterEach ->
@room.destroy()
delete process.env.BCYCLE_CITY
it 'returns error message if no default stations set', (done) ->
selfRoom = @room
selfRoom.user.say('<NAME>', '@hubot bcycle')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot bcycle']
['hubot', 'You do not have any BCYCLE_DEFAULT_STATIONS configured.']
['hubot', 'Use `hubot bcycle search <query>` to find stations.']
]
done()
catch err
done err
return
, 1000)
# hubot bcycle list
it 'gets a listing of stations in the city', (done) ->
selfRoom = @room
selfRoom.user.say('<NAME>', '@hubot bcycle list')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot bcycle list']
['hubot', '#2162 - Commerce & 2nd Ave N']
['hubot', '#2165 - Church St between 4th & 5th Ave N']
['hubot', '#2166 - Public Square : 3rd Ave N & Union St']
['hubot', '#2168 - Cumberland Park']
['hubot', '#2169 - 6th Ave N & Union St']
['hubot', '#2170 - The Gulch : 11th Ave S & Pine St']
['hubot', '#2171 - Music Row Roundabout : 16th Ave S']
['hubot', '#2173 - 9th Ave S & Demonbreun St']
['hubot', '#2175 - Wedgewood Ave & 21st Ave S']
['hubot', '#2176 - 57 Peabody St']
['hubot', '#2177 - 5 Points East Nashville : S 11th St']
['hubot', '#2179 - Nashville Farmers\' Market']
['hubot', '#2180 - Germantown: 5th Ave & Monroe St']
['hubot', '#2181 - 3rd Ave S & Symphony Pl']
['hubot', '#2516 - 12th Ave S & Elmwood']
['hubot', '#2684 - Church St. and 20th Ave N']
['hubot', '#2973 - 2017 Belmont Blvd']
['hubot', '#2975 - Junior Gilliam Way & 5th Ave N']
['hubot', '#3456 - 40th Ave. N and Charlotte Ave.']
['hubot', '#3467 - Charlotte Ave and 46th Ave N']
['hubot', '#3568 - 200 21st Ave South']
['hubot', '#3613 - 715 Porter Road']
]
done()
catch err
done err
return
, 1000)
# hubot bcycle me <station id>
it 'returns the status for a given station', (done) ->
selfRoom = @room
selfRoom.user.say('alice', '@hubot bcycle me 2162')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot bcycle me 2162']
['hubot', '#2162 - Commerce & 2nd Ave N\n> Active | Bikes: 12 | Docks: 3']
]
done()
catch err
done err
return
, 1000)
# hubot bcycle search <query>
it 'searches the listing of stations', (done) ->
selfRoom = @room
selfRoom.user.say('<NAME>', '@hubot bcycle search church st')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['<NAME>', '@hubot bcycle search church st']
['hubot', '#2165 - Church St between 4th & 5th Ave N']
['hubot', '#2684 - Church St. and 20th Ave N']
]
done()
catch err
done err
return
, 1000)
# hubot bcycle info
it 'returns information about your program', (done) ->
selfRoom = @room
selfRoom.user.say('<NAME>', '@hubot bcycle info')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['<NAME>', '@hubot bcycle info']
['hubot', 'Nashville BCycle | https://nashville.bcycle.com | 844-982-4533 | <EMAIL>']
]
done()
catch err
done err
return
, 1000)
# hubot bcycle price
it 'returns pricing plan information', (done) ->
selfRoom = @room
selfRoom.user.say('<NAME>', '@hubot bcycle price')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['<NAME>', '@hubot bcycle price']
['hubot', "Single Ride Pass Online ($5) - $5 per 30 minutes. Total minutes calculated and billed the following day.\nGuest Pass ($25) - Unlimited 120-minute rides in a 3-Day period. Additional rental fee of $3 per 30 minutes for rides longer than 120 minutes.\nMonthly Pass ($20) - Enjoy unlimited 60-minute rides for 30 days! Rides longer than 60 minutes are subject to a usage fee of $3 per additional 30 minutes.\nAnnual Pass ($120) - Enjoy unlimited 120-minute rides for a year! *Limited time offer of 120-minutes.* Rides longer than 120 minutes are subject to a usage fee of $3 per additional 30 minutes.\nSingle Ride Pass ($5) - $5 per 30 minutes. Total minutes calculated and billed the following day."]
]
done()
catch err
done err
return
, 1000)
| true | Helper = require('hubot-test-helper')
chai = require 'chai'
nock = require 'nock'
expect = chai.expect
helper = new Helper('../src/bcycle-finder.coffee')
describe 'hubot-bcycle-finder', ->
beforeEach ->
nock.disableNetConnect()
nock('https://gbfs.bcycle.com')
.get('/bcycle_nashville/system_information.json')
.replyWithFile(200, __dirname + '/fixtures/system_information.json')
nock('https://gbfs.bcycle.com')
.get('/bcycle_nashville/system_pricing_plans.json')
.replyWithFile(200, __dirname + '/fixtures/system_pricing_plans.json')
nock('https://gbfs.bcycle.com')
.get('/bcycle_nashville/station_information.json')
.replyWithFile(200, __dirname + '/fixtures/station_information.json')
nock('https://gbfs.bcycle.com')
.get('/bcycle_nashville/station_status.json')
.replyWithFile(200, __dirname + '/fixtures/station_status.json')
afterEach ->
nock.cleanAll()
# hubot bcycle
context 'default stations tests', ->
beforeEach ->
process.env.BCYCLE_CITY = 'nashville'
process.env.BCYCLE_DEFAULT_STATIONS='2162,2165'
@room = helper.createRoom()
afterEach ->
@room.destroy()
delete process.env.BCYCLE_CITY
delete process.env.BCYCLE_DEFAULT_STATIONS
it 'returns the status of the default stations', (done) ->
selfRoom = @room
selfRoom.user.say('alice', '@hubot bcycle')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot bcycle']
['hubot', "#2162 - Commerce & 2nd Ave N\n> Active | Bikes: 12 | Docks: 3\n#2165 - Church St between 4th & 5th Ave N\n> Active | Bikes: 1 | Docks: 8"]
]
done()
catch err
done err
return
, 1000)
context 'regular tests', ->
beforeEach ->
process.env.BCYCLE_CITY = 'nashville'
@room = helper.createRoom()
afterEach ->
@room.destroy()
delete process.env.BCYCLE_CITY
it 'returns error message if no default stations set', (done) ->
selfRoom = @room
selfRoom.user.say('PI:NAME:<NAME>END_PI', '@hubot bcycle')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot bcycle']
['hubot', 'You do not have any BCYCLE_DEFAULT_STATIONS configured.']
['hubot', 'Use `hubot bcycle search <query>` to find stations.']
]
done()
catch err
done err
return
, 1000)
# hubot bcycle list
it 'gets a listing of stations in the city', (done) ->
selfRoom = @room
selfRoom.user.say('PI:NAME:<NAME>END_PI', '@hubot bcycle list')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot bcycle list']
['hubot', '#2162 - Commerce & 2nd Ave N']
['hubot', '#2165 - Church St between 4th & 5th Ave N']
['hubot', '#2166 - Public Square : 3rd Ave N & Union St']
['hubot', '#2168 - Cumberland Park']
['hubot', '#2169 - 6th Ave N & Union St']
['hubot', '#2170 - The Gulch : 11th Ave S & Pine St']
['hubot', '#2171 - Music Row Roundabout : 16th Ave S']
['hubot', '#2173 - 9th Ave S & Demonbreun St']
['hubot', '#2175 - Wedgewood Ave & 21st Ave S']
['hubot', '#2176 - 57 Peabody St']
['hubot', '#2177 - 5 Points East Nashville : S 11th St']
['hubot', '#2179 - Nashville Farmers\' Market']
['hubot', '#2180 - Germantown: 5th Ave & Monroe St']
['hubot', '#2181 - 3rd Ave S & Symphony Pl']
['hubot', '#2516 - 12th Ave S & Elmwood']
['hubot', '#2684 - Church St. and 20th Ave N']
['hubot', '#2973 - 2017 Belmont Blvd']
['hubot', '#2975 - Junior Gilliam Way & 5th Ave N']
['hubot', '#3456 - 40th Ave. N and Charlotte Ave.']
['hubot', '#3467 - Charlotte Ave and 46th Ave N']
['hubot', '#3568 - 200 21st Ave South']
['hubot', '#3613 - 715 Porter Road']
]
done()
catch err
done err
return
, 1000)
# hubot bcycle me <station id>
it 'returns the status for a given station', (done) ->
selfRoom = @room
selfRoom.user.say('alice', '@hubot bcycle me 2162')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot bcycle me 2162']
['hubot', '#2162 - Commerce & 2nd Ave N\n> Active | Bikes: 12 | Docks: 3']
]
done()
catch err
done err
return
, 1000)
# hubot bcycle search <query>
it 'searches the listing of stations', (done) ->
selfRoom = @room
selfRoom.user.say('PI:NAME:<NAME>END_PI', '@hubot bcycle search church st')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['PI:NAME:<NAME>END_PI', '@hubot bcycle search church st']
['hubot', '#2165 - Church St between 4th & 5th Ave N']
['hubot', '#2684 - Church St. and 20th Ave N']
]
done()
catch err
done err
return
, 1000)
# hubot bcycle info
it 'returns information about your program', (done) ->
selfRoom = @room
selfRoom.user.say('PI:NAME:<NAME>END_PI', '@hubot bcycle info')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['PI:NAME:<NAME>END_PI', '@hubot bcycle info']
['hubot', 'Nashville BCycle | https://nashville.bcycle.com | 844-982-4533 | PI:EMAIL:<EMAIL>END_PI']
]
done()
catch err
done err
return
, 1000)
# hubot bcycle price
it 'returns pricing plan information', (done) ->
selfRoom = @room
selfRoom.user.say('PI:NAME:<NAME>END_PI', '@hubot bcycle price')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['PI:NAME:<NAME>END_PI', '@hubot bcycle price']
['hubot', "Single Ride Pass Online ($5) - $5 per 30 minutes. Total minutes calculated and billed the following day.\nGuest Pass ($25) - Unlimited 120-minute rides in a 3-Day period. Additional rental fee of $3 per 30 minutes for rides longer than 120 minutes.\nMonthly Pass ($20) - Enjoy unlimited 60-minute rides for 30 days! Rides longer than 60 minutes are subject to a usage fee of $3 per additional 30 minutes.\nAnnual Pass ($120) - Enjoy unlimited 120-minute rides for a year! *Limited time offer of 120-minutes.* Rides longer than 120 minutes are subject to a usage fee of $3 per additional 30 minutes.\nSingle Ride Pass ($5) - $5 per 30 minutes. Total minutes calculated and billed the following day."]
]
done()
catch err
done err
return
, 1000)
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999135732650757,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
},
{
"context": "s[undefined] =\n username: osu.trans 'users.deleted'\n\... | resources/assets/coffee/react/modding-profile/main.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 { Events } from './events'
import { ExtraTab } from '../profile-page/extra-tab'
import { Discussions} from './discussions'
import { Header } from './header'
import { Kudosu } from '../profile-page/kudosu'
import { Votes } from './votes'
import { BeatmapsContext } from 'beatmap-discussions/beatmaps-context'
import { DiscussionsContext } from 'beatmap-discussions/discussions-context'
import { BlockButton } from 'block-button'
import { NotificationBanner } from 'notification-banner'
import { Posts } from "./posts"
import * as React from 'react'
import { a, button, div, i, span} from 'react-dom-factories'
el = React.createElement
pages = document.getElementsByClassName("js-switchable-mode-page--scrollspy")
pagesOffset = document.getElementsByClassName("js-switchable-mode-page--scrollspy-offset")
currentLocation = ->
"#{document.location.pathname}#{document.location.search}"
export class Main extends React.PureComponent
constructor: (props) ->
super props
@cache = {}
@tabs = React.createRef()
@pages = React.createRef()
@state = JSON.parse(props.container.dataset.profilePageState ? null)
@restoredState = @state?
if !@restoredState
page = location.hash.slice(1)
@initialPage = page if page?
@state =
discussions: props.discussions
events: props.events
user: props.user
users: props.users
posts: props.posts
votes: props.votes
profileOrder: ['events', 'discussions', 'posts', 'votes', 'kudosu']
rankedAndApprovedBeatmapsets: @props.extras.rankedAndApprovedBeatmapsets
lovedBeatmapsets: @props.extras.lovedBeatmapsets
unrankedBeatmapsets: @props.extras.unrankedBeatmapsets
graveyardBeatmapsets: @props.extras.graveyardBeatmapsets
recentlyReceivedKudosu: @props.extras.recentlyReceivedKudosu
showMorePagination: {}
for own elem, perPage of @props.perPage
@state.showMorePagination[elem] ?= {}
@state.showMorePagination[elem].hasMore = @state[elem].length > perPage
if @state.showMorePagination[elem].hasMore
@state[elem].pop()
componentDidMount: =>
$.subscribe 'user:update.profilePage', @userUpdate
$.subscribe 'profile:showMore.moddingProfilePage', @showMore
$.subscribe 'profile:page:jump.moddingProfilePage', @pageJump
$.subscribe 'beatmapsetDiscussions:update.moddingProfilePage', @discussionUpdate
$(document).on 'ajax:success.moddingProfilePage', '.js-beatmapset-discussion-update', @ujsDiscussionUpdate
$(window).on 'throttled-scroll.moddingProfilePage', @pageScan
osu.pageChange()
@modeScrollUrl = currentLocation()
if !@restoredState
Timeout.set 0, => @pageJump null, @initialPage
componentWillUnmount: =>
$.unsubscribe '.moddingProfilePage'
$(window).off '.moddingProfilePage'
$(window).stop()
Timeout.clear @modeScrollTimeout
discussionUpdate: (_e, options) =>
{beatmapset} = options
return unless beatmapset?
discussions = @state.discussions
posts = @state.posts
users = @state.users
discussionIds = _.map discussions, 'id'
postIds = _.map posts, 'id'
userIds = _.map users, 'id'
# Due to the entire hierarchy of discussions being sent back when a post is updated (instead of just the modified post),
# we need to iterate over each discussion and their posts to extract the updates we want.
_.each beatmapset.discussions, (newDiscussion) ->
if discussionIds.includes(newDiscussion.id)
discussion = _.find discussions, id: newDiscussion.id
discussions = _.reject discussions, id: newDiscussion.id
newDiscussion = _.merge(discussion, newDiscussion)
# The discussion list shows discussions started by the current user, so it can be assumed that the first post is theirs
newDiscussion.starting_post = newDiscussion.posts[0]
discussions.push(newDiscussion)
_.each newDiscussion.posts, (newPost) ->
if postIds.includes(newPost.id)
post = _.find posts, id: newPost.id
posts = _.reject posts, id: newPost.id
posts.push(_.merge(post, newPost))
_.each beatmapset.related_users, (newUser) ->
if userIds.includes(newUser.id)
users = _.reject users, id: newUser.id
users.push(newUser)
@cache.users = @cache.discussions = @cache.beatmaps = null
@setState
discussions: _.reverse(_.sortBy(discussions, (d) -> Date.parse(d.starting_post.created_at)))
posts: _.reverse(_.sortBy(posts, (p) -> Date.parse(p.created_at)))
users: users
discussions: =>
# skipped discussions
# - not privileged (deleted discussion)
# - deleted beatmap
@cache.discussions ?= _ @state.discussions
.filter (d) -> !_.isEmpty(d)
.keyBy 'id'
.value()
beatmaps: =>
beatmaps = _.map(@discussions(), (d) => d.beatmap)
.filter((b) => b != undefined)
@cache.beatmaps ?= _.keyBy(beatmaps, 'id')
render: =>
profileOrder = @state.profileOrder
isBlocked = _.find(currentUser.blocks, target_id: @state.user.id)
el DiscussionsContext.Provider,
value: @discussions()
el BeatmapsContext.Provider,
value: @beatmaps()
div
className: 'osu-layout__no-scroll' if isBlocked && !@state.forceShow
if isBlocked
div className: 'osu-page',
el NotificationBanner,
type: 'warning'
title: osu.trans('users.blocks.banner_text')
message:
div className: 'grid-items grid-items--notification-banner-buttons',
div null,
el BlockButton, userId: @props.user.id
div null,
button
type: 'button'
className: 'textual-button'
onClick: =>
@setState forceShow: !@state.forceShow
span {},
i className: 'textual-button__icon fas fa-low-vision'
" "
if @state.forceShow
osu.trans('users.blocks.hide_profile')
else
osu.trans('users.blocks.show_profile')
div className: "osu-layout osu-layout--full#{if isBlocked && !@state.forceShow then ' osu-layout--masked' else ''}",
el Header,
user: @state.user
stats: @state.user.statistics
userAchievements: @props.userAchievements
div
className: 'hidden-xs page-extra-tabs page-extra-tabs--profile-page js-switchable-mode-page--scrollspy-offset'
div className: 'osu-page',
div
className: 'page-mode page-mode--profile-page-extra'
ref: @tabs
for m in profileOrder
a
className: 'page-mode__item'
key: m
'data-page-id': m
onClick: @tabClick
href: "##{m}"
el ExtraTab,
page: m
currentPage: @state.currentPage
currentMode: @state.currentMode
div
className: 'osu-layout__section osu-layout__section--users-extra'
div
className: 'osu-layout__row'
ref: @pages
@extraPage name for name in profileOrder
extraPage: (name) =>
{extraClass, props, component} = @extraPageParams name
classes = 'js-switchable-mode-page--scrollspy js-switchable-mode-page--page'
classes += " #{extraClass}" if extraClass?
props.name = name
@extraPages ?= {}
div
key: name
'data-page-id': name
className: classes
ref: (el) => @extraPages[name] = el
el component, props
extraPageParams: (name) =>
switch name
when 'discussions'
props:
discussions: @state.discussions
user: @state.user
users: @users()
component: Discussions
when 'events'
props:
events: @state.events
user: @state.user
users: @users()
component: Events
when 'kudosu'
props:
user: @state.user
recentlyReceivedKudosu: @state.recentlyReceivedKudosu
pagination: @state.showMorePagination
component: Kudosu
when 'posts'
props:
posts: @state.posts
user: @state.user
users: @users()
component: Posts
when 'votes'
props:
votes: @state.votes
user: @state.user
users: @users()
component: Votes
showMore: (e, {name, url, perPage = 50}) =>
offset = @state[name].length
paginationState = _.cloneDeep @state.showMorePagination
paginationState[name] ?= {}
paginationState[name].loading = true
@setState showMorePagination: paginationState, ->
$.get osu.updateQueryString(url, offset: offset, limit: perPage + 1), (data) =>
state = _.cloneDeep(@state[name]).concat(data)
hasMore = data.length > perPage
state.pop() if hasMore
paginationState = _.cloneDeep @state.showMorePagination
paginationState[name].loading = false
paginationState[name].hasMore = hasMore
@setState
"#{name}": state
showMorePagination: paginationState
pageJump: (_e, page) =>
if page == 'main'
@setCurrentPage null, page
return
target = $(@extraPages[page])
# if invalid page is specified, scan current position
if target.length == 0
@pageScan()
return
# Don't bother scanning the current position.
# The result will be wrong when target page is too short anyway.
@scrolling = true
Timeout.clear @modeScrollTimeout
# count for the tabs height; assume pageJump always causes the header to be pinned
# otherwise the calculation needs another phase and gets a bit messy.
offsetTop = target.offset().top - pagesOffset[0].getBoundingClientRect().height
$(window).stop().scrollTo window.stickyHeader.scrollOffset(offsetTop), 500,
onAfter: =>
# Manually set the mode to avoid confusion (wrong highlight).
# Scrolling will obviously break it but that's unfortunate result
# from having the scrollspy marker at middle of page.
@setCurrentPage null, page, =>
# Doesn't work:
# - part of state (callback, part of mode setting)
# - simple variable in callback
# Both still change the switch too soon.
@modeScrollTimeout = Timeout.set 100, => @scrolling = false
pageScan: =>
return if @modeScrollUrl != currentLocation()
return if @scrolling
return if pages.length == 0
anchorHeight = pagesOffset[0].getBoundingClientRect().height
if osu.bottomPage()
@setCurrentPage null, _.last(pages).dataset.pageId
return
for page in pages
pageDims = page.getBoundingClientRect()
pageBottom = pageDims.bottom - Math.min(pageDims.height * 0.75, 200)
continue unless pageBottom > anchorHeight
@setCurrentPage null, page.dataset.pageId
return
@setCurrentPage null, page.dataset.pageId
setCurrentPage: (_e, page, extraCallback) =>
callback = =>
extraCallback?()
@setHash?()
if @state.currentPage == page
return callback()
@setState currentPage: page, callback
tabClick: (e) =>
e.preventDefault()
@pageJump null, e.currentTarget.dataset.pageId
userUpdate: (_e, user) =>
return @forceUpdate() if user?.id != @state.user.id
# this component needs full user object but sometimes this event only sends part of it
@setState user: _.assign({}, @state.user, user)
users: =>
if !@cache.users?
@cache.users = _.keyBy @state.users, 'id'
@cache.users[null] = @cache.users[undefined] =
username: osu.trans 'users.deleted'
@cache.users
ujsDiscussionUpdate: (_e, data) =>
# to allow ajax:complete to be run
Timeout.set 0, => @discussionUpdate(null, beatmapset: data)
| 163318 | # 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 { Events } from './events'
import { ExtraTab } from '../profile-page/extra-tab'
import { Discussions} from './discussions'
import { Header } from './header'
import { Kudosu } from '../profile-page/kudosu'
import { Votes } from './votes'
import { BeatmapsContext } from 'beatmap-discussions/beatmaps-context'
import { DiscussionsContext } from 'beatmap-discussions/discussions-context'
import { BlockButton } from 'block-button'
import { NotificationBanner } from 'notification-banner'
import { Posts } from "./posts"
import * as React from 'react'
import { a, button, div, i, span} from 'react-dom-factories'
el = React.createElement
pages = document.getElementsByClassName("js-switchable-mode-page--scrollspy")
pagesOffset = document.getElementsByClassName("js-switchable-mode-page--scrollspy-offset")
currentLocation = ->
"#{document.location.pathname}#{document.location.search}"
export class Main extends React.PureComponent
constructor: (props) ->
super props
@cache = {}
@tabs = React.createRef()
@pages = React.createRef()
@state = JSON.parse(props.container.dataset.profilePageState ? null)
@restoredState = @state?
if !@restoredState
page = location.hash.slice(1)
@initialPage = page if page?
@state =
discussions: props.discussions
events: props.events
user: props.user
users: props.users
posts: props.posts
votes: props.votes
profileOrder: ['events', 'discussions', 'posts', 'votes', 'kudosu']
rankedAndApprovedBeatmapsets: @props.extras.rankedAndApprovedBeatmapsets
lovedBeatmapsets: @props.extras.lovedBeatmapsets
unrankedBeatmapsets: @props.extras.unrankedBeatmapsets
graveyardBeatmapsets: @props.extras.graveyardBeatmapsets
recentlyReceivedKudosu: @props.extras.recentlyReceivedKudosu
showMorePagination: {}
for own elem, perPage of @props.perPage
@state.showMorePagination[elem] ?= {}
@state.showMorePagination[elem].hasMore = @state[elem].length > perPage
if @state.showMorePagination[elem].hasMore
@state[elem].pop()
componentDidMount: =>
$.subscribe 'user:update.profilePage', @userUpdate
$.subscribe 'profile:showMore.moddingProfilePage', @showMore
$.subscribe 'profile:page:jump.moddingProfilePage', @pageJump
$.subscribe 'beatmapsetDiscussions:update.moddingProfilePage', @discussionUpdate
$(document).on 'ajax:success.moddingProfilePage', '.js-beatmapset-discussion-update', @ujsDiscussionUpdate
$(window).on 'throttled-scroll.moddingProfilePage', @pageScan
osu.pageChange()
@modeScrollUrl = currentLocation()
if !@restoredState
Timeout.set 0, => @pageJump null, @initialPage
componentWillUnmount: =>
$.unsubscribe '.moddingProfilePage'
$(window).off '.moddingProfilePage'
$(window).stop()
Timeout.clear @modeScrollTimeout
discussionUpdate: (_e, options) =>
{beatmapset} = options
return unless beatmapset?
discussions = @state.discussions
posts = @state.posts
users = @state.users
discussionIds = _.map discussions, 'id'
postIds = _.map posts, 'id'
userIds = _.map users, 'id'
# Due to the entire hierarchy of discussions being sent back when a post is updated (instead of just the modified post),
# we need to iterate over each discussion and their posts to extract the updates we want.
_.each beatmapset.discussions, (newDiscussion) ->
if discussionIds.includes(newDiscussion.id)
discussion = _.find discussions, id: newDiscussion.id
discussions = _.reject discussions, id: newDiscussion.id
newDiscussion = _.merge(discussion, newDiscussion)
# The discussion list shows discussions started by the current user, so it can be assumed that the first post is theirs
newDiscussion.starting_post = newDiscussion.posts[0]
discussions.push(newDiscussion)
_.each newDiscussion.posts, (newPost) ->
if postIds.includes(newPost.id)
post = _.find posts, id: newPost.id
posts = _.reject posts, id: newPost.id
posts.push(_.merge(post, newPost))
_.each beatmapset.related_users, (newUser) ->
if userIds.includes(newUser.id)
users = _.reject users, id: newUser.id
users.push(newUser)
@cache.users = @cache.discussions = @cache.beatmaps = null
@setState
discussions: _.reverse(_.sortBy(discussions, (d) -> Date.parse(d.starting_post.created_at)))
posts: _.reverse(_.sortBy(posts, (p) -> Date.parse(p.created_at)))
users: users
discussions: =>
# skipped discussions
# - not privileged (deleted discussion)
# - deleted beatmap
@cache.discussions ?= _ @state.discussions
.filter (d) -> !_.isEmpty(d)
.keyBy 'id'
.value()
beatmaps: =>
beatmaps = _.map(@discussions(), (d) => d.beatmap)
.filter((b) => b != undefined)
@cache.beatmaps ?= _.keyBy(beatmaps, 'id')
render: =>
profileOrder = @state.profileOrder
isBlocked = _.find(currentUser.blocks, target_id: @state.user.id)
el DiscussionsContext.Provider,
value: @discussions()
el BeatmapsContext.Provider,
value: @beatmaps()
div
className: 'osu-layout__no-scroll' if isBlocked && !@state.forceShow
if isBlocked
div className: 'osu-page',
el NotificationBanner,
type: 'warning'
title: osu.trans('users.blocks.banner_text')
message:
div className: 'grid-items grid-items--notification-banner-buttons',
div null,
el BlockButton, userId: @props.user.id
div null,
button
type: 'button'
className: 'textual-button'
onClick: =>
@setState forceShow: !@state.forceShow
span {},
i className: 'textual-button__icon fas fa-low-vision'
" "
if @state.forceShow
osu.trans('users.blocks.hide_profile')
else
osu.trans('users.blocks.show_profile')
div className: "osu-layout osu-layout--full#{if isBlocked && !@state.forceShow then ' osu-layout--masked' else ''}",
el Header,
user: @state.user
stats: @state.user.statistics
userAchievements: @props.userAchievements
div
className: 'hidden-xs page-extra-tabs page-extra-tabs--profile-page js-switchable-mode-page--scrollspy-offset'
div className: 'osu-page',
div
className: 'page-mode page-mode--profile-page-extra'
ref: @tabs
for m in profileOrder
a
className: 'page-mode__item'
key: m
'data-page-id': m
onClick: @tabClick
href: "##{m}"
el ExtraTab,
page: m
currentPage: @state.currentPage
currentMode: @state.currentMode
div
className: 'osu-layout__section osu-layout__section--users-extra'
div
className: 'osu-layout__row'
ref: @pages
@extraPage name for name in profileOrder
extraPage: (name) =>
{extraClass, props, component} = @extraPageParams name
classes = 'js-switchable-mode-page--scrollspy js-switchable-mode-page--page'
classes += " #{extraClass}" if extraClass?
props.name = name
@extraPages ?= {}
div
key: name
'data-page-id': name
className: classes
ref: (el) => @extraPages[name] = el
el component, props
extraPageParams: (name) =>
switch name
when 'discussions'
props:
discussions: @state.discussions
user: @state.user
users: @users()
component: Discussions
when 'events'
props:
events: @state.events
user: @state.user
users: @users()
component: Events
when 'kudosu'
props:
user: @state.user
recentlyReceivedKudosu: @state.recentlyReceivedKudosu
pagination: @state.showMorePagination
component: Kudosu
when 'posts'
props:
posts: @state.posts
user: @state.user
users: @users()
component: Posts
when 'votes'
props:
votes: @state.votes
user: @state.user
users: @users()
component: Votes
showMore: (e, {name, url, perPage = 50}) =>
offset = @state[name].length
paginationState = _.cloneDeep @state.showMorePagination
paginationState[name] ?= {}
paginationState[name].loading = true
@setState showMorePagination: paginationState, ->
$.get osu.updateQueryString(url, offset: offset, limit: perPage + 1), (data) =>
state = _.cloneDeep(@state[name]).concat(data)
hasMore = data.length > perPage
state.pop() if hasMore
paginationState = _.cloneDeep @state.showMorePagination
paginationState[name].loading = false
paginationState[name].hasMore = hasMore
@setState
"#{name}": state
showMorePagination: paginationState
pageJump: (_e, page) =>
if page == 'main'
@setCurrentPage null, page
return
target = $(@extraPages[page])
# if invalid page is specified, scan current position
if target.length == 0
@pageScan()
return
# Don't bother scanning the current position.
# The result will be wrong when target page is too short anyway.
@scrolling = true
Timeout.clear @modeScrollTimeout
# count for the tabs height; assume pageJump always causes the header to be pinned
# otherwise the calculation needs another phase and gets a bit messy.
offsetTop = target.offset().top - pagesOffset[0].getBoundingClientRect().height
$(window).stop().scrollTo window.stickyHeader.scrollOffset(offsetTop), 500,
onAfter: =>
# Manually set the mode to avoid confusion (wrong highlight).
# Scrolling will obviously break it but that's unfortunate result
# from having the scrollspy marker at middle of page.
@setCurrentPage null, page, =>
# Doesn't work:
# - part of state (callback, part of mode setting)
# - simple variable in callback
# Both still change the switch too soon.
@modeScrollTimeout = Timeout.set 100, => @scrolling = false
pageScan: =>
return if @modeScrollUrl != currentLocation()
return if @scrolling
return if pages.length == 0
anchorHeight = pagesOffset[0].getBoundingClientRect().height
if osu.bottomPage()
@setCurrentPage null, _.last(pages).dataset.pageId
return
for page in pages
pageDims = page.getBoundingClientRect()
pageBottom = pageDims.bottom - Math.min(pageDims.height * 0.75, 200)
continue unless pageBottom > anchorHeight
@setCurrentPage null, page.dataset.pageId
return
@setCurrentPage null, page.dataset.pageId
setCurrentPage: (_e, page, extraCallback) =>
callback = =>
extraCallback?()
@setHash?()
if @state.currentPage == page
return callback()
@setState currentPage: page, callback
tabClick: (e) =>
e.preventDefault()
@pageJump null, e.currentTarget.dataset.pageId
userUpdate: (_e, user) =>
return @forceUpdate() if user?.id != @state.user.id
# this component needs full user object but sometimes this event only sends part of it
@setState user: _.assign({}, @state.user, user)
users: =>
if !@cache.users?
@cache.users = _.keyBy @state.users, 'id'
@cache.users[null] = @cache.users[undefined] =
username: osu.trans 'users.deleted'
@cache.users
ujsDiscussionUpdate: (_e, data) =>
# to allow ajax:complete to be run
Timeout.set 0, => @discussionUpdate(null, beatmapset: data)
| 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 { Events } from './events'
import { ExtraTab } from '../profile-page/extra-tab'
import { Discussions} from './discussions'
import { Header } from './header'
import { Kudosu } from '../profile-page/kudosu'
import { Votes } from './votes'
import { BeatmapsContext } from 'beatmap-discussions/beatmaps-context'
import { DiscussionsContext } from 'beatmap-discussions/discussions-context'
import { BlockButton } from 'block-button'
import { NotificationBanner } from 'notification-banner'
import { Posts } from "./posts"
import * as React from 'react'
import { a, button, div, i, span} from 'react-dom-factories'
el = React.createElement
pages = document.getElementsByClassName("js-switchable-mode-page--scrollspy")
pagesOffset = document.getElementsByClassName("js-switchable-mode-page--scrollspy-offset")
currentLocation = ->
"#{document.location.pathname}#{document.location.search}"
export class Main extends React.PureComponent
constructor: (props) ->
super props
@cache = {}
@tabs = React.createRef()
@pages = React.createRef()
@state = JSON.parse(props.container.dataset.profilePageState ? null)
@restoredState = @state?
if !@restoredState
page = location.hash.slice(1)
@initialPage = page if page?
@state =
discussions: props.discussions
events: props.events
user: props.user
users: props.users
posts: props.posts
votes: props.votes
profileOrder: ['events', 'discussions', 'posts', 'votes', 'kudosu']
rankedAndApprovedBeatmapsets: @props.extras.rankedAndApprovedBeatmapsets
lovedBeatmapsets: @props.extras.lovedBeatmapsets
unrankedBeatmapsets: @props.extras.unrankedBeatmapsets
graveyardBeatmapsets: @props.extras.graveyardBeatmapsets
recentlyReceivedKudosu: @props.extras.recentlyReceivedKudosu
showMorePagination: {}
for own elem, perPage of @props.perPage
@state.showMorePagination[elem] ?= {}
@state.showMorePagination[elem].hasMore = @state[elem].length > perPage
if @state.showMorePagination[elem].hasMore
@state[elem].pop()
componentDidMount: =>
$.subscribe 'user:update.profilePage', @userUpdate
$.subscribe 'profile:showMore.moddingProfilePage', @showMore
$.subscribe 'profile:page:jump.moddingProfilePage', @pageJump
$.subscribe 'beatmapsetDiscussions:update.moddingProfilePage', @discussionUpdate
$(document).on 'ajax:success.moddingProfilePage', '.js-beatmapset-discussion-update', @ujsDiscussionUpdate
$(window).on 'throttled-scroll.moddingProfilePage', @pageScan
osu.pageChange()
@modeScrollUrl = currentLocation()
if !@restoredState
Timeout.set 0, => @pageJump null, @initialPage
componentWillUnmount: =>
$.unsubscribe '.moddingProfilePage'
$(window).off '.moddingProfilePage'
$(window).stop()
Timeout.clear @modeScrollTimeout
discussionUpdate: (_e, options) =>
{beatmapset} = options
return unless beatmapset?
discussions = @state.discussions
posts = @state.posts
users = @state.users
discussionIds = _.map discussions, 'id'
postIds = _.map posts, 'id'
userIds = _.map users, 'id'
# Due to the entire hierarchy of discussions being sent back when a post is updated (instead of just the modified post),
# we need to iterate over each discussion and their posts to extract the updates we want.
_.each beatmapset.discussions, (newDiscussion) ->
if discussionIds.includes(newDiscussion.id)
discussion = _.find discussions, id: newDiscussion.id
discussions = _.reject discussions, id: newDiscussion.id
newDiscussion = _.merge(discussion, newDiscussion)
# The discussion list shows discussions started by the current user, so it can be assumed that the first post is theirs
newDiscussion.starting_post = newDiscussion.posts[0]
discussions.push(newDiscussion)
_.each newDiscussion.posts, (newPost) ->
if postIds.includes(newPost.id)
post = _.find posts, id: newPost.id
posts = _.reject posts, id: newPost.id
posts.push(_.merge(post, newPost))
_.each beatmapset.related_users, (newUser) ->
if userIds.includes(newUser.id)
users = _.reject users, id: newUser.id
users.push(newUser)
@cache.users = @cache.discussions = @cache.beatmaps = null
@setState
discussions: _.reverse(_.sortBy(discussions, (d) -> Date.parse(d.starting_post.created_at)))
posts: _.reverse(_.sortBy(posts, (p) -> Date.parse(p.created_at)))
users: users
discussions: =>
# skipped discussions
# - not privileged (deleted discussion)
# - deleted beatmap
@cache.discussions ?= _ @state.discussions
.filter (d) -> !_.isEmpty(d)
.keyBy 'id'
.value()
beatmaps: =>
beatmaps = _.map(@discussions(), (d) => d.beatmap)
.filter((b) => b != undefined)
@cache.beatmaps ?= _.keyBy(beatmaps, 'id')
render: =>
profileOrder = @state.profileOrder
isBlocked = _.find(currentUser.blocks, target_id: @state.user.id)
el DiscussionsContext.Provider,
value: @discussions()
el BeatmapsContext.Provider,
value: @beatmaps()
div
className: 'osu-layout__no-scroll' if isBlocked && !@state.forceShow
if isBlocked
div className: 'osu-page',
el NotificationBanner,
type: 'warning'
title: osu.trans('users.blocks.banner_text')
message:
div className: 'grid-items grid-items--notification-banner-buttons',
div null,
el BlockButton, userId: @props.user.id
div null,
button
type: 'button'
className: 'textual-button'
onClick: =>
@setState forceShow: !@state.forceShow
span {},
i className: 'textual-button__icon fas fa-low-vision'
" "
if @state.forceShow
osu.trans('users.blocks.hide_profile')
else
osu.trans('users.blocks.show_profile')
div className: "osu-layout osu-layout--full#{if isBlocked && !@state.forceShow then ' osu-layout--masked' else ''}",
el Header,
user: @state.user
stats: @state.user.statistics
userAchievements: @props.userAchievements
div
className: 'hidden-xs page-extra-tabs page-extra-tabs--profile-page js-switchable-mode-page--scrollspy-offset'
div className: 'osu-page',
div
className: 'page-mode page-mode--profile-page-extra'
ref: @tabs
for m in profileOrder
a
className: 'page-mode__item'
key: m
'data-page-id': m
onClick: @tabClick
href: "##{m}"
el ExtraTab,
page: m
currentPage: @state.currentPage
currentMode: @state.currentMode
div
className: 'osu-layout__section osu-layout__section--users-extra'
div
className: 'osu-layout__row'
ref: @pages
@extraPage name for name in profileOrder
extraPage: (name) =>
{extraClass, props, component} = @extraPageParams name
classes = 'js-switchable-mode-page--scrollspy js-switchable-mode-page--page'
classes += " #{extraClass}" if extraClass?
props.name = name
@extraPages ?= {}
div
key: name
'data-page-id': name
className: classes
ref: (el) => @extraPages[name] = el
el component, props
extraPageParams: (name) =>
switch name
when 'discussions'
props:
discussions: @state.discussions
user: @state.user
users: @users()
component: Discussions
when 'events'
props:
events: @state.events
user: @state.user
users: @users()
component: Events
when 'kudosu'
props:
user: @state.user
recentlyReceivedKudosu: @state.recentlyReceivedKudosu
pagination: @state.showMorePagination
component: Kudosu
when 'posts'
props:
posts: @state.posts
user: @state.user
users: @users()
component: Posts
when 'votes'
props:
votes: @state.votes
user: @state.user
users: @users()
component: Votes
showMore: (e, {name, url, perPage = 50}) =>
offset = @state[name].length
paginationState = _.cloneDeep @state.showMorePagination
paginationState[name] ?= {}
paginationState[name].loading = true
@setState showMorePagination: paginationState, ->
$.get osu.updateQueryString(url, offset: offset, limit: perPage + 1), (data) =>
state = _.cloneDeep(@state[name]).concat(data)
hasMore = data.length > perPage
state.pop() if hasMore
paginationState = _.cloneDeep @state.showMorePagination
paginationState[name].loading = false
paginationState[name].hasMore = hasMore
@setState
"#{name}": state
showMorePagination: paginationState
pageJump: (_e, page) =>
if page == 'main'
@setCurrentPage null, page
return
target = $(@extraPages[page])
# if invalid page is specified, scan current position
if target.length == 0
@pageScan()
return
# Don't bother scanning the current position.
# The result will be wrong when target page is too short anyway.
@scrolling = true
Timeout.clear @modeScrollTimeout
# count for the tabs height; assume pageJump always causes the header to be pinned
# otherwise the calculation needs another phase and gets a bit messy.
offsetTop = target.offset().top - pagesOffset[0].getBoundingClientRect().height
$(window).stop().scrollTo window.stickyHeader.scrollOffset(offsetTop), 500,
onAfter: =>
# Manually set the mode to avoid confusion (wrong highlight).
# Scrolling will obviously break it but that's unfortunate result
# from having the scrollspy marker at middle of page.
@setCurrentPage null, page, =>
# Doesn't work:
# - part of state (callback, part of mode setting)
# - simple variable in callback
# Both still change the switch too soon.
@modeScrollTimeout = Timeout.set 100, => @scrolling = false
pageScan: =>
return if @modeScrollUrl != currentLocation()
return if @scrolling
return if pages.length == 0
anchorHeight = pagesOffset[0].getBoundingClientRect().height
if osu.bottomPage()
@setCurrentPage null, _.last(pages).dataset.pageId
return
for page in pages
pageDims = page.getBoundingClientRect()
pageBottom = pageDims.bottom - Math.min(pageDims.height * 0.75, 200)
continue unless pageBottom > anchorHeight
@setCurrentPage null, page.dataset.pageId
return
@setCurrentPage null, page.dataset.pageId
setCurrentPage: (_e, page, extraCallback) =>
callback = =>
extraCallback?()
@setHash?()
if @state.currentPage == page
return callback()
@setState currentPage: page, callback
tabClick: (e) =>
e.preventDefault()
@pageJump null, e.currentTarget.dataset.pageId
userUpdate: (_e, user) =>
return @forceUpdate() if user?.id != @state.user.id
# this component needs full user object but sometimes this event only sends part of it
@setState user: _.assign({}, @state.user, user)
users: =>
if !@cache.users?
@cache.users = _.keyBy @state.users, 'id'
@cache.users[null] = @cache.users[undefined] =
username: osu.trans 'users.deleted'
@cache.users
ujsDiscussionUpdate: (_e, data) =>
# to allow ajax:complete to be run
Timeout.set 0, => @discussionUpdate(null, beatmapset: data)
|
[
{
"context": "ingle line of markdown', ->\n\t\t\tmarkdown = \"\"\"\n\t\t\t# fatarrow\n\t\t\t\"\"\"\n\n\t\t\thtml = @markdownService.convert ma",
"end": 213,
"score": 0.8162595629692078,
"start": 205,
"tag": "USERNAME",
"value": "fatarrow"
},
{
"context": "iple lines of markdown',... | src/components/markdown/test/markdownService.spec.coffee | webmaster89898/CaryLandholt-fatarrow | 0 | describe 'markdown', ->
describe 'markdownService', ->
beforeEach module 'app'
beforeEach inject (@markdownService) ->
it 'converts html from a single line of markdown', ->
markdown = """
# fatarrow
"""
html = @markdownService.convert markdown
expected = '<h1 id="fatarrow">fatarrow</h1>'
expect html
.toEqual expected
it 'converts html from multiple lines of markdown', ->
markdown = """
# fatarrow
## Table of Contents
"""
html = @markdownService.convert markdown
expected = """
<h1 id="fatarrow">fatarrow</h1>
<h2 id="tableofcontents">Table of Contents</h2>
"""
expect html
.toEqual expected | 215424 | describe 'markdown', ->
describe 'markdownService', ->
beforeEach module 'app'
beforeEach inject (@markdownService) ->
it 'converts html from a single line of markdown', ->
markdown = """
# fatarrow
"""
html = @markdownService.convert markdown
expected = '<h1 id="fatarrow">fatarrow</h1>'
expect html
.toEqual expected
it 'converts html from multiple lines of markdown', ->
markdown = """
# <NAME>atarrow
## Table of Contents
"""
html = @markdownService.convert markdown
expected = """
<h1 id="fatarrow">fatarrow</h1>
<h2 id="tableofcontents">Table of Contents</h2>
"""
expect html
.toEqual expected | true | describe 'markdown', ->
describe 'markdownService', ->
beforeEach module 'app'
beforeEach inject (@markdownService) ->
it 'converts html from a single line of markdown', ->
markdown = """
# fatarrow
"""
html = @markdownService.convert markdown
expected = '<h1 id="fatarrow">fatarrow</h1>'
expect html
.toEqual expected
it 'converts html from multiple lines of markdown', ->
markdown = """
# PI:NAME:<NAME>END_PIatarrow
## Table of Contents
"""
html = @markdownService.convert markdown
expected = """
<h1 id="fatarrow">fatarrow</h1>
<h2 id="tableofcontents">Table of Contents</h2>
"""
expect html
.toEqual expected |
[
{
"context": "e 'apn'\n\nclass PushServiceAPNS\n tokenFormat: /^[0-9a-f]{64}$/i\n validateToken: (token) ->\n if PushServic",
"end": 72,
"score": 0.8423500061035156,
"start": 64,
"tag": "KEY",
"value": "9a-f]{64"
}
] | lib/pushservices/apns.coffee | Lytro/pushd | 0 | apns = require 'apn'
class PushServiceAPNS
tokenFormat: /^[0-9a-f]{64}$/i
validateToken: (token) ->
if PushServiceAPNS::tokenFormat.test(token)
return token.toLowerCase()
constructor: (conf, @logger, tokenResolver) ->
conf.errorCallback = (errCode, note, device) =>
@logger?.error("APNS Error #{errCode} for subscriber #{device?.subscriberId}")
@driver = new apns.Connection(conf)
@payloadFilter = conf.payloadFilter
@feedback = new apns.Feedback(conf)
# Handle Apple Feedbacks
@feedback.on 'feedback', (feedbackData) =>
@logger?.debug("APNS feedback returned #{feedbackData.length} devices")
feedbackData.forEach (item) =>
tokenResolver 'apns', item.device.toString(), (subscriber) =>
subscriber?.get (info) =>
if info.updated < item.time
@logger?.warn("APNS Automatic unregistration for subscriber #{subscriber.id}")
subscriber.delete()
push: (subscriber, subOptions, payload) ->
subscriber.get (info) =>
note = new apns.Notification()
device = new apns.Device(info.token)
device.subscriberId = subscriber.id # used for error logging
if subOptions?.ignore_message isnt true and alert = payload.localizedMessage(info.lang)
note.alert = alert
badge = parseInt(info.badge)
if payload.incrementBadge
badge += 1
note.badge = badge if not isNaN(badge)
note.sound = payload.sound
if @payloadFilter?
for key, val of payload.data
note.payload[key] = val if key in @payloadFilter
else
note.payload = payload.data
@driver.pushNotification note, device
# On iOS we have to maintain the badge counter on the server
if payload.incrementBadge
subscriber.incr 'badge'
exports.PushServiceAPNS = PushServiceAPNS
| 122056 | apns = require 'apn'
class PushServiceAPNS
tokenFormat: /^[0-<KEY>}$/i
validateToken: (token) ->
if PushServiceAPNS::tokenFormat.test(token)
return token.toLowerCase()
constructor: (conf, @logger, tokenResolver) ->
conf.errorCallback = (errCode, note, device) =>
@logger?.error("APNS Error #{errCode} for subscriber #{device?.subscriberId}")
@driver = new apns.Connection(conf)
@payloadFilter = conf.payloadFilter
@feedback = new apns.Feedback(conf)
# Handle Apple Feedbacks
@feedback.on 'feedback', (feedbackData) =>
@logger?.debug("APNS feedback returned #{feedbackData.length} devices")
feedbackData.forEach (item) =>
tokenResolver 'apns', item.device.toString(), (subscriber) =>
subscriber?.get (info) =>
if info.updated < item.time
@logger?.warn("APNS Automatic unregistration for subscriber #{subscriber.id}")
subscriber.delete()
push: (subscriber, subOptions, payload) ->
subscriber.get (info) =>
note = new apns.Notification()
device = new apns.Device(info.token)
device.subscriberId = subscriber.id # used for error logging
if subOptions?.ignore_message isnt true and alert = payload.localizedMessage(info.lang)
note.alert = alert
badge = parseInt(info.badge)
if payload.incrementBadge
badge += 1
note.badge = badge if not isNaN(badge)
note.sound = payload.sound
if @payloadFilter?
for key, val of payload.data
note.payload[key] = val if key in @payloadFilter
else
note.payload = payload.data
@driver.pushNotification note, device
# On iOS we have to maintain the badge counter on the server
if payload.incrementBadge
subscriber.incr 'badge'
exports.PushServiceAPNS = PushServiceAPNS
| true | apns = require 'apn'
class PushServiceAPNS
tokenFormat: /^[0-PI:KEY:<KEY>END_PI}$/i
validateToken: (token) ->
if PushServiceAPNS::tokenFormat.test(token)
return token.toLowerCase()
constructor: (conf, @logger, tokenResolver) ->
conf.errorCallback = (errCode, note, device) =>
@logger?.error("APNS Error #{errCode} for subscriber #{device?.subscriberId}")
@driver = new apns.Connection(conf)
@payloadFilter = conf.payloadFilter
@feedback = new apns.Feedback(conf)
# Handle Apple Feedbacks
@feedback.on 'feedback', (feedbackData) =>
@logger?.debug("APNS feedback returned #{feedbackData.length} devices")
feedbackData.forEach (item) =>
tokenResolver 'apns', item.device.toString(), (subscriber) =>
subscriber?.get (info) =>
if info.updated < item.time
@logger?.warn("APNS Automatic unregistration for subscriber #{subscriber.id}")
subscriber.delete()
push: (subscriber, subOptions, payload) ->
subscriber.get (info) =>
note = new apns.Notification()
device = new apns.Device(info.token)
device.subscriberId = subscriber.id # used for error logging
if subOptions?.ignore_message isnt true and alert = payload.localizedMessage(info.lang)
note.alert = alert
badge = parseInt(info.badge)
if payload.incrementBadge
badge += 1
note.badge = badge if not isNaN(badge)
note.sound = payload.sound
if @payloadFilter?
for key, val of payload.data
note.payload[key] = val if key in @payloadFilter
else
note.payload = payload.data
@driver.pushNotification note, device
# On iOS we have to maintain the badge counter on the server
if payload.incrementBadge
subscriber.incr 'badge'
exports.PushServiceAPNS = PushServiceAPNS
|
[
{
"context": "verview Rule to flag no-unneeded-ternary\n# @author Gyandeep Singh\n###\n\n'use strict'\n\nastUtils = require '../eslint-",
"end": 78,
"score": 0.9998258352279663,
"start": 64,
"tag": "NAME",
"value": "Gyandeep Singh"
}
] | src/rules/no-unneeded-ternary.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Rule to flag no-unneeded-ternary
# @author Gyandeep Singh
###
'use strict'
astUtils = require '../eslint-ast-utils'
# Operators that always result in a boolean value
BOOLEAN_OPERATORS = new Set [
'=='
'is'
'!='
'isnt'
'>'
'>='
'<'
'<='
'in'
'not in'
'of'
'not of'
'instanceof'
]
OPERATOR_INVERSES =
'==': '!='
'!=': '=='
is: 'isnt'
isnt: 'is'
# Operators like < and >= are not true inverses, since both will return false with NaN.
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'disallow ternary operators when simpler alternatives exist'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/no-unneeded-ternary'
schema: [
type: 'object'
properties:
defaultAssignment:
type: 'boolean'
additionalProperties: no
]
fixable: 'code'
create: (context) ->
options = context.options[0] or {}
defaultAssignment = options.defaultAssignment isnt no
sourceCode = context.getSourceCode()
###*
# Test if the node is a boolean literal
# @param {ASTNode} node - The node to report.
# @returns {boolean} True if the its a boolean literal
# @private
###
isBooleanLiteral = (node) ->
node and node.type is 'Literal' and typeof node.value is 'boolean'
###*
# Creates an expression that represents the boolean inverse of the expression represented by the original node
# @param {ASTNode} node A node representing an expression
# @returns {string} A string representing an inverted expression
###
invertExpression = (node) ->
if (
node.type is 'BinaryExpression' and
Object.prototype.hasOwnProperty.call OPERATOR_INVERSES, node.operator
)
operatorToken = sourceCode.getFirstTokenBetween node.left, node.right, (
token
) ->
token.value is node.operator
text = sourceCode.getText()
return (
text.slice(node.range[0], operatorToken.range[0]) +
OPERATOR_INVERSES[node.operator] +
text.slice operatorToken.range[1], node.range[1]
)
return "!(#{astUtils.getParenthesisedText sourceCode, node})" if (
astUtils.getPrecedence(node) <
astUtils.getPrecedence type: 'UnaryExpression'
)
if node.type is 'UnaryExpression' and node.operator is 'not'
return "!!#{astUtils.getParenthesisedText sourceCode, node.argument}"
"!#{astUtils.getParenthesisedText sourceCode, node}"
###*
# Tests if a given node always evaluates to a boolean value
# @param {ASTNode} node - An expression node
# @returns {boolean} True if it is determined that the node will always evaluate to a boolean value
###
isBooleanExpression = (node) ->
(node.type is 'BinaryExpression' and
BOOLEAN_OPERATORS.has(node.operator)) or
(node.type is 'UnaryExpression' and node.operator in ['!', 'not'])
getLoneExpression = (node) ->
return node unless (
node.type is 'BlockStatement' and
node.body.length is 1 and
node.body[0].type is 'ExpressionStatement'
)
node.body[0].expression
justIdentifierName = (node) ->
expression = getLoneExpression node
return unless expression.type is 'Identifier'
expression.name
###*
# Test if the node matches the pattern id ? id : expression
# @param {ASTNode} node - The ConditionalExpression to check.
# @returns {boolean} True if the pattern is matched, and false otherwise
# @private
###
matchesDefaultAssignment = (node) ->
return unless node.alternate
return unless testIdentifierName = justIdentifierName node.test
return unless (
consequentIdentifierName = justIdentifierName node.consequent
)
testIdentifierName is consequentIdentifierName
checkConditional = (node) ->
if isBooleanLiteral(node.alternate) and isBooleanLiteral node.consequent
context.report {
node
loc: node.consequent.loc.start
message:
'Unnecessary use of boolean literals in conditional expression.'
fix: (fixer) ->
# Replace `foo ? true : true` with just `true`, but don't replace `foo() ? true : true`
return (
if node.test.type is 'Identifier'
fixer.replaceText node, node.consequent.name
else
null
) if node.consequent.value is node.alternate.value
# Replace `foo() ? false : true` with `!(foo())`
return fixer.replaceText node, invertExpression node.test if (
(not node.inverted and node.alternate.value) or
(node.inverted and not node.alternate.value)
)
# Replace `foo ? true : false` with `foo` if `foo` is guaranteed to be a boolean, or `!!foo` otherwise.
fixer.replaceText node,
if isBooleanExpression node.test
astUtils.getParenthesisedText sourceCode, node.test
else
"!#{invertExpression node.test}"
}
else if not defaultAssignment and matchesDefaultAssignment node
context.report {
node
loc: node.consequent.loc.start
message:
'Unnecessary use of conditional expression for default assignment.'
fix: (fixer) ->
alternate = getLoneExpression node.alternate
nodeAlternate = astUtils.getParenthesisedText sourceCode, alternate
if alternate.type in [
'ConditionalExpression'
'IfStatement'
'YieldExpression'
]
isAlternateParenthesised = astUtils.isParenthesised(
sourceCode
alternate
)
nodeAlternate =
if isAlternateParenthesised
nodeAlternate
else
"(#{nodeAlternate})"
fixer.replaceText(
node
"#{astUtils.getParenthesisedText(
sourceCode
node.test
)} or #{nodeAlternate}"
)
}
ConditionalExpression: checkConditional
IfStatement: checkConditional
| 130264 | ###*
# @fileoverview Rule to flag no-unneeded-ternary
# @author <NAME>
###
'use strict'
astUtils = require '../eslint-ast-utils'
# Operators that always result in a boolean value
BOOLEAN_OPERATORS = new Set [
'=='
'is'
'!='
'isnt'
'>'
'>='
'<'
'<='
'in'
'not in'
'of'
'not of'
'instanceof'
]
OPERATOR_INVERSES =
'==': '!='
'!=': '=='
is: 'isnt'
isnt: 'is'
# Operators like < and >= are not true inverses, since both will return false with NaN.
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'disallow ternary operators when simpler alternatives exist'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/no-unneeded-ternary'
schema: [
type: 'object'
properties:
defaultAssignment:
type: 'boolean'
additionalProperties: no
]
fixable: 'code'
create: (context) ->
options = context.options[0] or {}
defaultAssignment = options.defaultAssignment isnt no
sourceCode = context.getSourceCode()
###*
# Test if the node is a boolean literal
# @param {ASTNode} node - The node to report.
# @returns {boolean} True if the its a boolean literal
# @private
###
isBooleanLiteral = (node) ->
node and node.type is 'Literal' and typeof node.value is 'boolean'
###*
# Creates an expression that represents the boolean inverse of the expression represented by the original node
# @param {ASTNode} node A node representing an expression
# @returns {string} A string representing an inverted expression
###
invertExpression = (node) ->
if (
node.type is 'BinaryExpression' and
Object.prototype.hasOwnProperty.call OPERATOR_INVERSES, node.operator
)
operatorToken = sourceCode.getFirstTokenBetween node.left, node.right, (
token
) ->
token.value is node.operator
text = sourceCode.getText()
return (
text.slice(node.range[0], operatorToken.range[0]) +
OPERATOR_INVERSES[node.operator] +
text.slice operatorToken.range[1], node.range[1]
)
return "!(#{astUtils.getParenthesisedText sourceCode, node})" if (
astUtils.getPrecedence(node) <
astUtils.getPrecedence type: 'UnaryExpression'
)
if node.type is 'UnaryExpression' and node.operator is 'not'
return "!!#{astUtils.getParenthesisedText sourceCode, node.argument}"
"!#{astUtils.getParenthesisedText sourceCode, node}"
###*
# Tests if a given node always evaluates to a boolean value
# @param {ASTNode} node - An expression node
# @returns {boolean} True if it is determined that the node will always evaluate to a boolean value
###
isBooleanExpression = (node) ->
(node.type is 'BinaryExpression' and
BOOLEAN_OPERATORS.has(node.operator)) or
(node.type is 'UnaryExpression' and node.operator in ['!', 'not'])
getLoneExpression = (node) ->
return node unless (
node.type is 'BlockStatement' and
node.body.length is 1 and
node.body[0].type is 'ExpressionStatement'
)
node.body[0].expression
justIdentifierName = (node) ->
expression = getLoneExpression node
return unless expression.type is 'Identifier'
expression.name
###*
# Test if the node matches the pattern id ? id : expression
# @param {ASTNode} node - The ConditionalExpression to check.
# @returns {boolean} True if the pattern is matched, and false otherwise
# @private
###
matchesDefaultAssignment = (node) ->
return unless node.alternate
return unless testIdentifierName = justIdentifierName node.test
return unless (
consequentIdentifierName = justIdentifierName node.consequent
)
testIdentifierName is consequentIdentifierName
checkConditional = (node) ->
if isBooleanLiteral(node.alternate) and isBooleanLiteral node.consequent
context.report {
node
loc: node.consequent.loc.start
message:
'Unnecessary use of boolean literals in conditional expression.'
fix: (fixer) ->
# Replace `foo ? true : true` with just `true`, but don't replace `foo() ? true : true`
return (
if node.test.type is 'Identifier'
fixer.replaceText node, node.consequent.name
else
null
) if node.consequent.value is node.alternate.value
# Replace `foo() ? false : true` with `!(foo())`
return fixer.replaceText node, invertExpression node.test if (
(not node.inverted and node.alternate.value) or
(node.inverted and not node.alternate.value)
)
# Replace `foo ? true : false` with `foo` if `foo` is guaranteed to be a boolean, or `!!foo` otherwise.
fixer.replaceText node,
if isBooleanExpression node.test
astUtils.getParenthesisedText sourceCode, node.test
else
"!#{invertExpression node.test}"
}
else if not defaultAssignment and matchesDefaultAssignment node
context.report {
node
loc: node.consequent.loc.start
message:
'Unnecessary use of conditional expression for default assignment.'
fix: (fixer) ->
alternate = getLoneExpression node.alternate
nodeAlternate = astUtils.getParenthesisedText sourceCode, alternate
if alternate.type in [
'ConditionalExpression'
'IfStatement'
'YieldExpression'
]
isAlternateParenthesised = astUtils.isParenthesised(
sourceCode
alternate
)
nodeAlternate =
if isAlternateParenthesised
nodeAlternate
else
"(#{nodeAlternate})"
fixer.replaceText(
node
"#{astUtils.getParenthesisedText(
sourceCode
node.test
)} or #{nodeAlternate}"
)
}
ConditionalExpression: checkConditional
IfStatement: checkConditional
| true | ###*
# @fileoverview Rule to flag no-unneeded-ternary
# @author PI:NAME:<NAME>END_PI
###
'use strict'
astUtils = require '../eslint-ast-utils'
# Operators that always result in a boolean value
BOOLEAN_OPERATORS = new Set [
'=='
'is'
'!='
'isnt'
'>'
'>='
'<'
'<='
'in'
'not in'
'of'
'not of'
'instanceof'
]
OPERATOR_INVERSES =
'==': '!='
'!=': '=='
is: 'isnt'
isnt: 'is'
# Operators like < and >= are not true inverses, since both will return false with NaN.
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'disallow ternary operators when simpler alternatives exist'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/no-unneeded-ternary'
schema: [
type: 'object'
properties:
defaultAssignment:
type: 'boolean'
additionalProperties: no
]
fixable: 'code'
create: (context) ->
options = context.options[0] or {}
defaultAssignment = options.defaultAssignment isnt no
sourceCode = context.getSourceCode()
###*
# Test if the node is a boolean literal
# @param {ASTNode} node - The node to report.
# @returns {boolean} True if the its a boolean literal
# @private
###
isBooleanLiteral = (node) ->
node and node.type is 'Literal' and typeof node.value is 'boolean'
###*
# Creates an expression that represents the boolean inverse of the expression represented by the original node
# @param {ASTNode} node A node representing an expression
# @returns {string} A string representing an inverted expression
###
invertExpression = (node) ->
if (
node.type is 'BinaryExpression' and
Object.prototype.hasOwnProperty.call OPERATOR_INVERSES, node.operator
)
operatorToken = sourceCode.getFirstTokenBetween node.left, node.right, (
token
) ->
token.value is node.operator
text = sourceCode.getText()
return (
text.slice(node.range[0], operatorToken.range[0]) +
OPERATOR_INVERSES[node.operator] +
text.slice operatorToken.range[1], node.range[1]
)
return "!(#{astUtils.getParenthesisedText sourceCode, node})" if (
astUtils.getPrecedence(node) <
astUtils.getPrecedence type: 'UnaryExpression'
)
if node.type is 'UnaryExpression' and node.operator is 'not'
return "!!#{astUtils.getParenthesisedText sourceCode, node.argument}"
"!#{astUtils.getParenthesisedText sourceCode, node}"
###*
# Tests if a given node always evaluates to a boolean value
# @param {ASTNode} node - An expression node
# @returns {boolean} True if it is determined that the node will always evaluate to a boolean value
###
isBooleanExpression = (node) ->
(node.type is 'BinaryExpression' and
BOOLEAN_OPERATORS.has(node.operator)) or
(node.type is 'UnaryExpression' and node.operator in ['!', 'not'])
getLoneExpression = (node) ->
return node unless (
node.type is 'BlockStatement' and
node.body.length is 1 and
node.body[0].type is 'ExpressionStatement'
)
node.body[0].expression
justIdentifierName = (node) ->
expression = getLoneExpression node
return unless expression.type is 'Identifier'
expression.name
###*
# Test if the node matches the pattern id ? id : expression
# @param {ASTNode} node - The ConditionalExpression to check.
# @returns {boolean} True if the pattern is matched, and false otherwise
# @private
###
matchesDefaultAssignment = (node) ->
return unless node.alternate
return unless testIdentifierName = justIdentifierName node.test
return unless (
consequentIdentifierName = justIdentifierName node.consequent
)
testIdentifierName is consequentIdentifierName
checkConditional = (node) ->
if isBooleanLiteral(node.alternate) and isBooleanLiteral node.consequent
context.report {
node
loc: node.consequent.loc.start
message:
'Unnecessary use of boolean literals in conditional expression.'
fix: (fixer) ->
# Replace `foo ? true : true` with just `true`, but don't replace `foo() ? true : true`
return (
if node.test.type is 'Identifier'
fixer.replaceText node, node.consequent.name
else
null
) if node.consequent.value is node.alternate.value
# Replace `foo() ? false : true` with `!(foo())`
return fixer.replaceText node, invertExpression node.test if (
(not node.inverted and node.alternate.value) or
(node.inverted and not node.alternate.value)
)
# Replace `foo ? true : false` with `foo` if `foo` is guaranteed to be a boolean, or `!!foo` otherwise.
fixer.replaceText node,
if isBooleanExpression node.test
astUtils.getParenthesisedText sourceCode, node.test
else
"!#{invertExpression node.test}"
}
else if not defaultAssignment and matchesDefaultAssignment node
context.report {
node
loc: node.consequent.loc.start
message:
'Unnecessary use of conditional expression for default assignment.'
fix: (fixer) ->
alternate = getLoneExpression node.alternate
nodeAlternate = astUtils.getParenthesisedText sourceCode, alternate
if alternate.type in [
'ConditionalExpression'
'IfStatement'
'YieldExpression'
]
isAlternateParenthesised = astUtils.isParenthesised(
sourceCode
alternate
)
nodeAlternate =
if isAlternateParenthesised
nodeAlternate
else
"(#{nodeAlternate})"
fixer.replaceText(
node
"#{astUtils.getParenthesisedText(
sourceCode
node.test
)} or #{nodeAlternate}"
)
}
ConditionalExpression: checkConditional
IfStatement: checkConditional
|
[
{
"context": " @[setting] = value\n\nclass User\n constructor: (@name, @slack, @salary, @timetable, @row = null) ->\n ",
"end": 2432,
"score": 0.9973101019859314,
"start": 2428,
"tag": "USERNAME",
"value": "name"
},
{
"context": "verageLogged)\n user = new User(temp.name, temp... | src/models/user.coffee | fangamer/ibizan | 0 |
moment = require 'moment-timezone'
Q = require 'q'
{ HEADERS, TIMEZONE } = require '../helpers/constants'
Logger = require('../helpers/logger')()
getPositiveNumber = (input, current) ->
if not current
current = 0
if not input
return current
if not isNaN input
# number
if input >= 0
return input
return 0
return current
class Timetable
constructor: (@start, @end, @timezone) ->
if typeof @timezone is 'string'
@timezone = moment.tz.zone(@timezone)
@startRaw = @start
@endRaw = @end
@start = moment.tz(@start, 'hh:mm a', @timezone.name)
@end = moment.tz(@end, 'hh:mm a', @timezone.name)
activeHours: ->
now = moment.tz @timezone.name
start = @start.year(now.year()).dayOfYear(now.dayOfYear())
end = @end.year(now.year()).dayOfYear(now.dayOfYear())
[start, end]
activeTime: ->
rawTime = +(@end.diff(@start, 'hours', true).toFixed(2))
return Math.min(8, rawTime)
toDays: (hours) ->
return hours / @activeTime()
setVacation: (total, available) ->
@vacationTotal = getPositiveNumber(total, @vacationTotal)
@vacationAvailable = getPositiveNumber(available, @vacationAvailable)
setSick: (total, available) ->
@sickTotal = getPositiveNumber(total, @sickTotal)
@sickAvailable = getPositiveNumber(available, @sickAvailable)
setUnpaid: (total) ->
@unpaidTotal = getPositiveNumber(total, @unpaidTotal)
setLogged: (total) ->
@loggedTotal = getPositiveNumber(total, @loggedTotal)
setAverageLogged: (average) ->
@averageLoggedTotal = getPositiveNumber(average, @averageLoggedTotal)
setTimezone: (timezone) ->
@timezone = timezone
@start = moment.tz(@startRaw, 'hh:mm a', @timezone.name)
@end = moment.tz(@endRaw, 'hh:mm a', @timezone.name)
setStart: (start) ->
@startRaw = start
@start = moment.tz(@startRaw, 'hh:mm a', @timezone.name)
setEnd: (end) ->
@endRaw = end
@end = moment.tz(@endRaw, 'hh:mm a', @timezone.name)
class Settings
constructor: () ->
@shouldHound = true
@shouldResetHound = true
@houndFrequency = -1
@lastMessage = null
@lastPing = null
@fromSettings: (settings) ->
newSetting = new Settings()
newSetting.fromSettings settings
newSetting
fromSettings: (opts) ->
if not opts or
typeof opts isnt 'object'
return
for setting, value of opts
@[setting] = value
class User
constructor: (@name, @slack, @salary, @timetable, @row = null) ->
@punches = []
@taxType = 'W2'
@parse: (row) ->
headers = HEADERS.users
temp = {}
for key, header of headers
if header is headers.start or header is headers.end
row[header] = row[header].toLowerCase()
if row[header] is 'midnight'
row[header] = '12:00 am'
else if row[header] is 'noon'
row[header] = '12:00 pm'
temp[key] = row[header]
else if header is headers.salary
temp[key] = row[header] is 'Y'
else if header is headers.timezone
if zone = moment.tz.zone row[header]
temp[key] = zone
else
temp[key] = row[header]
else if header is headers.shouldHound
temp[key] = row[header] is 'Y'
else if header is headers.taxType
temp.taxType = row[header] || 'W2'
else if header is headers.houndFrequency
temp[key] = row[header] || -1
if temp[key] is -1
temp.shouldResetHound = false
else
temp.shouldResetHound = true
else if header is headers.overtime
continue
else if header is headers.lastPing
tz = TIMEZONE
if temp.timezone
tz = temp.timezone.name
lastPing = moment.tz(row[header], 'MM/DD/YYYY hh:mm:ss A', tz)
if lastPing.isValid()
temp[key] = lastPing
else
temp[key] = moment.tz(tz).subtract(1, 'days')
else
if isNaN row[header]
temp[key] = row[header].trim()
else
temp[key] = parseFloat row[header]
timetable = new Timetable(temp.start, temp.end, temp.timezone)
timetable.setVacation(temp.vacationLogged, temp.vacationAvailable)
timetable.setSick(temp.sickLogged, temp.sickAvailable)
timetable.setUnpaid(temp.unpaidLogged)
timetable.setLogged(temp.totalLogged)
timetable.setAverageLogged(temp.averageLogged)
user = new User(temp.name, temp.slackname, temp.salary, timetable, row)
user.settings = Settings.fromSettings {
shouldHound: temp.shouldHound,
shouldResetHound: temp.shouldResetHound,
houndFrequency: temp.houndFrequency,
lastMessage: null,
lastPing: temp.lastPing
}
return user
activeHours: ->
return @timetable.activeHours()
activeTime: ->
return @timetable.activeTime()
setTimezone: (timezone) ->
tz = moment.tz.zone(timezone)
if tz
@timetable.setTimezone(tz)
@updateRow()
return tz
setStart: (start) ->
time = moment(start, 'h:mm A')
if time
@timetable.setStart(time)
@updateRow()
return time
setEnd: (end) ->
time = moment(end, 'h:mm A')
if time
@timetable.setEnd(time)
@updateRow()
return time
toDays: (hours) ->
return @timetable.toDays hours
isInactive: (current) ->
current = current || moment.tz(@timetable.timezone.name)
[start, end] = @activeHours()
if current.holiday()?
return true
else if current.isBetween(start, end)
return false
else
return true
lastPunch: (modes) ->
if typeof modes is 'string'
modes = [modes]
if not modes || modes.length is 0
return @punches.slice(-1)[0]
if @punches and @punches.length > 0
len = @punches.length
for i in [len-1..0]
last = @punches[i]
if 'in' in modes and not 'out' in modes and last.mode is 'out'
return
else if last.mode in modes
return last
return
lastPunchTime: ->
if @punches.length > 0
punch = @lastPunch()
if punch.times.length > 0
time = punch.times.slice(-1)[0]
if time.isSame(moment(), 'day')
date = 'today'
else if time.isSame(moment().subtract(1, 'days'), 'day')
date = 'yesterday'
else
date = 'on ' + time.format('MMM Do')
return "#{date}, #{time.format('h:mm a')}"
else if punch.times.block
if punch.mode is 'none'
type = ' '
else if punch.mode is 'vacation' or
punch.mode is 'sick' or
punch.mode is 'unpaid'
type = punch.mode + ' '
return "a #{punch.times.block} hour #{type}block punch"
return "never"
undoPunch: () ->
deferred = Q.defer()
lastPunch = @lastPunch()
that = @
Logger.log "Undoing #{that.slack}'s punch: #{lastPunch.description(that)}"
if lastPunch.times.block
elapsed = lastPunch.times.block
else
elapsed = lastPunch.elapsed || 0
headers = HEADERS.rawdata
if lastPunch.mode is 'vacation' or
lastPunch.mode is 'sick' or
lastPunch.mode is 'unpaid' or
lastPunch.mode is 'none'
deletePromise = Q.nfbind(lastPunch.row.del.bind(lastPunch))
deletePromise()
.then(() ->
punch = that.punches.pop()
elapsedDays = that.toDays elapsed
if punch.mode is 'vacation'
total = that.timetable.vacationTotal
available = that.timetable.vacationAvailable
that.timetable.setVacation(total - elapsedDays,
available + elapsedDays)
else if punch.mode is 'sick'
total = that.timetable.sickTotal
available = that.timetable.sickAvailable
that.timetable.setSick(total - elapsedDays, available + elapsedDays)
else if punch.mode is 'unpaid'
total = that.timetable.unpaidTotal
that.timetable.setUnpaid(total - elapsedDays)
else
logged = that.timetable.loggedTotal
that.timetable.setLogged(logged - elapsed)
deferred.resolve(punch)
)
else if lastPunch.mode is 'out'
# projects will not be touched
lastPunch.times.pop()
lastPunch.elapsed = null
if lastPunch.notes.lastIndexOf("\n") > 0
lastPunch.notes = lastPunch.notes
.substring(0, lastPunch.notes.lastIndexOf("\n"))
lastPunch.mode = 'in'
lastPunch.row[headers.out] =
lastPunch.row[headers.totalTime] =
lastPunch.row[headers.blockTime] = ''
lastPunch.row[headers.notes] = lastPunch.notes
savePromise = Q.nfbind(lastPunch.row.save.bind(lastPunch))
savePromise()
.then(() ->
logged = that.timetable.loggedTotal
that.timetable.setLogged(logged - elapsed)
deferred.resolve(lastPunch)
)
else if lastPunch.mode is 'in'
deletePromise = Q.nfbind(lastPunch.row.del.bind(lastPunch))
deletePromise()
.then(() ->
punch = that.punches.pop()
deferred.resolve(punch)
)
deferred.promise
toRawPayroll: (start, end) ->
headers = HEADERS.payrollreports
row = {}
row[headers.date] = moment.tz(TIMEZONE).format('M/DD/YYYY')
firstName = @name.split(' ').slice(0, -1).join(' ')
lastName = @name.split(' ').slice(-1)
row[headers.name] = lastName + ', ' + firstName
loggedTime = unpaidTime = vacationTime = sickTime = 0
projectsForPeriod = []
for punch in @punches
if punch.date.isBefore(start) or punch.date.isAfter(end)
continue
else if not punch.elapsed and not punch.times.block
continue
else if punch.mode is 'in'
continue
else if punch.mode is 'vacation'
if punch.times.block
vacationTime += punch.times.block
else
vacationTime += punch.elapsed
else if punch.mode is 'unpaid'
if punch.times.block
unpaidTime += punch.times.block
else
unpaidTime += punch.elapsed
else if punch.mode is 'sick'
if punch.times.block
sickTime += punch.times.block
else
sickTime += punch.elapsed
else
if punch.times.block
loggedTime += punch.times.block
else
loggedTime += punch.elapsed
if punch.projects? and punch.projects?.length > 0
for project in punch.projects
match = projectsForPeriod.filter((item, index, arr) ->
return project.name is item.name
)[0]
if not match
projectsForPeriod.push project
loggedTime = +loggedTime.toFixed(2)
vacationTime = +vacationTime.toFixed(2)
sickTime = +sickTime.toFixed(2)
unpaidTime = +unpaidTime.toFixed(2)
holidayTime = @timetable.holiday || 0
if @salary
paidTime = Math.min(80, loggedTime + vacationTime + sickTime + holidayTime)
row[headers.paid] = if paidTime > 0 then paidTime else ''
row[headers.unpaid] = if unpaidTime > 0 then unpaidTime else ''
row[headers.vacation] = if vacationTime > 0 then vacationTime else ''
row[headers.sick] = if sickTime > 0 then sickTime else ''
# row[headers.salary] = '=MIN(80,MINUS(80,SUM(D1,H1:K1)))'
else
paidTime = loggedTime
row[headers.paid] = if paidTime > 0 then paidTime else ''
# row[headers.salary] = '=MIN(80,MINUS(C1,SUM(D1,H1:K1)))'
row[headers.logged] = loggedTime
overTime = Math.max(0, loggedTime - 80)
row[headers.overtime] = if overTime > 0 then overTime else ''
row[headers.holiday] = if holidayTime > 0 then holidayTime else ''
row.extra = {
slack: @slack,
projects: projectsForPeriod
}
row
updateRow: () ->
deferred = Q.defer()
if @row?
headers = HEADERS.users
@row[headers.start] = @timetable.start.format('h:mm A')
@row[headers.end] = @timetable.end.format('h:mm A')
@row[headers.timezone] = @timetable.timezone.name
@row[headers.shouldHound] = if @settings?.shouldHound then 'Y' else 'N'
@row[headers.houndFrequency] = if @settings?.houndFrequency then @settings.houndFrequency else -1
@row[headers.vacationAvailable] = @timetable.vacationAvailable
@row[headers.vacationLogged] = @timetable.vacationTotal
@row[headers.sickAvailable] = @timetable.sickAvailable
@row[headers.sickLogged] = @timetable.sickTotal
@row[headers.unpaidLogged] = @timetable.unpaidTotal
@row[headers.overtime] = Math.max(0, @timetable.loggedTotal - 80)
@row[headers.totalLogged] = @timetable.loggedTotal
@row[headers.averageLogged] = @timetable.averageLoggedTotal
@row[headers.lastPing] = if @settings?.lastPing then moment.tz(@settings.lastPing, @timetable.timezone.name).format('MM/DD/YYYY hh:mm:ss A') else moment.tz(@timetable.timezone.name).format('MM/DD/YYYY hh:mm:ss A')
@row.save (err) ->
if err
deferred.reject err
else
deferred.resolve true
else
deferred.reject 'Row is null'
deferred.promise
directMessage: (msg, logger=Logger, attachment) ->
logger.logToChannel msg, @slack, attachment, true
hound: (msg, logger=Logger) ->
now = moment.tz TIMEZONE
@settings?.lastPing = now
me = @
if not @salary and @settings?.houndFrequency > 0
msg = "You have been on the clock for
#{@settings.houndFrequency} hours.\n" + msg
setTimeout ->
me.directMessage msg, logger
, 1000 * (Math.floor(Math.random() * 3) + 1)
Logger.log "Hounded #{@slack} with '#{msg}'"
@updateRow()
hexColor: ->
hash = 0
for i in [0...@slack.length]
hash = @slack.charCodeAt(i) + ((hash << 3) - hash)
color = Math.abs(hash).toString(16).substring(0, 6)
hexColor = "#" + '000000'.substring(0, 6 - color.length) + color
return hexColor
slackAttachment: () ->
fields = []
statusString = "#{if @salary then 'Salary' else 'Hourly'} -
Active #{@timetable.start.format('h:mm a')} to
#{@timetable.end.format('h:mm a z')}"
lastPunch = @lastPunch()
if lastPunch
lastPunchField =
title: "Last Punch"
value: "#{lastPunch.description(@)}"
short: true
fields.push lastPunchField
houndString = "#{if @settings?.shouldHound then 'On' else 'Off'}"
if @settings?.shouldHound
houndString += " (#{@settings?.houndFrequency} hours)"
houndField =
title: "Hounding"
value: houndString
short: true
fields.push houndField
if @salary
vacationDaysField =
title: "Vacation Days"
value: "#{@timetable.vacationAvailable} available,
#{@timetable.vacationTotal} used"
short: true
fields.push vacationDaysField
sickDaysField =
title: "Sick Days"
value: "#{@timetable.sickAvailable} available,
#{@timetable.sickTotal} used"
short: true
fields.push sickDaysField
if @unpaidTotal > 0
unpaidField =
title: "Unpaid Days"
value: "#{@timetable.unpaidTotal} used"
short: true
fields.push unpaidField
attachment =
title: @name + " (@" + @slack + ")",
text: statusString,
fallback: @name.replace(/\W/g, '') + " @" + @slack.replace(/\W/g, '')
color: @hexColor()
fields: fields
return attachment
description: () ->
return "User: #{@name} (#{@slack})\n
They have #{(@punches || []).length} punches on record\n
Last punch was #{@lastPunchTime()}\n
Their active hours are from #{@timetable.start.format('h:mm a')} to
#{@timetable.end.format('h:mm a')}\n
They are in #{@timetable.timezone.name}\n
The last time they sent a message was
#{+(moment.tz(TIMEZONE).diff(@settings?.lastMessage?.time, 'hours', true).toFixed(2))} hours ago"
module.exports.User = User
module.exports.Settings = Settings
module.exports.Timetable = Timetable
| 161031 |
moment = require 'moment-timezone'
Q = require 'q'
{ HEADERS, TIMEZONE } = require '../helpers/constants'
Logger = require('../helpers/logger')()
getPositiveNumber = (input, current) ->
if not current
current = 0
if not input
return current
if not isNaN input
# number
if input >= 0
return input
return 0
return current
class Timetable
constructor: (@start, @end, @timezone) ->
if typeof @timezone is 'string'
@timezone = moment.tz.zone(@timezone)
@startRaw = @start
@endRaw = @end
@start = moment.tz(@start, 'hh:mm a', @timezone.name)
@end = moment.tz(@end, 'hh:mm a', @timezone.name)
activeHours: ->
now = moment.tz @timezone.name
start = @start.year(now.year()).dayOfYear(now.dayOfYear())
end = @end.year(now.year()).dayOfYear(now.dayOfYear())
[start, end]
activeTime: ->
rawTime = +(@end.diff(@start, 'hours', true).toFixed(2))
return Math.min(8, rawTime)
toDays: (hours) ->
return hours / @activeTime()
setVacation: (total, available) ->
@vacationTotal = getPositiveNumber(total, @vacationTotal)
@vacationAvailable = getPositiveNumber(available, @vacationAvailable)
setSick: (total, available) ->
@sickTotal = getPositiveNumber(total, @sickTotal)
@sickAvailable = getPositiveNumber(available, @sickAvailable)
setUnpaid: (total) ->
@unpaidTotal = getPositiveNumber(total, @unpaidTotal)
setLogged: (total) ->
@loggedTotal = getPositiveNumber(total, @loggedTotal)
setAverageLogged: (average) ->
@averageLoggedTotal = getPositiveNumber(average, @averageLoggedTotal)
setTimezone: (timezone) ->
@timezone = timezone
@start = moment.tz(@startRaw, 'hh:mm a', @timezone.name)
@end = moment.tz(@endRaw, 'hh:mm a', @timezone.name)
setStart: (start) ->
@startRaw = start
@start = moment.tz(@startRaw, 'hh:mm a', @timezone.name)
setEnd: (end) ->
@endRaw = end
@end = moment.tz(@endRaw, 'hh:mm a', @timezone.name)
class Settings
constructor: () ->
@shouldHound = true
@shouldResetHound = true
@houndFrequency = -1
@lastMessage = null
@lastPing = null
@fromSettings: (settings) ->
newSetting = new Settings()
newSetting.fromSettings settings
newSetting
fromSettings: (opts) ->
if not opts or
typeof opts isnt 'object'
return
for setting, value of opts
@[setting] = value
class User
constructor: (@name, @slack, @salary, @timetable, @row = null) ->
@punches = []
@taxType = 'W2'
@parse: (row) ->
headers = HEADERS.users
temp = {}
for key, header of headers
if header is headers.start or header is headers.end
row[header] = row[header].toLowerCase()
if row[header] is 'midnight'
row[header] = '12:00 am'
else if row[header] is 'noon'
row[header] = '12:00 pm'
temp[key] = row[header]
else if header is headers.salary
temp[key] = row[header] is 'Y'
else if header is headers.timezone
if zone = moment.tz.zone row[header]
temp[key] = zone
else
temp[key] = row[header]
else if header is headers.shouldHound
temp[key] = row[header] is 'Y'
else if header is headers.taxType
temp.taxType = row[header] || 'W2'
else if header is headers.houndFrequency
temp[key] = row[header] || -1
if temp[key] is -1
temp.shouldResetHound = false
else
temp.shouldResetHound = true
else if header is headers.overtime
continue
else if header is headers.lastPing
tz = TIMEZONE
if temp.timezone
tz = temp.timezone.name
lastPing = moment.tz(row[header], 'MM/DD/YYYY hh:mm:ss A', tz)
if lastPing.isValid()
temp[key] = lastPing
else
temp[key] = moment.tz(tz).subtract(1, 'days')
else
if isNaN row[header]
temp[key] = row[header].trim()
else
temp[key] = parseFloat row[header]
timetable = new Timetable(temp.start, temp.end, temp.timezone)
timetable.setVacation(temp.vacationLogged, temp.vacationAvailable)
timetable.setSick(temp.sickLogged, temp.sickAvailable)
timetable.setUnpaid(temp.unpaidLogged)
timetable.setLogged(temp.totalLogged)
timetable.setAverageLogged(temp.averageLogged)
user = new User(temp.name, temp.<NAME>name, temp.salary, timetable, row)
user.settings = Settings.fromSettings {
shouldHound: temp.shouldHound,
shouldResetHound: temp.shouldResetHound,
houndFrequency: temp.houndFrequency,
lastMessage: null,
lastPing: temp.lastPing
}
return user
activeHours: ->
return @timetable.activeHours()
activeTime: ->
return @timetable.activeTime()
setTimezone: (timezone) ->
tz = moment.tz.zone(timezone)
if tz
@timetable.setTimezone(tz)
@updateRow()
return tz
setStart: (start) ->
time = moment(start, 'h:mm A')
if time
@timetable.setStart(time)
@updateRow()
return time
setEnd: (end) ->
time = moment(end, 'h:mm A')
if time
@timetable.setEnd(time)
@updateRow()
return time
toDays: (hours) ->
return @timetable.toDays hours
isInactive: (current) ->
current = current || moment.tz(@timetable.timezone.name)
[start, end] = @activeHours()
if current.holiday()?
return true
else if current.isBetween(start, end)
return false
else
return true
lastPunch: (modes) ->
if typeof modes is 'string'
modes = [modes]
if not modes || modes.length is 0
return @punches.slice(-1)[0]
if @punches and @punches.length > 0
len = @punches.length
for i in [len-1..0]
last = @punches[i]
if 'in' in modes and not 'out' in modes and last.mode is 'out'
return
else if last.mode in modes
return last
return
lastPunchTime: ->
if @punches.length > 0
punch = @lastPunch()
if punch.times.length > 0
time = punch.times.slice(-1)[0]
if time.isSame(moment(), 'day')
date = 'today'
else if time.isSame(moment().subtract(1, 'days'), 'day')
date = 'yesterday'
else
date = 'on ' + time.format('MMM Do')
return "#{date}, #{time.format('h:mm a')}"
else if punch.times.block
if punch.mode is 'none'
type = ' '
else if punch.mode is 'vacation' or
punch.mode is 'sick' or
punch.mode is 'unpaid'
type = punch.mode + ' '
return "a #{punch.times.block} hour #{type}block punch"
return "never"
undoPunch: () ->
deferred = Q.defer()
lastPunch = @lastPunch()
that = @
Logger.log "Undoing #{that.slack}'s punch: #{lastPunch.description(that)}"
if lastPunch.times.block
elapsed = lastPunch.times.block
else
elapsed = lastPunch.elapsed || 0
headers = HEADERS.rawdata
if lastPunch.mode is 'vacation' or
lastPunch.mode is 'sick' or
lastPunch.mode is 'unpaid' or
lastPunch.mode is 'none'
deletePromise = Q.nfbind(lastPunch.row.del.bind(lastPunch))
deletePromise()
.then(() ->
punch = that.punches.pop()
elapsedDays = that.toDays elapsed
if punch.mode is 'vacation'
total = that.timetable.vacationTotal
available = that.timetable.vacationAvailable
that.timetable.setVacation(total - elapsedDays,
available + elapsedDays)
else if punch.mode is 'sick'
total = that.timetable.sickTotal
available = that.timetable.sickAvailable
that.timetable.setSick(total - elapsedDays, available + elapsedDays)
else if punch.mode is 'unpaid'
total = that.timetable.unpaidTotal
that.timetable.setUnpaid(total - elapsedDays)
else
logged = that.timetable.loggedTotal
that.timetable.setLogged(logged - elapsed)
deferred.resolve(punch)
)
else if lastPunch.mode is 'out'
# projects will not be touched
lastPunch.times.pop()
lastPunch.elapsed = null
if lastPunch.notes.lastIndexOf("\n") > 0
lastPunch.notes = lastPunch.notes
.substring(0, lastPunch.notes.lastIndexOf("\n"))
lastPunch.mode = 'in'
lastPunch.row[headers.out] =
lastPunch.row[headers.totalTime] =
lastPunch.row[headers.blockTime] = ''
lastPunch.row[headers.notes] = lastPunch.notes
savePromise = Q.nfbind(lastPunch.row.save.bind(lastPunch))
savePromise()
.then(() ->
logged = that.timetable.loggedTotal
that.timetable.setLogged(logged - elapsed)
deferred.resolve(lastPunch)
)
else if lastPunch.mode is 'in'
deletePromise = Q.nfbind(lastPunch.row.del.bind(lastPunch))
deletePromise()
.then(() ->
punch = that.punches.pop()
deferred.resolve(punch)
)
deferred.promise
toRawPayroll: (start, end) ->
headers = HEADERS.payrollreports
row = {}
row[headers.date] = moment.tz(TIMEZONE).format('M/DD/YYYY')
firstName = @name.split(' ').slice(0, -1).join(' ')
lastName = @name.split(' ').slice(-1)
row[headers.name] = lastName + ', ' + firstName
loggedTime = unpaidTime = vacationTime = sickTime = 0
projectsForPeriod = []
for punch in @punches
if punch.date.isBefore(start) or punch.date.isAfter(end)
continue
else if not punch.elapsed and not punch.times.block
continue
else if punch.mode is 'in'
continue
else if punch.mode is 'vacation'
if punch.times.block
vacationTime += punch.times.block
else
vacationTime += punch.elapsed
else if punch.mode is 'unpaid'
if punch.times.block
unpaidTime += punch.times.block
else
unpaidTime += punch.elapsed
else if punch.mode is 'sick'
if punch.times.block
sickTime += punch.times.block
else
sickTime += punch.elapsed
else
if punch.times.block
loggedTime += punch.times.block
else
loggedTime += punch.elapsed
if punch.projects? and punch.projects?.length > 0
for project in punch.projects
match = projectsForPeriod.filter((item, index, arr) ->
return project.name is item.name
)[0]
if not match
projectsForPeriod.push project
loggedTime = +loggedTime.toFixed(2)
vacationTime = +vacationTime.toFixed(2)
sickTime = +sickTime.toFixed(2)
unpaidTime = +unpaidTime.toFixed(2)
holidayTime = @timetable.holiday || 0
if @salary
paidTime = Math.min(80, loggedTime + vacationTime + sickTime + holidayTime)
row[headers.paid] = if paidTime > 0 then paidTime else ''
row[headers.unpaid] = if unpaidTime > 0 then unpaidTime else ''
row[headers.vacation] = if vacationTime > 0 then vacationTime else ''
row[headers.sick] = if sickTime > 0 then sickTime else ''
# row[headers.salary] = '=MIN(80,MINUS(80,SUM(D1,H1:K1)))'
else
paidTime = loggedTime
row[headers.paid] = if paidTime > 0 then paidTime else ''
# row[headers.salary] = '=MIN(80,MINUS(C1,SUM(D1,H1:K1)))'
row[headers.logged] = loggedTime
overTime = Math.max(0, loggedTime - 80)
row[headers.overtime] = if overTime > 0 then overTime else ''
row[headers.holiday] = if holidayTime > 0 then holidayTime else ''
row.extra = {
slack: @slack,
projects: projectsForPeriod
}
row
updateRow: () ->
deferred = Q.defer()
if @row?
headers = HEADERS.users
@row[headers.start] = @timetable.start.format('h:mm A')
@row[headers.end] = @timetable.end.format('h:mm A')
@row[headers.timezone] = @timetable.timezone.name
@row[headers.shouldHound] = if @settings?.shouldHound then 'Y' else 'N'
@row[headers.houndFrequency] = if @settings?.houndFrequency then @settings.houndFrequency else -1
@row[headers.vacationAvailable] = @timetable.vacationAvailable
@row[headers.vacationLogged] = @timetable.vacationTotal
@row[headers.sickAvailable] = @timetable.sickAvailable
@row[headers.sickLogged] = @timetable.sickTotal
@row[headers.unpaidLogged] = @timetable.unpaidTotal
@row[headers.overtime] = Math.max(0, @timetable.loggedTotal - 80)
@row[headers.totalLogged] = @timetable.loggedTotal
@row[headers.averageLogged] = @timetable.averageLoggedTotal
@row[headers.lastPing] = if @settings?.lastPing then moment.tz(@settings.lastPing, @timetable.timezone.name).format('MM/DD/YYYY hh:mm:ss A') else moment.tz(@timetable.timezone.name).format('MM/DD/YYYY hh:mm:ss A')
@row.save (err) ->
if err
deferred.reject err
else
deferred.resolve true
else
deferred.reject 'Row is null'
deferred.promise
directMessage: (msg, logger=Logger, attachment) ->
logger.logToChannel msg, @slack, attachment, true
hound: (msg, logger=Logger) ->
now = moment.tz TIMEZONE
@settings?.lastPing = now
me = @
if not @salary and @settings?.houndFrequency > 0
msg = "You have been on the clock for
#{@settings.houndFrequency} hours.\n" + msg
setTimeout ->
me.directMessage msg, logger
, 1000 * (Math.floor(Math.random() * 3) + 1)
Logger.log "Hounded #{@slack} with '#{msg}'"
@updateRow()
hexColor: ->
hash = 0
for i in [0...@slack.length]
hash = @slack.charCodeAt(i) + ((hash << 3) - hash)
color = Math.abs(hash).toString(16).substring(0, 6)
hexColor = "#" + '000000'.substring(0, 6 - color.length) + color
return hexColor
slackAttachment: () ->
fields = []
statusString = "#{if @salary then 'Salary' else 'Hourly'} -
Active #{@timetable.start.format('h:mm a')} to
#{@timetable.end.format('h:mm a z')}"
lastPunch = @lastPunch()
if lastPunch
lastPunchField =
title: "Last Punch"
value: "#{lastPunch.description(@)}"
short: true
fields.push lastPunchField
houndString = "#{if @settings?.shouldHound then 'On' else 'Off'}"
if @settings?.shouldHound
houndString += " (#{@settings?.houndFrequency} hours)"
houndField =
title: "Hounding"
value: houndString
short: true
fields.push houndField
if @salary
vacationDaysField =
title: "Vacation Days"
value: "#{@timetable.vacationAvailable} available,
#{@timetable.vacationTotal} used"
short: true
fields.push vacationDaysField
sickDaysField =
title: "Sick Days"
value: "#{@timetable.sickAvailable} available,
#{@timetable.sickTotal} used"
short: true
fields.push sickDaysField
if @unpaidTotal > 0
unpaidField =
title: "Unpaid Days"
value: "#{@timetable.unpaidTotal} used"
short: true
fields.push unpaidField
attachment =
title: @name + " (@" + @slack + ")",
text: statusString,
fallback: @name.replace(/\W/g, '') + " @" + @slack.replace(/\W/g, '')
color: @hexColor()
fields: fields
return attachment
description: () ->
return "User: #{@name} (#{@slack})\n
They have #{(@punches || []).length} punches on record\n
Last punch was #{@lastPunchTime()}\n
Their active hours are from #{@timetable.start.format('h:mm a')} to
#{@timetable.end.format('h:mm a')}\n
They are in #{@timetable.timezone.name}\n
The last time they sent a message was
#{+(moment.tz(TIMEZONE).diff(@settings?.lastMessage?.time, 'hours', true).toFixed(2))} hours ago"
module.exports.User = User
module.exports.Settings = Settings
module.exports.Timetable = Timetable
| true |
moment = require 'moment-timezone'
Q = require 'q'
{ HEADERS, TIMEZONE } = require '../helpers/constants'
Logger = require('../helpers/logger')()
getPositiveNumber = (input, current) ->
if not current
current = 0
if not input
return current
if not isNaN input
# number
if input >= 0
return input
return 0
return current
class Timetable
constructor: (@start, @end, @timezone) ->
if typeof @timezone is 'string'
@timezone = moment.tz.zone(@timezone)
@startRaw = @start
@endRaw = @end
@start = moment.tz(@start, 'hh:mm a', @timezone.name)
@end = moment.tz(@end, 'hh:mm a', @timezone.name)
activeHours: ->
now = moment.tz @timezone.name
start = @start.year(now.year()).dayOfYear(now.dayOfYear())
end = @end.year(now.year()).dayOfYear(now.dayOfYear())
[start, end]
activeTime: ->
rawTime = +(@end.diff(@start, 'hours', true).toFixed(2))
return Math.min(8, rawTime)
toDays: (hours) ->
return hours / @activeTime()
setVacation: (total, available) ->
@vacationTotal = getPositiveNumber(total, @vacationTotal)
@vacationAvailable = getPositiveNumber(available, @vacationAvailable)
setSick: (total, available) ->
@sickTotal = getPositiveNumber(total, @sickTotal)
@sickAvailable = getPositiveNumber(available, @sickAvailable)
setUnpaid: (total) ->
@unpaidTotal = getPositiveNumber(total, @unpaidTotal)
setLogged: (total) ->
@loggedTotal = getPositiveNumber(total, @loggedTotal)
setAverageLogged: (average) ->
@averageLoggedTotal = getPositiveNumber(average, @averageLoggedTotal)
setTimezone: (timezone) ->
@timezone = timezone
@start = moment.tz(@startRaw, 'hh:mm a', @timezone.name)
@end = moment.tz(@endRaw, 'hh:mm a', @timezone.name)
setStart: (start) ->
@startRaw = start
@start = moment.tz(@startRaw, 'hh:mm a', @timezone.name)
setEnd: (end) ->
@endRaw = end
@end = moment.tz(@endRaw, 'hh:mm a', @timezone.name)
class Settings
constructor: () ->
@shouldHound = true
@shouldResetHound = true
@houndFrequency = -1
@lastMessage = null
@lastPing = null
@fromSettings: (settings) ->
newSetting = new Settings()
newSetting.fromSettings settings
newSetting
fromSettings: (opts) ->
if not opts or
typeof opts isnt 'object'
return
for setting, value of opts
@[setting] = value
class User
constructor: (@name, @slack, @salary, @timetable, @row = null) ->
@punches = []
@taxType = 'W2'
@parse: (row) ->
headers = HEADERS.users
temp = {}
for key, header of headers
if header is headers.start or header is headers.end
row[header] = row[header].toLowerCase()
if row[header] is 'midnight'
row[header] = '12:00 am'
else if row[header] is 'noon'
row[header] = '12:00 pm'
temp[key] = row[header]
else if header is headers.salary
temp[key] = row[header] is 'Y'
else if header is headers.timezone
if zone = moment.tz.zone row[header]
temp[key] = zone
else
temp[key] = row[header]
else if header is headers.shouldHound
temp[key] = row[header] is 'Y'
else if header is headers.taxType
temp.taxType = row[header] || 'W2'
else if header is headers.houndFrequency
temp[key] = row[header] || -1
if temp[key] is -1
temp.shouldResetHound = false
else
temp.shouldResetHound = true
else if header is headers.overtime
continue
else if header is headers.lastPing
tz = TIMEZONE
if temp.timezone
tz = temp.timezone.name
lastPing = moment.tz(row[header], 'MM/DD/YYYY hh:mm:ss A', tz)
if lastPing.isValid()
temp[key] = lastPing
else
temp[key] = moment.tz(tz).subtract(1, 'days')
else
if isNaN row[header]
temp[key] = row[header].trim()
else
temp[key] = parseFloat row[header]
timetable = new Timetable(temp.start, temp.end, temp.timezone)
timetable.setVacation(temp.vacationLogged, temp.vacationAvailable)
timetable.setSick(temp.sickLogged, temp.sickAvailable)
timetable.setUnpaid(temp.unpaidLogged)
timetable.setLogged(temp.totalLogged)
timetable.setAverageLogged(temp.averageLogged)
user = new User(temp.name, temp.PI:NAME:<NAME>END_PIname, temp.salary, timetable, row)
user.settings = Settings.fromSettings {
shouldHound: temp.shouldHound,
shouldResetHound: temp.shouldResetHound,
houndFrequency: temp.houndFrequency,
lastMessage: null,
lastPing: temp.lastPing
}
return user
activeHours: ->
return @timetable.activeHours()
activeTime: ->
return @timetable.activeTime()
setTimezone: (timezone) ->
tz = moment.tz.zone(timezone)
if tz
@timetable.setTimezone(tz)
@updateRow()
return tz
setStart: (start) ->
time = moment(start, 'h:mm A')
if time
@timetable.setStart(time)
@updateRow()
return time
setEnd: (end) ->
time = moment(end, 'h:mm A')
if time
@timetable.setEnd(time)
@updateRow()
return time
toDays: (hours) ->
return @timetable.toDays hours
isInactive: (current) ->
current = current || moment.tz(@timetable.timezone.name)
[start, end] = @activeHours()
if current.holiday()?
return true
else if current.isBetween(start, end)
return false
else
return true
lastPunch: (modes) ->
if typeof modes is 'string'
modes = [modes]
if not modes || modes.length is 0
return @punches.slice(-1)[0]
if @punches and @punches.length > 0
len = @punches.length
for i in [len-1..0]
last = @punches[i]
if 'in' in modes and not 'out' in modes and last.mode is 'out'
return
else if last.mode in modes
return last
return
lastPunchTime: ->
if @punches.length > 0
punch = @lastPunch()
if punch.times.length > 0
time = punch.times.slice(-1)[0]
if time.isSame(moment(), 'day')
date = 'today'
else if time.isSame(moment().subtract(1, 'days'), 'day')
date = 'yesterday'
else
date = 'on ' + time.format('MMM Do')
return "#{date}, #{time.format('h:mm a')}"
else if punch.times.block
if punch.mode is 'none'
type = ' '
else if punch.mode is 'vacation' or
punch.mode is 'sick' or
punch.mode is 'unpaid'
type = punch.mode + ' '
return "a #{punch.times.block} hour #{type}block punch"
return "never"
undoPunch: () ->
deferred = Q.defer()
lastPunch = @lastPunch()
that = @
Logger.log "Undoing #{that.slack}'s punch: #{lastPunch.description(that)}"
if lastPunch.times.block
elapsed = lastPunch.times.block
else
elapsed = lastPunch.elapsed || 0
headers = HEADERS.rawdata
if lastPunch.mode is 'vacation' or
lastPunch.mode is 'sick' or
lastPunch.mode is 'unpaid' or
lastPunch.mode is 'none'
deletePromise = Q.nfbind(lastPunch.row.del.bind(lastPunch))
deletePromise()
.then(() ->
punch = that.punches.pop()
elapsedDays = that.toDays elapsed
if punch.mode is 'vacation'
total = that.timetable.vacationTotal
available = that.timetable.vacationAvailable
that.timetable.setVacation(total - elapsedDays,
available + elapsedDays)
else if punch.mode is 'sick'
total = that.timetable.sickTotal
available = that.timetable.sickAvailable
that.timetable.setSick(total - elapsedDays, available + elapsedDays)
else if punch.mode is 'unpaid'
total = that.timetable.unpaidTotal
that.timetable.setUnpaid(total - elapsedDays)
else
logged = that.timetable.loggedTotal
that.timetable.setLogged(logged - elapsed)
deferred.resolve(punch)
)
else if lastPunch.mode is 'out'
# projects will not be touched
lastPunch.times.pop()
lastPunch.elapsed = null
if lastPunch.notes.lastIndexOf("\n") > 0
lastPunch.notes = lastPunch.notes
.substring(0, lastPunch.notes.lastIndexOf("\n"))
lastPunch.mode = 'in'
lastPunch.row[headers.out] =
lastPunch.row[headers.totalTime] =
lastPunch.row[headers.blockTime] = ''
lastPunch.row[headers.notes] = lastPunch.notes
savePromise = Q.nfbind(lastPunch.row.save.bind(lastPunch))
savePromise()
.then(() ->
logged = that.timetable.loggedTotal
that.timetable.setLogged(logged - elapsed)
deferred.resolve(lastPunch)
)
else if lastPunch.mode is 'in'
deletePromise = Q.nfbind(lastPunch.row.del.bind(lastPunch))
deletePromise()
.then(() ->
punch = that.punches.pop()
deferred.resolve(punch)
)
deferred.promise
toRawPayroll: (start, end) ->
headers = HEADERS.payrollreports
row = {}
row[headers.date] = moment.tz(TIMEZONE).format('M/DD/YYYY')
firstName = @name.split(' ').slice(0, -1).join(' ')
lastName = @name.split(' ').slice(-1)
row[headers.name] = lastName + ', ' + firstName
loggedTime = unpaidTime = vacationTime = sickTime = 0
projectsForPeriod = []
for punch in @punches
if punch.date.isBefore(start) or punch.date.isAfter(end)
continue
else if not punch.elapsed and not punch.times.block
continue
else if punch.mode is 'in'
continue
else if punch.mode is 'vacation'
if punch.times.block
vacationTime += punch.times.block
else
vacationTime += punch.elapsed
else if punch.mode is 'unpaid'
if punch.times.block
unpaidTime += punch.times.block
else
unpaidTime += punch.elapsed
else if punch.mode is 'sick'
if punch.times.block
sickTime += punch.times.block
else
sickTime += punch.elapsed
else
if punch.times.block
loggedTime += punch.times.block
else
loggedTime += punch.elapsed
if punch.projects? and punch.projects?.length > 0
for project in punch.projects
match = projectsForPeriod.filter((item, index, arr) ->
return project.name is item.name
)[0]
if not match
projectsForPeriod.push project
loggedTime = +loggedTime.toFixed(2)
vacationTime = +vacationTime.toFixed(2)
sickTime = +sickTime.toFixed(2)
unpaidTime = +unpaidTime.toFixed(2)
holidayTime = @timetable.holiday || 0
if @salary
paidTime = Math.min(80, loggedTime + vacationTime + sickTime + holidayTime)
row[headers.paid] = if paidTime > 0 then paidTime else ''
row[headers.unpaid] = if unpaidTime > 0 then unpaidTime else ''
row[headers.vacation] = if vacationTime > 0 then vacationTime else ''
row[headers.sick] = if sickTime > 0 then sickTime else ''
# row[headers.salary] = '=MIN(80,MINUS(80,SUM(D1,H1:K1)))'
else
paidTime = loggedTime
row[headers.paid] = if paidTime > 0 then paidTime else ''
# row[headers.salary] = '=MIN(80,MINUS(C1,SUM(D1,H1:K1)))'
row[headers.logged] = loggedTime
overTime = Math.max(0, loggedTime - 80)
row[headers.overtime] = if overTime > 0 then overTime else ''
row[headers.holiday] = if holidayTime > 0 then holidayTime else ''
row.extra = {
slack: @slack,
projects: projectsForPeriod
}
row
updateRow: () ->
deferred = Q.defer()
if @row?
headers = HEADERS.users
@row[headers.start] = @timetable.start.format('h:mm A')
@row[headers.end] = @timetable.end.format('h:mm A')
@row[headers.timezone] = @timetable.timezone.name
@row[headers.shouldHound] = if @settings?.shouldHound then 'Y' else 'N'
@row[headers.houndFrequency] = if @settings?.houndFrequency then @settings.houndFrequency else -1
@row[headers.vacationAvailable] = @timetable.vacationAvailable
@row[headers.vacationLogged] = @timetable.vacationTotal
@row[headers.sickAvailable] = @timetable.sickAvailable
@row[headers.sickLogged] = @timetable.sickTotal
@row[headers.unpaidLogged] = @timetable.unpaidTotal
@row[headers.overtime] = Math.max(0, @timetable.loggedTotal - 80)
@row[headers.totalLogged] = @timetable.loggedTotal
@row[headers.averageLogged] = @timetable.averageLoggedTotal
@row[headers.lastPing] = if @settings?.lastPing then moment.tz(@settings.lastPing, @timetable.timezone.name).format('MM/DD/YYYY hh:mm:ss A') else moment.tz(@timetable.timezone.name).format('MM/DD/YYYY hh:mm:ss A')
@row.save (err) ->
if err
deferred.reject err
else
deferred.resolve true
else
deferred.reject 'Row is null'
deferred.promise
directMessage: (msg, logger=Logger, attachment) ->
logger.logToChannel msg, @slack, attachment, true
hound: (msg, logger=Logger) ->
now = moment.tz TIMEZONE
@settings?.lastPing = now
me = @
if not @salary and @settings?.houndFrequency > 0
msg = "You have been on the clock for
#{@settings.houndFrequency} hours.\n" + msg
setTimeout ->
me.directMessage msg, logger
, 1000 * (Math.floor(Math.random() * 3) + 1)
Logger.log "Hounded #{@slack} with '#{msg}'"
@updateRow()
hexColor: ->
hash = 0
for i in [0...@slack.length]
hash = @slack.charCodeAt(i) + ((hash << 3) - hash)
color = Math.abs(hash).toString(16).substring(0, 6)
hexColor = "#" + '000000'.substring(0, 6 - color.length) + color
return hexColor
slackAttachment: () ->
fields = []
statusString = "#{if @salary then 'Salary' else 'Hourly'} -
Active #{@timetable.start.format('h:mm a')} to
#{@timetable.end.format('h:mm a z')}"
lastPunch = @lastPunch()
if lastPunch
lastPunchField =
title: "Last Punch"
value: "#{lastPunch.description(@)}"
short: true
fields.push lastPunchField
houndString = "#{if @settings?.shouldHound then 'On' else 'Off'}"
if @settings?.shouldHound
houndString += " (#{@settings?.houndFrequency} hours)"
houndField =
title: "Hounding"
value: houndString
short: true
fields.push houndField
if @salary
vacationDaysField =
title: "Vacation Days"
value: "#{@timetable.vacationAvailable} available,
#{@timetable.vacationTotal} used"
short: true
fields.push vacationDaysField
sickDaysField =
title: "Sick Days"
value: "#{@timetable.sickAvailable} available,
#{@timetable.sickTotal} used"
short: true
fields.push sickDaysField
if @unpaidTotal > 0
unpaidField =
title: "Unpaid Days"
value: "#{@timetable.unpaidTotal} used"
short: true
fields.push unpaidField
attachment =
title: @name + " (@" + @slack + ")",
text: statusString,
fallback: @name.replace(/\W/g, '') + " @" + @slack.replace(/\W/g, '')
color: @hexColor()
fields: fields
return attachment
description: () ->
return "User: #{@name} (#{@slack})\n
They have #{(@punches || []).length} punches on record\n
Last punch was #{@lastPunchTime()}\n
Their active hours are from #{@timetable.start.format('h:mm a')} to
#{@timetable.end.format('h:mm a')}\n
They are in #{@timetable.timezone.name}\n
The last time they sent a message was
#{+(moment.tz(TIMEZONE).diff(@settings?.lastMessage?.time, 'hours', true).toFixed(2))} hours ago"
module.exports.User = User
module.exports.Settings = Settings
module.exports.Timetable = Timetable
|
[
{
"context": "# Original Author: David Morrow\n# https://github.com/dperrymorrow/callbacks.js\n# ",
"end": 31,
"score": 0.9997570514678955,
"start": 19,
"tag": "NAME",
"value": "David Morrow"
},
{
"context": "riginal Author: David Morrow\n# https://github.com/dperrymorrow/callbacks.j... | app/assets/javascripts/0-utils/callbacks.js.coffee | quark-zju/gerrit-frontend | 2 | # Original Author: David Morrow
# https://github.com/dperrymorrow/callbacks.js
# MIT license
#
# Modified:
# - Rename method names. For example, remove `Callback`
# - Fix `remove`
# - Remove `instance`, change `method` from string to real method
# - Callbacks.add = Callbacks.get().add
class @Callbacks
constructor: ->
@triggerMap = {}
add: (trigger, method) ->
(@triggerMap[trigger] ||= []).push {trigger, method}
return
remove: (trigger, method) ->
triggers = @triggerMap[trigger]
return if !triggers
@triggerMap[trigger] = (listener for listener in triggers when listener.method != method)
return
removeAll: (trigger) ->
if trigger
@triggerMap[trigger] = null
else
@triggerMap = {}
return
fire: (trigger) ->
return if !@triggerMap[trigger]
for listener in @triggerMap[trigger]
methodArguments = [] # Array.prototype.slice(arguments) won't work in nodejs
for argument, i in arguments
methodArguments.push argument if i != 0
listener.method.apply null, methodArguments
return
_instance = new @
@get: -> _instance
@add: _instance.add.bind(_instance)
@fire: _instance.fire.bind(_instance)
@removeAll: _instance.removeAll.bind(_instance)
@remove: _instance.remove.bind(_instance)
| 204320 | # Original Author: <NAME>
# https://github.com/dperrymorrow/callbacks.js
# MIT license
#
# Modified:
# - Rename method names. For example, remove `Callback`
# - Fix `remove`
# - Remove `instance`, change `method` from string to real method
# - Callbacks.add = Callbacks.get().add
class @Callbacks
constructor: ->
@triggerMap = {}
add: (trigger, method) ->
(@triggerMap[trigger] ||= []).push {trigger, method}
return
remove: (trigger, method) ->
triggers = @triggerMap[trigger]
return if !triggers
@triggerMap[trigger] = (listener for listener in triggers when listener.method != method)
return
removeAll: (trigger) ->
if trigger
@triggerMap[trigger] = null
else
@triggerMap = {}
return
fire: (trigger) ->
return if !@triggerMap[trigger]
for listener in @triggerMap[trigger]
methodArguments = [] # Array.prototype.slice(arguments) won't work in nodejs
for argument, i in arguments
methodArguments.push argument if i != 0
listener.method.apply null, methodArguments
return
_instance = new @
@get: -> _instance
@add: _instance.add.bind(_instance)
@fire: _instance.fire.bind(_instance)
@removeAll: _instance.removeAll.bind(_instance)
@remove: _instance.remove.bind(_instance)
| true | # Original Author: PI:NAME:<NAME>END_PI
# https://github.com/dperrymorrow/callbacks.js
# MIT license
#
# Modified:
# - Rename method names. For example, remove `Callback`
# - Fix `remove`
# - Remove `instance`, change `method` from string to real method
# - Callbacks.add = Callbacks.get().add
class @Callbacks
constructor: ->
@triggerMap = {}
add: (trigger, method) ->
(@triggerMap[trigger] ||= []).push {trigger, method}
return
remove: (trigger, method) ->
triggers = @triggerMap[trigger]
return if !triggers
@triggerMap[trigger] = (listener for listener in triggers when listener.method != method)
return
removeAll: (trigger) ->
if trigger
@triggerMap[trigger] = null
else
@triggerMap = {}
return
fire: (trigger) ->
return if !@triggerMap[trigger]
for listener in @triggerMap[trigger]
methodArguments = [] # Array.prototype.slice(arguments) won't work in nodejs
for argument, i in arguments
methodArguments.push argument if i != 0
listener.method.apply null, methodArguments
return
_instance = new @
@get: -> _instance
@add: _instance.add.bind(_instance)
@fire: _instance.fire.bind(_instance)
@removeAll: _instance.removeAll.bind(_instance)
@remove: _instance.remove.bind(_instance)
|
[
{
"context": "oment().add(1, 'days').format()\n title: \"Andy Foobar's Retrospective\"\n )\n fixtures.secti",
"end": 644,
"score": 0.9596894383430481,
"start": 633,
"tag": "NAME",
"value": "Andy Foobar"
},
{
"context": ".running()[0].get('title')\n .shou... | test/collections/verticals.coffee | l2succes/force | 0 | _ = require 'underscore'
moment = require 'moment'
sinon = require 'sinon'
Backbone = require 'backbone'
fixtures = require '../helpers/fixtures'
Sections = require '../../collections/sections'
describe 'Sections', ->
beforeEach ->
sinon.stub Backbone, 'sync'
@sections = new Sections [fixtures.section]
afterEach ->
Backbone.sync.restore()
describe '#running', ->
it 'pulls the currently running sections', ->
@sections.reset [
_.extend(_.clone(fixtures.section),
start_at: moment().subtract(1, 'days').format()
end_at: moment().add(1, 'days').format()
title: "Andy Foobar's Retrospective"
)
fixtures.section
]
@sections.running().length.should.equal 1
@sections.running()[0].get('title')
.should.equal "Andy Foobar's Retrospective" | 7005 | _ = require 'underscore'
moment = require 'moment'
sinon = require 'sinon'
Backbone = require 'backbone'
fixtures = require '../helpers/fixtures'
Sections = require '../../collections/sections'
describe 'Sections', ->
beforeEach ->
sinon.stub Backbone, 'sync'
@sections = new Sections [fixtures.section]
afterEach ->
Backbone.sync.restore()
describe '#running', ->
it 'pulls the currently running sections', ->
@sections.reset [
_.extend(_.clone(fixtures.section),
start_at: moment().subtract(1, 'days').format()
end_at: moment().add(1, 'days').format()
title: "<NAME>'s Retrospective"
)
fixtures.section
]
@sections.running().length.should.equal 1
@sections.running()[0].get('title')
.should.equal "<NAME>'s Retrospective" | true | _ = require 'underscore'
moment = require 'moment'
sinon = require 'sinon'
Backbone = require 'backbone'
fixtures = require '../helpers/fixtures'
Sections = require '../../collections/sections'
describe 'Sections', ->
beforeEach ->
sinon.stub Backbone, 'sync'
@sections = new Sections [fixtures.section]
afterEach ->
Backbone.sync.restore()
describe '#running', ->
it 'pulls the currently running sections', ->
@sections.reset [
_.extend(_.clone(fixtures.section),
start_at: moment().subtract(1, 'days').format()
end_at: moment().add(1, 'days').format()
title: "PI:NAME:<NAME>END_PI's Retrospective"
)
fixtures.section
]
@sections.running().length.should.equal 1
@sections.running()[0].get('title')
.should.equal "PI:NAME:<NAME>END_PI's Retrospective" |
[
{
"context": ", xor_digest }\n\ndesc = \"Set 1, vector# 0\"\nkey = \"80000000000000000000000000000000\"\nIV = \"0000000000000000\"\nstream = [\n { \"low\" : 0",
"end": 372,
"score": 0.9995388984680176,
"start": 340,
"tag": "KEY",
"value": "80000000000000000000000000000000"
},
{
"co... | test/gen/gen_salsa20_key128.iced | CyberFlameGO/triplesec | 274 | # These test vectors can be found here:
#
# http://www.ecrypt.eu.org/stream/svn/viewcvs.cgi/ecrypt/trunk/submissions/salsa20/full/verified.test-vectors?logsort=rev&rev=210&view=markup"
#
# They specify keystreams for various inputs
#
out = []
f = () ->
out.push { desc, key, IV, stream, xor_digest }
desc = "Set 1, vector# 0"
key = "80000000000000000000000000000000"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "4DFA5E481DA23EA09A31022050859936DA52FCEE218005164F267CB65F5CFD7F2B4F97E0FF16924A52DF269515110A07F9E460BC65EF95DA58F740B7D1DBB0AA" }
{ "low" : 192, "hi" : 255, "bytes" : "DA9C1581F429E0A00F7D67E23B730676783B262E8EB43A25F55FB90B3E753AEF8C6713EC66C51881111593CCB3E8CB8F8DE124080501EEEB389C4BCB6977CF95" }
{ "low" : 256, "hi" : 319, "bytes" : "7D5789631EB4554400E1E025935DFA7B3E9039D61BDC58A8697D36815BF1985CEFDF7AE112E5BB81E37ECF0616CE7147FC08A93A367E08631F23C03B00A8DA2F" }
{ "low" : 448, "hi" : 511, "bytes" : "B375703739DACED4DD4059FD71C3C47FC2F9939670FAD4A46066ADCC6A5645783308B90FFB72BE04A6B147CBE38CC0C3B9267C296A92A7C69873F9F263BE9703" } ]
xor_digest = "F7A274D268316790A67EC058F45C0F2A067A99FCDE6236C0CEF8E056349FE54C5F13AC74D2539570FD34FEAB06C572053949B59585742181A5A760223AFA22D4"
f()
desc = "Set 1, vector# 9"
key = "00400000000000000000000000000000"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "0471076057830FB99202291177FBFE5D38C888944DF8917CAB82788B91B53D1CFB06D07A304B18BB763F888A61BB6B755CD58BEC9C4CFB7569CB91862E79C459" }
{ "low" : 192, "hi" : 255, "bytes" : "D1D7E97556426E6CFC21312AE38114259E5A6FB10DACBD88E4354B04725569352B6DA5ACAFACD5E266F9575C2ED8E6F2EFE4B4D36114C3A623DD49F4794F865B" }
{ "low" : 256, "hi" : 319, "bytes" : "AF06FAA82C73291231E1BD916A773DE152FD2126C40A10C3A6EB40F22834B8CC68BD5C6DBD7FC1EC8F34165C517C0B639DB0C60506D3606906B8463AA0D0EC2F" }
{ "low" : 448, "hi" : 511, "bytes" : "AB3216F1216379EFD5EC589510B8FD35014D0AA0B613040BAE63ECAB90A9AF79661F8DA2F853A5204B0F8E72E9D9EB4DBA5A4690E73A4D25F61EE7295215140C" } ]
xor_digest = "B76A7991D5EE58FC51B9035E077E1315D81F131FA1F26CF22005C6C4F2412243C401A850AFEFAADC5B052435B51177C70AE68CB9DF9B44681C2D8B7049D89333"
f()
desc = "Set 1, vector# 18"
key = "00002000000000000000000000000000"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "BACFE4145E6D4182EA4A0F59D4076C7E83FFD17E7540E5B7DE70EEDDF9552006B291B214A43E127EED1DA1540F33716D83C3AD7D711CD03251B78B2568F2C844" }
{ "low" : 192, "hi" : 255, "bytes" : "56824347D03D9084ECCF358A0AE410B94F74AE7FAD9F73D2351E0A44DF1274343ADE372BDA2971189623FD1EAA4B723D76F5B9741A3DDC7E5B3E8ED4928EF421" }
{ "low" : 256, "hi" : 319, "bytes" : "999F4E0F54C62F9211D4B1F1B79B227AFB3116C9CF9ADB9715DE856A8EB3108471AB40DFBF47B71389EF64C20E1FFDCF018790BCE8E9FDC46527FE1545D3A6EA" }
{ "low" : 448, "hi" : 511, "bytes" : "76F1B87E93EB9FEFEC3AED69210FE4AB2ED577DECE01A75FD364CD1CD7DE10275A002DDBC494EE8350E8EEC1D8D6925EFD6FE7EA7F610512F1F0A83C8949AEB1" } ]
xor_digest = "B9D233247408CD459A027430A23E6FCF3E9A3BAF0D0FC59E623F04D9C107D402880620C64A111318ECE60C22737BECA421F7D3D004E7191ECE2C7075289B31BF"
f()
desc = "Set 1, vector# 27"
key = "00000010000000000000000000000000"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "24F4E317B675336E68A8E2A3A04CA967AB96512ACBA2F832015E9BE03F08830FCF32E93D14FFBD2C901E982831ED806221D7DC8C32BBC8E056F21BF9BDDC8020" }
{ "low" : 192, "hi" : 255, "bytes" : "E223DE7299E51C94623F8EAD3A6DB0454091EE2B54A498F98690D7D84DB7EFD5A2A8202435CAC1FB34C842AEECF643C63054C424FAC5A632502CD3146278498A" }
{ "low" : 256, "hi" : 319, "bytes" : "5A111014076A6D52E94C364BD7311B64411DE27872FC8641D92C9D811F2B518594935F959D064A9BE806FAD06517819D2321B248E1F37E108E3412CE93FA8970" }
{ "low" : 448, "hi" : 511, "bytes" : "8A9AB11BD5360D8C7F34887982B3F6586C34C1D6CB49100EA5D09A24C6B835D577C1A1C776902D785CB5516D74E8748079878FDFDDF0126B1867E762546E4D72" } ]
xor_digest = "0423874278AE11EF0A29B3E6E1A5BA41E43671636615E3F1F6215750E5A1749ACDFE0CEB74A11AC4862527C5849110C9A7A6F01E419372824BCAB90550340E81"
f()
desc = "Set 1, vector# 36"
key = "00000000080000000000000000000000"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "9907DB5E2156427AD15B167BEB0AD445452478AFEE3CF71AE1ED8EAF43E001A1C8199AF9CFD88D2B782AA2F39845A26A7AC54E5BE15DB7BDFBF873E16BC05A1D" }
{ "low" : 192, "hi" : 255, "bytes" : "EBA0DCC03E9EB60AE1EE5EFE3647BE456E66733AA5D6353447981184A05F0F0CB0AD1CB630C35DC253DE3FEBD10684CADBA8B4B85E02B757DED0FEB1C31D71A3" }
{ "low" : 256, "hi" : 319, "bytes" : "BD24858A3DB0D9E552345A3C3ECC4C69BBAE4901016A944C0D7ECCAAB9027738975EEA6A4240D94DA183A74D649B789E24A0849E26DC367BDE4539ADCCF0CAD8" }
{ "low" : 448, "hi" : 511, "bytes" : "EE20675194FA404F54BAB7103F6821C137EE2347560DC31D338B01026AB6E57165467215315F06360D85F3C5FE7A359E80CBFE735F75AA065BC18EFB2829457D" } ]
xor_digest = "19B8E721CD10577375FC6D0E6DC39B054E371860CE2AA310906EA7BAB28D737F2357B42E7DC1C48D597EA58B87602CE5C37EEDED2E0F4819938878AE7C50E151"
f()
desc = "Set 1, vector# 45"
key = "00000000000400000000000000000000"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "A59CE982636F2C8C912B1E8105E2577D9C86861E61FA3BFF757D74CB9EDE6027D7D6DE775643FAF5F2C04971BDCB56E6BE8144366235AC5E01C1EDF8512AF78B" }
{ "low" : 192, "hi" : 255, "bytes" : "DF8F13F1059E54DEF681CD554439BAB724CDE604BE5B77D85D2829B3EB137F4F2466BEADF4D5D54BA4DC36F1254BEC4FB2B367A59EA6DDAC005354949D573E68" }
{ "low" : 256, "hi" : 319, "bytes" : "B3F542ECBAD4ACA0A95B31D281B930E8021993DF5012E48A333316E712C4E19B58231AAE7C90C91C9CC135B12B490BE42CF9C9A2727621CA81B2C3A081716F76" }
{ "low" : 448, "hi" : 511, "bytes" : "F64A6449F2F13030BE554DB00D24CD50A89F80CCFE97435EBF0C49EB08747BF7B2C89BE612629F231C1B3398D8B4CC3F35DBECD1CF1CFDFDECD481B72A51276A" } ]
xor_digest = "4134A74A52EA89BF22E05A467E37E08215537896BE4D2BBDF29EA52A2303E64BD954A18928543C82B68A21E4B830A775CBA9D1176EBF8DB92938DF6E59117B74"
f()
desc = "Set 1, vector# 54"
key = "00000000000002000000000000000000"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "7A8131B777F7FBFD33A06E396FF32D7D8C3CEEE9573F405F98BD6083FE57BAB6FC87D5F34522D2440F649741D9F87849BC8751EF432DEE5DCC6A88B34B6A1EA9" }
{ "low" : 192, "hi" : 255, "bytes" : "6573F813310565DB22219984E09194459E5BB8613237F012EBB8249666582ACA751ED59380199117DDB29A5298F95FF065D271AB66CF6BC6CDE0EA5FC4D304EB" }
{ "low" : 256, "hi" : 319, "bytes" : "0E65CB6944AFBD84F5B5D00F307402B8399BF02852ED2826EA9AA4A55FB56DF2A6B83F7F228947DFAB2E0B10EAAA09D75A34F165ECB4D06CE6AB4796ABA3206A" }
{ "low" : 448, "hi" : 511, "bytes" : "11F69B4D034B1D7213B9560FAE89FF2A53D9D0C9EAFCAA7F27E9D119DEEEA299AC8EC0EA0529846DAF90CF1D9BFBE406043FE03F1713F249084BDD32FD98CD72" } ]
xor_digest = "E9CFBD15B5F4AD02903851F46728F2DD5910273E7360F1571EF1442199143B6C28E5368A2E00E08ADAE73AF3489E0D6F0D8032984ADD139B6BF508A5EEE4434B"
f()
desc = "Set 1, vector# 63"
key = "00000000000000010000000000000000"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "FE4DF972E982735FFAEC4D66F929403F7246FB5B2794118493DF068CD310DEB63EEEF12344E221A2D163CC666F5685B502F4883142FA867B0BA46BF17D011984" }
{ "low" : 192, "hi" : 255, "bytes" : "4694F79AB2F3877BD590BA09B413F1BDF394C4D8F2C20F551AA5A07207433204C2BC3A3BA014886A08F4EC5E4D91CDD01D7A039C5B815754198B2DBCE68D25EA" }
{ "low" : 256, "hi" : 319, "bytes" : "D1340204FB4544EFD5DAF28EDCC6FF03B39FBEE708CAEF6ABD3E2E3AB5738B3204EF38CACCC40B9FBD1E6F0206A2B564E2F9EA05E10B6DD061F6AB94374681C0" }
{ "low" : 448, "hi" : 511, "bytes" : "BB802FB53E11AFDC3104044D7044807941FDAEF1042E0D35972D80CE77B4D560083EB4113CDBC4AC56014D7FF94291DC9387CEF74A0E165042BC12373C6E020C" } ]
xor_digest = "FF021AEC5DC82F40BBF44CEA85287BCFD70F16F557F07B1BF970407051F71C415B703A67CAF8E81CB22D9F09E0CBD2475E9859355A48FDA9F48E38E2748BE41B"
f()
desc = "Set 1, vector# 72"
key = "00000000000000000080000000000000"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "8F8121BDD7B286465F03D64CA45A4A154BDF44560419A40E0B482CED194C4B324F2E9295C452B73B292BA7F55A692DEEA5129A49167BA7AABBEED26E39B25E7A" }
{ "low" : 192, "hi" : 255, "bytes" : "7E4388EDBBA6EC5882E9CBF01CFA67860F10F0A5109FCA7E865C3814EB007CC89585C2653BDCE30F667CF95A2AA425D35A531F558180EF3E32A9543AE50E8FD6" }
{ "low" : 256, "hi" : 319, "bytes" : "527FF72879B1B809C027DFB7B39D02B304D648CD8D70F4E0465615B334ED9E2D59703745467F1168A8033BA861841DC00E7E1AB5E96469F6DA01B8973D0D414A" }
{ "low" : 448, "hi" : 511, "bytes" : "82653E0949A5D8E32C4D0A81BBF96F6A7249D4D1E0DCDCC72B90565D9AF4D0AC461C1EAC85E254DD5E567A009EEB38979A2FD1E4F32FAD15D177D766932190E1" } ]
xor_digest = "B2F239692CE50EECABD7A846AC33388543CFC1061F33420B6F205809F3965D899C56C02D208DD3E9A1F0D5BBED8F5DACB164FD005DF907002302F40ADB6665CC"
f()
desc = "Set 1, vector# 81"
key = "00000000000000000000400000000000"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "52FA8BD042682CD5AA21188EBF3B9E4AEE3BE38AE052C5B37730E52C6CEE33C91B492F95A67F2F6C15425A8623C0C2AE7275FFD0FCF13A0A293A784289BEACB4" }
{ "low" : 192, "hi" : 255, "bytes" : "5F43C508BA6F728D032841618F96B10319B094027E7719C28A8A8637D4B0C4D225D602EA23B40D1541A3F8487F25B14A8CBD8D2001AC28EADFDC0325BA2C140E" }
{ "low" : 256, "hi" : 319, "bytes" : "5C802C813FF09CAF632CA8832479F891FB1016F2F44EFA81B3C872E37468B8183EB32D8BD8917A858AEF47524FCC05D3688C551FC8A42C8D9F0509018706E40E" }
{ "low" : 448, "hi" : 511, "bytes" : "4CDD40DC6E9C0E4F84810ABE712003F64B23C6D0C88E61D1F303C3BBD89B58AA098B44B5CD82EDCFC618D324A41317AC6FED20C9A0C54A9ED1F4DA3BF2EC3C66" } ]
xor_digest = "B72D2FEE4BFBC0F65005EE2797B0608A7A6D9CD1114B67C0ADEC7B4B6D793182880777B0279E3DF27CBA820714629A96034E4C71F5356254A0116CF3E9F7EF5C"
f()
desc = "Set 1, vector# 90"
key = "00000000000000000000002000000000"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "6262315C736E88717E9627EECF4F6B55BD10D5960A9961D572EFC7CBDB9A1F011733D3E17E4735BEFA16FE6B148F86614C1E37065A48ACF287FFE65C9DC44A58" }
{ "low" : 192, "hi" : 255, "bytes" : "B43439584FB2FAF3B2937838D8000AC4CD4BC4E582212A7741A0192F71C1F11B58D7F779CA0E6E4B8BD58E00B50C3C53DAF843467064A2DBE2FAD6FF6F40ECD8" }
{ "low" : 256, "hi" : 319, "bytes" : "EE51EE875F6F1B8AF0334F509DF5692B9B43CC63A586C2380AF3AE490DCD6CFF7907BC3724AE3BBEAD79D436E6DADDB22141B3BA46C9BEC0E01B9D4F7657B387" }
{ "low" : 448, "hi" : 511, "bytes" : "E5A4FE4A2FCA9A9ED779A9574283DC21C85216D54486D9B182300D0593B1E2B010814F7066AEB955C057609CE9AF0D63F057E17B19F57FFB7287EB2067C43B8D" } ]
xor_digest = "8866D8F9E6F423A7DF10C77625014AA582C06CD861A88F40FB9CD1EBF09111884344BEEA5A724E6FD8DB98BF4E6B9BEA5318FA62813D1B49A2D529FC00CB5777"
f()
desc = "Set 1, vector# 99"
key = "00000000000000000000000010000000"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "82FD629BD82C3BE22910951E2E41F8FE187E2BD198F6113AFF44B9B0689AA520C8CCE4E8D3FBA69EDE748BCF18397214F98D7ACF4424866A8670E98EBAB715A3" }
{ "low" : 192, "hi" : 255, "bytes" : "342D80E30E2FE7A00B02FC62F7090CDDECBDFD283D42A00423113196A87BEFD8B9E8AAF61C93F73CC6CBE9CC5AEC182F3948B7857F96B017F3477A2EEC3AEB3B" }
{ "low" : 256, "hi" : 319, "bytes" : "8233712B6D3CCB572474BE200D67E5403FC62128D74CE5F790202C696BFFB7EE3CAD255324F87291273A7719278FA3131ABA12342692A2C0C58D27BA3725761B" }
{ "low" : 448, "hi" : 511, "bytes" : "782600E7357AC69EA158C725B3E1E94051A0CB63D0D1B4B3DF5F5037E3E1DE45850578E9D513B90B8E5882D4DCA9F42BE32621F4DCC1C77B38F1B0AC1227C196" } ]
xor_digest = "F8AE82F9B77EF090AE0C72A5EAE2140568BEF0B354BCDF4BD39732CD86C63A82AFD27F58C459272B3E8A4B9B558D856F8475CF3A1AD99074822A836CFE520DC5"
f()
desc = "Set 1, vector#108"
key = "00000000000000000000000000080000"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "D244F87EB315A7EEF02CA314B440777EC6C44660020B43189693500F3279FA017257BE0AB087B81F85FD55AAC5845189C66E259B5412C4BDFD0EBE805FC70C8A" }
{ "low" : 192, "hi" : 255, "bytes" : "5A2D8D3E431FB40E60856F05C797620642B35DAB0255764D986740699040702F6CDE058458E842CB6E1843EBD336D37423833EC01DFFF9086FEECAB8A165D29F" }
{ "low" : 256, "hi" : 319, "bytes" : "443CEF4570C83517ED55C2F57058BB70294CC8D7342597E2CD850F6C02E355CAEB43C0A41F4BB74FFE9F6B0D25799140D03792D667601AD7954D21BD7C174C43" }
{ "low" : 448, "hi" : 511, "bytes" : "959C8B16A0ADEC58B544BE33CCF03277E48C7916E333F549CDE16E2B4B6DCE2D8D76C50718C0E77BFBEB3A3CB3CA14BF40F65EBFAE1A5001EAB36E531414E87F" } ]
xor_digest = "4DC82B00DC54141CC890348496115C681DB10ABE8454FBD10B49EF951CD20C6F7FE8AAA10906E57CF05EE838F76C8B7A3F9E6BD6D21C49F1590C913026C71A3E"
f()
desc = "Set 1, vector#117"
key = "00000000000000000000000000000400"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "44A74D35E73A7E7C37B009AE712783AC86ACE0C02CB175656AF79023D91C909ED2CB2F5C94BF8593DDC5E054D7EB726E0E867572AF954F88E05A4DAFD00CCF0A" }
{ "low" : 192, "hi" : 255, "bytes" : "FEC113A0255391D48A37CDF607AE122686305DDAD4CF1294598F2336AB6A5A029D927393454C2E014868137688C0417A2D31D0FE9540D7246FE2F84D6052DE40" }
{ "low" : 256, "hi" : 319, "bytes" : "79C2F7431D69E54C0474D8160113F3648156A8963817C34AC9A9AD222543666E7EAF03AF4EE03271C3ECED262E7B4C66B0F618BAF3395423274DD1F73E2675E3" }
{ "low" : 448, "hi" : 511, "bytes" : "75C1295C871B1100F27DAF19E5D5BF8D880B9A54CEFDF1561B4351A32898F3C26A04AB1149C24FBFA2AC963388E64C4365D716BCE8330BC03FA178DBE5C1E6B0" } ]
xor_digest = "65D58F845F973928ADF5803799901856A08952CF215154C52A5FF2DAD71E8B703DE107E5531491666353F323E790EB021B5EF66C13F43401F4F6A27F08CE11D5"
f()
desc = "Set 1, vector#126"
key = "00000000000000000000000000000002"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "E23A3638C836B1ACF7E27296E1F5A2413C4CC351EFEF65E3672E7C2FCD1FA1052D2C26778DB774B8FBA29ABED72D058EE35EBA376BA5BC3D84F8E44ABD5DC2CC" }
{ "low" : 192, "hi" : 255, "bytes" : "2A8BEB3C372A6570F54EB429FA7F562D6EF14DF725861EDCE8132620EAA00D8B1DFEF653B64E9C328930904A0EEB0132B277BB3D9888431E1F28CDB0238DE685" }
{ "low" : 256, "hi" : 319, "bytes" : "CCBEB5CA57104B95BF7BA5B12C8B85534CE9548F628CF53EF02C337D788BCE71D2D3D9C355E7D5EB75C56D079CB7D99D6AF0C8A86024B3AF5C2FC8A028413D93" }
{ "low" : 448, "hi" : 511, "bytes" : "D00A5FDCE01A334C37E75634A8037B49BEC06ACBD2243320E2CA41FB5619E6D875AB2007310D4149379C91EF4E199805BE261E5C744F0DF21737E01243B7116F" } ]
xor_digest = "2D72232A4485E0D2EEDC0619396020774C100C5424FF742B2868E3A68E67E1654C4711C54A34DA937359A26B8386AD2039EB2021DCFBB6A11603AF56225DE098"
f()
desc = "Set 2, vector# 0"
key = "00000000000000000000000000000000"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "6513ADAECFEB124C1CBE6BDAEF690B4FFB00B0FCACE33CE806792BB41480199834BFB1CFDD095802C6E95E251002989AC22AE588D32AE79320D9BD7732E00338" }
{ "low" : 192, "hi" : 255, "bytes" : "75E9D0493CA05D2820408719AFC75120692040118F76B8328AC279530D84667065E735C52ADD4BCFE07C9D93C00917902B187D46A25924767F91A6B29C961859" }
{ "low" : 256, "hi" : 319, "bytes" : "0E47D68F845B3D31E8B47F3BEA660E2ECA484C82F5E3AE00484D87410A1772D0FA3B88F8024C170B21E50E0989E94A2669C91973B3AE5781D305D8122791DA4C" }
{ "low" : 448, "hi" : 511, "bytes" : "CCBA51D3DB400E7EB780C0CCBD3D2B5BB9AAD82A75A1F746824EE5B9DAF7B7947A4B808DF48CE94830F6C9146860611DA649E735ED5ED6E3E3DFF7C218879D63" } ]
xor_digest = "6D3937FFA13637648E477623277644ADAD3854E6B2B3E4D68155356F68B30490842B2AEA2E32239BE84E613C6CE1B9BD026094962CB1A6757AF5A13DDAF8252C"
f()
desc = "Set 2, vector# 9"
key = "09090909090909090909090909090909"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "169060CCB42BEA7BEE4D8012A02F3635EB7BCA12859FA159CD559094B3507DB801735D1A1300102A9C9415546829CBD2021BA217B39B81D89C55B13D0C603359" }
{ "low" : 192, "hi" : 255, "bytes" : "23EF24BB24195B9FD574823CD8A40C29D86BD35C191E2038779FF696C712B6D82E7014DBE1AC5D527AF076C088C4A8D44317958189F6EF54933A7E0816B5B916" }
{ "low" : 256, "hi" : 319, "bytes" : "D8F12ED8AFE9422B85E5CC9B8ADEC9D6CFABE8DBC1082BCCC02F5A7266AA074CA284E583A35837798CC0E69D4CE937653B8CDD65CE414B89138615CCB165AD19" }
{ "low" : 448, "hi" : 511, "bytes" : "F70A0FF4ECD155E0F033604693A51E2363880E2ECF98699E7174AF7C2C6B0FC659AE329599A3949272A37B9B2183A0910922A3F325AE124DCBDD735364055CEB" } ]
xor_digest = "30209DD68D46E5A30034EF6DCE74FE1AB6C772AB22CD3D6C354A9C4607EF3F82900423D29FB65E07FFA3AEAD94E940D6E52E305A10D60936D34BD03B3F342AB1"
f()
desc = "Set 2, vector# 18"
key = "12121212121212121212121212121212"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "05835754A1333770BBA8262F8A84D0FD70ABF58CDB83A54172B0C07B6CCA5641060E3097D2B19F82E918CB697D0F347DC7DAE05C14355D09B61B47298FE89AEB" }
{ "low" : 192, "hi" : 255, "bytes" : "5525C22F425949A5E51A4EAFA18F62C6E01A27EF78D79B073AEBEC436EC8183BC683CD3205CF80B795181DAFF3DC98486644C6310F09D865A7A75EE6D5105F92" }
{ "low" : 256, "hi" : 319, "bytes" : "2EE7A4F9C576EADE7EE325334212196CB7A61D6FA693238E6E2C8B53B900FF1A133A6E53F58AC89D6A695594CE03F7758DF9ABE981F23373B3680C7A4AD82680" }
{ "low" : 448, "hi" : 511, "bytes" : "CB7A0595F3A1B755E9070E8D3BACCF9574F881E4B9D91558E19317C4C254988F42184584E5538C63D964F8EF61D86B09D983998979BA3F44BAF527128D3E5393" } ]
xor_digest = "AD29013FD0A222EEBE65126380A26477BD86751B3B0A2B4922602E63E6ECDA523BA789633BEE6CFF64436A8644CCD7E8F81B062187A9595A8D2507ED774FA5CD"
f()
desc = "Set 2, vector# 27"
key = "1B1B1B1B1B1B1B1B1B1B1B1B1B1B1B1B"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "72A8D26F2DF3B6713C2A053B3354DBA6C10743C7A8F19261CF0E7957905748DDD6D3333E2CBC6611B68C458D5CDBA2A230AC5AB03D59E71FE9C993E7B8E7E09F" }
{ "low" : 192, "hi" : 255, "bytes" : "7B6132DC5E2990B0049A5F7F357C9D997733948018AE1D4F9DB999F4605FD78CB548D75AC4657D93A20AA451B8F35E0A3CD08880CCED7D4A508BA7FB49737C17" }
{ "low" : 256, "hi" : 319, "bytes" : "EF7A7448D019C76ED0B9C18B5B2867CF9AD84B789FB037E6B107B0A4615737B5C1C113F91462CDA0BCB9ADDC09E8EA6B99E4835FED25F5CC423EEFF56D851838" }
{ "low" : 448, "hi" : 511, "bytes" : "6B75BDD0EC8D581CB7567426F0B92C9BB5057A89C3F604583DB700A46D6B8DE41AF315AE99BB5C1B52C76272D1E262F9FC7022CE70B435C27AE443284F5F84C1" } ]
xor_digest = "484F9FCB516547DD89AF46991B18F1DEC4C6CBC7D52735E00FC3201B4650151C3D4FB9C119442B368B28E3C68ED83F10D9DA2FDED7DEB8F04827FA91CCDBF65B"
f()
desc = "Set 2, vector# 36"
key = "24242424242424242424242424242424"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "76240D13C7E59CBD4183D162834A5D3637CD09EE4F5AFE9C28CFA9466A4089F65C80C224A87F956459B173D720274D09C573FCD128498D810460FDA1BB50F934" }
{ "low" : 192, "hi" : 255, "bytes" : "71AF115217F3B7F77A05B56E32AD0889BFA470B6DDC256D852C63B45688D7BC8DC610D347A2600D7769C67B28D1FA25F1AACFB8F9BB68BFE17357335D8FAC993" }
{ "low" : 256, "hi" : 319, "bytes" : "6573CC1ADC0DE744F6694E5FBB59E5BF5939CE5D13793E2F683C7F2C7DD9A460575746688A0F17D419FE3E5F886545597B6705E1390542B4F953D568025F5BB3" }
{ "low" : 448, "hi" : 511, "bytes" : "809179FAD4AD9B5C355A09E99C8BE9314B9DF269F162C1317206EB3580CAE58AB93A408C23739EF9538730FE687C8DAC1CE95290BA4ACBC886153E63A613857B" } ]
xor_digest = "D1781DCE3EFB8B13740F016264051354F323C81A13D42CE75E67180849AC49FFA7EA95720696F86848A1A4B8506A95E3A61371DDE7F21167CC147173BFC4D78F"
f()
desc = "Set 2, vector# 45"
key = "2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "3117FD618A1E7821EA08CDED410C8A67BDD8F7BE3FCA9649BD3E297FD83A80AD814C8904C9D7A2DC0DCAA641CFFF502D78AFF1832D34C263C1938C1ADF01238F" }
{ "low" : 192, "hi" : 255, "bytes" : "1E8CB540F19EC7AFCB366A25F74C0004B682E06129030617527BECD16E3E3E0027D818F035EDCDF56D8D4752AEF28BDBFA0D3B008235173475F5FA105B91BEED" }
{ "low" : 256, "hi" : 319, "bytes" : "637C3B4566BBEBBE703E4BF1C978CCD277AE3B8768DB97DF01983CDF3529B3EC6B1137CA6F231047C13EA38649D0058EBE5EF7B7BBA140F22338E382F1D6AB3F" }
{ "low" : 448, "hi" : 511, "bytes" : "D407259B6355C343D64A5130DA55C057E4AF722B70AC8A074262233677A457AFEAA34E7FD6F15959A4C781C4C978F7B3BC571BF66674F015A1EA5DB262E25BDC" } ]
xor_digest = "1F64F78101768FF5067B9A918444EF703FF06561E23B31C61BD43BCF86CFAD249942F73DC8F40AE49B14874B08F2A527A53DF496F37D067F1168268D4A134740"
f()
desc = "Set 2, vector# 54"
key = "36363636363636363636363636363636"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "7FED83B9283449AD8EBFC935F5F364075C9008ADE8626D350770E2DBD058F053F7E5300B088B1341EC54C2BEE72A520C35C673E79CC4ED0A6D8F4C15FBDD090B" }
{ "low" : 192, "hi" : 255, "bytes" : "D780206A2537106610D1C95BF7E9121BEDE1F0B8DFBE83CBC49C2C653DD187F7D84A2F4607BF99A96B3B84FB792340D4E67202FB74EC24F38955F345F21CF3DB" }
{ "low" : 256, "hi" : 319, "bytes" : "6CA21C5DC289674C13CFD4FCBDEA83560A90F53BB54F16DBF274F5CC56D7857CD3E3B06C81C70C828DC30DADEBD92F38BB8C24136F37797A647584BCEE68DF91" }
{ "low" : 448, "hi" : 511, "bytes" : "471936CE9C84E131C4C5792B769654B89644BFAFB1149130E580FD805A325B628CDE5FAE0F5C7CFFEF0D931F8F517A929E892D3789B74217A81BAEFE441E47ED" } ]
xor_digest = "0073DA29855E96EA5C414B9BD2E1C0F4987D3F1EB1CA73C4AA10180B99A437744857EB36586593B81088AADE5D89BBC68FBD8B0D268080746D6BE38DBC9396CD"
f()
desc = "Set 2, vector# 63"
key = "3F3F3F3F3F3F3F3F3F3F3F3F3F3F3F3F"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "C224F33B124D6692263733DFD5BF52717D1FB45EC1CEDCA6BF92BA44C1EADA85F7B031BCC581A890FD275085C7AD1C3D652BCA5F4D7597DECDB2232318EABC32" }
{ "low" : 192, "hi" : 255, "bytes" : "090325F54C0350AD446C19ABDCAEFF52EC57F5A13FB55FEDE4606CEC44EC658BBB13163481D2C84BF9409313F6470A0DA9803936094CC29A8DE7613CBFA77DD5" }
{ "low" : 256, "hi" : 319, "bytes" : "1F66F5B70B9D12BC7092C1846498A2A0730AA8FA8DD97A757BBB878320CE6633E5BCC3A5090F3F75BE6E72DD1E8D95B0DE7DBFDD764E484E1FB854B68A7111C6" }
{ "low" : 448, "hi" : 511, "bytes" : "F8AE560041414BE888C7B5EB3082CC7C4DFBBA5FD103F522FBD95A7166B91DE6C78FB47413576EC83F0EDE6338C9EDDB81757B58C45CBD3A3E29E491DB1F04E2" } ]
xor_digest = "542B2672401C5D1225CC704365753E33D0827A863C4897FFCE1B724CD10B2A0E8A4E4CDAB7357424FC6DC78440037240B8FD5299907A946CE77DAFA5322AB73D"
f()
desc = "Set 2, vector# 72"
key = "48484848484848484848484848484848"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "11BF31E22D7458C189092A1DE3A4905BA2FA36858907E3511FB63FDFF2C5C2A15B651B2C2F1A3A43A7186421528069672B6BB0AEC10452F1DAA9FC73FF5A396A" }
{ "low" : 192, "hi" : 255, "bytes" : "D1E1619E4BD327D2A124FC52BC15B1940B05394ECE5926E1E1ADE7D3FC8C6E91E43889F6F9C1FD5C094F6CA25025AE4CCC4FDC1824936373DBEE16D62B81112D" }
{ "low" : 256, "hi" : 319, "bytes" : "F900E9B0665F84C939D5FE4946FA7B41E34F06058522A2DB49E210E3E5385E5897C24F6350C6CCA578285325CC16F5586DC662FFBEA41BAC68996BAAB9F32D1F" }
{ "low" : 448, "hi" : 511, "bytes" : "40587ECAD15841F1BD1D236A61051574A974E15292F777ABDED64D2B761892BEF3DD69E479DE0D02CC73AF76E81E8A77F3CEE74180CB5685ACD4F0039DFFC3B0" } ]
xor_digest = "C3E5CC5C7CEA1B3885EB9CEF2D1FAF18E7DE1CFD7237F2D6D344F3DF7168A88EC88C1314CB6F5A3EAE1BC468B4FAD75E8A42BE8607705C9A7950302461AD9B3F"
f()
desc = "Set 2, vector# 81"
key = "51515151515151515151515151515151"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "EBC464423EADEF13E845C595A9795A585064F478A1C8582F07A4BA68E81329CB26A13C2EA0EFE9094B0A749FDB1CC6F9C2D293F0B395E14EB63075A39A2EDB4C" }
{ "low" : 192, "hi" : 255, "bytes" : "F4BBBBCE9C5869DE6BAF5FD4AE835DBE5B7F1752B2972086F3383E9D180C2FE55618846B10EB68AC0EB0865E0B167C6D3A843B29336BC1100A4AB7E8A3369959" }
{ "low" : 256, "hi" : 319, "bytes" : "3CEB39E3D740771BD49002EA8CD998518A8C70772679ECAF2030583AED43F77F565FECDBEF333265A2E1CC42CB606980AEF3B24C436A12C85CBDC5EBD97A9177" }
{ "low" : 448, "hi" : 511, "bytes" : "EF651A98A98C4C2B61EA8E7A673F5D4FD832D1F9FD19EE4537B6FEC7D11C6B2F3EF5D764EEAD396A7A2E32662647BFC07F02A557BA6EF046C8DE3781D74332B0" } ]
xor_digest = "88A96FF895BF2A827FC26DB2BB75DC698E8E1B7E231997AB2942E981EF1633EA061F6B323B99519828FB41A6F5CCC79C57F6DDDD34DEAB38514A54C4886626E5"
f()
desc = "Set 2, vector# 90"
key = "5A5A5A5A5A5A5A5A5A5A5A5A5A5A5A5A"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "F40253BAA835152E1582646FD5BD3FED638EB3498C80BFB941644A7750BBA5653130CC97A937A2B27AFBB3E679BC42BE87F83723DC6F0D61DCE9DE8608AC62AA" }
{ "low" : 192, "hi" : 255, "bytes" : "A5A1CD35A230ED57ADB8FE16CD2D2EA6055C32D3E621A0FD6EB6717AA916D47857CD987C16E6112EDE60CCB0F70146422788017A6812202362691FDA257E5856" }
{ "low" : 256, "hi" : 319, "bytes" : "81F0D04A929DB4676F6A3E6C15049779C4EC9A12ACF80168D7E9AA1D6FA9C13EF2956CEE750A89103B48F22C06439C5CE9129996455FAE2D7775A1D8D39B00CE" }
{ "low" : 448, "hi" : 511, "bytes" : "3F6D60A0951F0747B94E4DDE3CA4ED4C96694B7534CD9ED97B96FAAD3CF00D4AEF12919D410CD9777CD5F2F3F2BF160EBBA3561CC24345D9A09978C3253F6DCB" } ]
xor_digest = "554F89BF1AD5602655B800DB9B3CCFFA1B267D57654DCF3FDDA81A59DF68B022555E63DE51E7A83668E7F1AE09EEB5B8748DEF8580B304199C4D117CF9A94E78"
f()
desc = "Set 2, vector# 99"
key = "63636363636363636363636363636363"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "ED5FF13649F7D8EDFC783EFDF2F843B368776B19390AF110BEF12EAC8EC58A2E8CDAB6EC9049FBDA23A615C536C3A313799E21668C248EC864D5D5D99DED80B3" }
{ "low" : 192, "hi" : 255, "bytes" : "845ACE9B870CF9D77597201988552DE53FD40D2C8AC51ABE1335F6A2D0035DF8B10CACAD851E000BAC6EA8831B2FBCFEB7C94787E41CC541BAC3D9D26DB4F19D" }
{ "low" : 256, "hi" : 319, "bytes" : "981580764B81A4E12CA1F36634B591365E4BDB6C12DE13F2F337E72E018029C5A0BECDA7B6723DD609D81A314CE396190E82848893E5A44478B08340F90A73F3" }
{ "low" : 448, "hi" : 511, "bytes" : "4CD3B072D5720E6C64C9476552D1CFF4D4EF68DCBD11E8D516F0C248F9250B571990DD3AFC0AE8452896CCCC0BD0EFDF17B616691AB3DF9AF6A42EDCA54BF9CD" } ]
xor_digest = "52D590BB5E396FCC2E00D9C51B3C0BF073E123C7EE69B528B0F0F87B57DC6907F4B57FD5F5B10D602B1F723E9FDD5510AEC60CD0DD50ED4B60FA355859638C2C"
f()
desc = "Set 2, vector#108"
key = "6C6C6C6C6C6C6C6C6C6C6C6C6C6C6C6C"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "78ED06021C5C7867D176DA2A96C4BBAA494F451F21875446393E9688205ED63DEA8ADEB1A2381201F576C5A541BC88874078608CA8F2C2A6BDCDC1081DD254CC" }
{ "low" : 192, "hi" : 255, "bytes" : "C1747F85DB1E4FB3E29621015314E3CB261808FA6485E59057B60BE82851CFC948966763AF97CB9869567B763C7454575022249DFE729BD5DEF41E6DBCC68128" }
{ "low" : 256, "hi" : 319, "bytes" : "1EE4C7F63AF666D8EDB2564268ECD127B4D015CB59487FEAF87D0941D42D0F8A24BD353D4EF765FCCF07A3C3ACF71B90E03E8AEA9C3F467FE2DD36CEC00E5271" }
{ "low" : 448, "hi" : 511, "bytes" : "7AFF4F3A284CC39E5EAF07BA6341F065671147CA0F073CEF2B992A7E21690C8271639ED678D6A675EBDAD4833658421315A2BA74754467CCCE128CCC62668D0D" } ]
xor_digest = "FB3FE601D4E58B0766F02FA15C3323913CD745E905AD74EA5DABA77BC25D282DD66D98204E101F06D60BA446A21331AF6DDEB70679DEF46B886EB8A75C916380"
f()
desc = "Set 2, vector#117"
key = "75757575757575757575757575757575"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "D935C93A8EBB90DB53A27BF9B41B334523E1DFDE3BFFC09EA97EFB9376D38C7D6DC67AAB21EA3A5C07B6503F986F7E8D9E11B3150BF0D38F36C284ADB31FACF8" }
{ "low" : 192, "hi" : 255, "bytes" : "DA88C48115010D3CD5DC0640DED2E6520399AAFED73E573CBAF552C6FE06B1B3F3ADE3ADC19DA311B675A6D83FD48E3846825BD36EB88001AE1BD69439A0141C" }
{ "low" : 256, "hi" : 319, "bytes" : "14EA210224DAF4FC5D647C78B6BFEF7D724DC56DCDF832B496DEAD31DD948DB1944E17AB2966973FD7CCB1BC9EC0335F35326D5834EE3B08833358C4C28F70DE" }
{ "low" : 448, "hi" : 511, "bytes" : "D5346E161C083E00E247414F44E0E7375B435F426B58D482A37694331D7C5DC97D8953E6A852625282973ECCFD012D664C0AFA5D481A59D7688FDB54C55CD04F" } ]
xor_digest = "BB5EAC1AB84C70857245294309C023C4B1A4199D16877BC847BCBB1B0A8D1B544289D6C8BF27212AAFFD42021669BB2477A4F815FA01B3F7E88299240155265B"
f()
desc = "Set 2, vector#126"
key = "7E7E7E7E7E7E7E7E7E7E7E7E7E7E7E7E"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "45A43A587C45607441CE3AE20046797788879C5B77FDB90B76F7D2DF27EE8D9428A5B5AF35E2AAE242E6577BEC92DA0929A6AFB3CB8F8496375C98085460AB95" }
{ "low" : 192, "hi" : 255, "bytes" : "14AE0BA973AE19E6FD674413C276AB9D99AA0048822AFB6F0B68A2741FB5CE2F64F3D862106EF2BDE19B39209F75B92BDBE9015D63FDFD7B9E8A776291F4E831" }
{ "low" : 256, "hi" : 319, "bytes" : "C26FA1812FFC32EFF2954592A0E1E5B126D5A2196624156E3DFD0481205B24D5613B0A75AF3CBC8BBE5911BE93125BD3D3C50C92910DBA05D80666632E5DF9EF" }
{ "low" : 448, "hi" : 511, "bytes" : "AD0DABE5AF74AB4F62B4699E0D667BBF01B4DCF0A45514554CAC4DFDE453EFF1E51BE5B74B37512C40E3608FB0E65A3FD4EAFA27A3BB0D6E1300C594CB0D1254" } ]
xor_digest = "0F1A4B0994EE03B6C381FE4BB8E33C0EE47C395BB59922C5537EEBFD125494220F743B93D867085E027E56623F79505608179A39FF52D4C00A45A5FB8F618C49"
f()
desc = "Set 2, vector#135"
key = "87878787878787878787878787878787"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "09E15E82DFA9D821B8F68789978D094048892C624167BA88AD767CAEFDE80E25F57467156B8054C8E88F3478A2897A20344C4B05665E7438AD1836BE86A07B83" }
{ "low" : 192, "hi" : 255, "bytes" : "2D752E53C3FCA8D3CC4E760595D588A6B321F910B8F96459DBD42C663506324660A527C66A53B406709262B0E42F11CB0AD2450A1FB2F48EA85C1B39D4408DB9" }
{ "low" : 256, "hi" : 319, "bytes" : "1EC94A21BD2C0408D3E15104FA25D15D6E3E0D3F8070D84184D35B6302BF62AEA282E3640820CC09E1528B684B7400180598D6960EC92E4EC4C9E533E1BA06F1" }
{ "low" : 448, "hi" : 511, "bytes" : "D0AC302C5CC256351E24CFFD11F0BD8A0BE1277EDDCB3EE4D530E051712A710DF4513FD6438B7A355CCF4FEDA9A60F2AC375508F998C642E6C51724FE9462F7F" } ]
xor_digest = "B7F32B6FADB48BB8DA231BDBDC4697232BAE5F8F8345F9F14A991FF851CC3C641DF4913A5C550FC898F95AC299ED89155A434DC4B1E37D82EA137BB763F68BC7"
f()
desc = "Set 2, vector#144"
key = "90909090909090909090909090909090"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "EA869D49E7C75E07B551C24EBE351B4E7FD9CB26413E55A8A977B766650F81EFCA06E30107F76DC97EA9147FFA7CA66AFD4D4DA538CDA1C27E8D948CC406FB89" }
{ "low" : 192, "hi" : 255, "bytes" : "436A8EC10421116CD03BF95A4DAAE6301BB8C724B3D481099C70B26109971CCEACBCE35C8EE98BBB0CD553B5C418112500262C7EA10FAAC8BA9A30A04222D8E2" }
{ "low" : 256, "hi" : 319, "bytes" : "47487A34DE325E79838475B1757D5D293C931F9E57579FCA5E04A40E4A0A38CFD1614F9CEF75F024FFF5D972BD671DC9FB2A80F64E8A2D82C3BAA5DDFD1E6821" }
{ "low" : 448, "hi" : 511, "bytes" : "3FDCAD4E7B069391FAB74C836D58DE2395B27FFAE47D633912AE97E7E3E60264CA0DC540D33122320311C5CFC9E26D632753AC45B6A8E81AC816F5CA3BBDB1D6" } ]
xor_digest = "E30E770C75C94EE022BEA6B95241E5D7163D7C55AAF20FE7150768CEE6E1103742902FA4F928CDCF31335944DCDEBADDE36FE089D2EB93677E9DF75234E1B3C8"
f()
desc = "Set 2, vector#153"
key = "99999999999999999999999999999999"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "7B3AA4599561C9059739C7D18D342CF2E73B3B9E1E85D38EDB41AEFADD81BF241580885078CA10D338598D18B3E4B693155D12D362D533494BA48142AB068F68" }
{ "low" : 192, "hi" : 255, "bytes" : "D27864FC30D5FD278A9FB83FADADFD2FE72CE78A2563C031791D55FF31CF59464BE7422C81968A70E040164603DC0B0AEEE93AC497CC0B770779CE6058BE80CF" }
{ "low" : 256, "hi" : 319, "bytes" : "4C5A87029660B65782FD616F48CFD6006DFB158682DC80E085E52163BE2947E270A0FD74DC8DC2F5920E59F28E225280FAC96BA78B8007E3D0DF6EF7BF835993" }
{ "low" : 448, "hi" : 511, "bytes" : "F5A2ECD04452358970E4F8914FC08E82926ECFF33D9FC0977F10241E7A50E528996A7FB71F79FC30BF881AF6BA19016DDC077ED22C58DC57E2BDBDA1020B30B2" } ]
xor_digest = "8C9995B52F4AC9CA25E5C956850FFE90D396530617298D89659C2F863995FB060B65ADFED6AA977EDBB4FC2F6774335E9DEBC61E05E92718A340F79368E74273"
f()
desc = "Set 2, vector#162"
key = "A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "9776A232A31A22E2F10D203A2A1B60B9D28D64D6D0BF32C8CCA1BBF6B57B1482BCC9FCF7BBE0F8B61C4BF64C540474BCF1F9C1C808CCBE6693668632A4E8653B" }
{ "low" : 192, "hi" : 255, "bytes" : "5C746D64A3195079079028D74CE029A87F72B30B34B6C7459998847C42F2E44D843CF196229EED471B6BBDBA63BE3B529B8AF4B5846EB0AB008261E161707B76" }
{ "low" : 256, "hi" : 319, "bytes" : "F780FE5204AC188A680F41068A9F50182D9154D6D5F1886034C270A8C3AF61DF945381B7ADCA546E153DBF0E6EA2DDDA4EDA3E7F7CF4E2043C5E20AF659282B4" }
{ "low" : 448, "hi" : 511, "bytes" : "71D24CD8B4A70554906A32A5EFDFA8B834C324E6F35240257A0A27485103616DD41C8F4108D1FC76AB72AF166100AB17212492A72099ACF6F9EB53AC50BD8B8B" } ]
xor_digest = "B2217FF55077D373B735C1A7D8B784F5187AF2F028FE906F85B938277CAC918CE87BEA508AFF86B9071F2B7E4F88A3B1F3323151C9DF441FE6F266CF8F01A0B9"
f()
desc = "Set 2, vector#171"
key = "ABABABABABABABABABABABABABABABAB"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "62DF49A919AF1367D2AAF1EB608DE1FDF8B93C2026389CEBE93FA389C6F2845848EBBE70B3A3C8E79061D78E9ED24ED9AA7BB6C1D726AA060AEFC4FFE70F0169" }
{ "low" : 192, "hi" : 255, "bytes" : "E7A4DF0D61453F612FB558D1FAE198AAB1979F91E1792C99423E0C573345936570915B60210F1F9CA8845120E6372659B02A179A4D679E8EDDDDF8843ABAB7A4" }
{ "low" : 256, "hi" : 319, "bytes" : "C9501A02DD6AFB536BD2045917B016B83C5150A7232E945A53B4A61F90C5D0FB6E6AC45182CBF428772049B32C825D1C33290DBEEC9EF3FE69F5EF4FAC95E9B1" }
{ "low" : 448, "hi" : 511, "bytes" : "B8D487CDD057282A0DDF21CE3F421E2AC9696CD36416FA900D12A20199FE001886C904AB629194AECCC28E59A54A135747B7537D4E017B66538E5B1E83F88367" } ]
xor_digest = "4EB0E761F6BD6A738DC295C0B1B737FCFDB2A68FF50EB198D699CC71141EC6EB54434D40B592A65F2F5C50B6027D4F529307969E1D74028FF4BD6A44CEAA121C"
f()
desc = "Set 2, vector#180"
key = "B4B4B4B4B4B4B4B4B4B4B4B4B4B4B4B4"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "6F703F3FF0A49665AC70CD9675902EE78C60FF8BEB931011FC89B0F28D6E176A9AD4D494693187CB5DB08FF727477AE64B2EF7383E76F19731B9E23186212720" }
{ "low" : 192, "hi" : 255, "bytes" : "AD26886ABF6AD6E0CA4E305E468DA1B369F0ADD3E14364C8A95BD78C5F2762B72915264A022AD11B3C6D312B5F6526E0183D581B57973AFB824945BFB78CEB8F" }
{ "low" : 256, "hi" : 319, "bytes" : "FE29F08A5C157B87C600CE4458F274C986451983FE5AE561DF56139FF33755D71100286068A32559B169D8C2161E215DBC32FAEA11B652284795C144CF3E693E" }
{ "low" : 448, "hi" : 511, "bytes" : "7974578366C3E999028FA8318D82AAAA8ED3FD4DFB111CBF0F529C251BA91DC6ACFA9795C90C954CEA287D23AD979028E974393B4C3ABA251BCB6CECCD09210E" } ]
xor_digest = "88BE85838404EA4F0FFDD192C43E3B93329C4A4919234D116E4393EA26110022BED2B427EC719178E6F1A9B9B08BEF5BF2FE4A9CC869CB6BD2D989F750EDA78F"
f()
desc = "Set 2, vector#189"
key = "BDBDBDBDBDBDBDBDBDBDBDBDBDBDBDBD"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "61900F2EF2BEA2F59971C82CDFB52F279D81B444833FF02DD0178A53A8BFB9E1FF3B8D7EC799A7FBB60EADE8B1630C121059AA3E756702FEF9EEE7F233AFC79F" }
{ "low" : 192, "hi" : 255, "bytes" : "D27E0784038D1B13833ACD396413FF10D35F3C5C04A710FC58313EEBC1113B2CFA20CBD1AEA4433C6650F16E7C3B68302E5F6B58D8E4F26D91F19FE981DEF939" }
{ "low" : 256, "hi" : 319, "bytes" : "B658FB693E80CE50E3F64B910B660BEB142B4C4B61466424A9884D22EB80B8B40C26BEA869118ED068DCC83F9E4C68F17A3597D0FE0E36700D01B4252EE0010E" }
{ "low" : 448, "hi" : 511, "bytes" : "9FC658A20D3107A34680CC75EB3F76D6A2150490E9F6A3428C9AD57F2A252385C956B01C31C978E219BE351A534DB23B99908DACC6726196742D0B7E1D88472C" } ]
xor_digest = "DA74A6EC8D54723B1797751F786CB1B517995EBF297A034AF744EEF86833CC5BA3DCBDB4D3FAB47F5BA37463CEC80F45DAE1A48FBB80148A39CA789BAE09D39F"
f()
desc = "Set 2, vector#198"
key = "C6C6C6C6C6C6C6C6C6C6C6C6C6C6C6C6"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "42D1C40F11588014006445E81C8219C4370E55E06731E09514956834B2047EE28A9DAECC7EB25F34A311CC8EA28EDCD24A539160A0D8FDAA1A26E9F0CDFE0BE3" }
{ "low" : 192, "hi" : 255, "bytes" : "976201744266DEABBA3BFE206295F40E8D9D169475C11659ADA3F6F25F11CEF8CD6B851B1F72CD3E7D6F0ABAF8FB929DDB7CF0C7B128B4E4C2C977297B2C5FC9" }
{ "low" : 256, "hi" : 319, "bytes" : "D3601C4CD44BBEEFD5DAD1BDFF12C190A5F0B0CE95C019972863F4309CE566DE62BECB0C5F43360A9A09EB5BAB87CF13E7AB42D71D5E1229AF88667D95E8C96F" }
{ "low" : 448, "hi" : 511, "bytes" : "69EAA4BAAAA795BCF3B96E79C931A1F2D2DD16A242714358B106F38C1234A5BBD269E68A03539EFAFA79455ADBE1B984E9766B0720947E1365FDF076F73639CD" } ]
xor_digest = "54E422EB1EB2DBDB338798E0D352A87AD5F5A28BC5F77E1B42913E6500723A936D4019D703DC93A1DF7C65AB74F1FC1A4D38C519A8338B73A435FC7491DFC769"
f()
desc = "Set 2, vector#207"
key = "CFCFCFCFCFCFCFCFCFCFCFCFCFCFCFCF"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "9C09F353BF5ED33EDEF88D73985A14DBC1390F08236461F08FDCAF9A7699FD7C4C602BE458B3437CEB1464F451ED021A0E1C906BA59C73A8BA745979AF213E35" }
{ "low" : 192, "hi" : 255, "bytes" : "437E3C1DE32B0DB2F0A57E41A7282670AC223D9FD958D111A8B45A70A1F863E2989A97386758D44060F6BFFF5434C90888B4BB4EDAE6528AAADC7B81B8C7BEA3" }
{ "low" : 256, "hi" : 319, "bytes" : "94007100350C946B6D12B7C6A2FD1215682C867257C12C74E343B79E3DE79A782D74663347D8E633D8BE9D288A2A64A855C71B4496587ADECCB4F30706BB4BD9" }
{ "low" : 448, "hi" : 511, "bytes" : "585D0C2DB901F4004846ADBAA754BCA82B66A94C9AF06C914E3751243B87581AFAE281312A492DBEE8D6BB64DD748F445EF88F82AB44CBA33D767678914BDE77" } ]
xor_digest = "BB97F09B9FCEC06B6124310BBDD1E9CE8D3793F62FF1337F520DE2A90FE2592AF2636DFA20466FDAA9329443ACC0E9A50492621AF5790CAE5642E6F7D9AF400D"
f()
desc = "Set 2, vector#216"
key = "D8D8D8D8D8D8D8D8D8D8D8D8D8D8D8D8"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "4965F30797EE95156A0C141D2ACA523204DD7C0F89C6B3F5A2AC1C59B8CF0DA401B3906A6A3C94DA1F1E0046BD895052CB9E95F667407B4EE9E579D7A2C91861" }
{ "low" : 192, "hi" : 255, "bytes" : "8EDF23D6C8B062593C6F32360BF271B7ACEC1A4F7B66BF964DFB6C0BD93217BBC5FACC720B286E93D3E9B31FA8C4C762DF1F8A3836A8FD8ACBA384B8093E0817" }
{ "low" : 256, "hi" : 319, "bytes" : "44FA82E9E469170BA6E5E8833117DAE9E65401105C5F9FEA0AF682E53A627B4A4A621B63F7CE5265D3DFADFBFD4A2B6C2B40D2249EB0385D959F9FE73B37D67D" }
{ "low" : 448, "hi" : 511, "bytes" : "828BA57593BC4C2ACB0E8E4B8266C1CC095CE9A761FB68FC57D7A2FCFF768EFB39629D3378549FEE08CCF48A4A4DC2DD17E72A1454B7FA82E2ACF90B4B8370A7" } ]
xor_digest = "8A365EE7E7BC9198EC88A39F5047431D1632CBB0D1E812957595E7A0763DFA46953070863838812A9504F7A376078FEA9444B27E15FC043AE2D375D37DB1C6C3"
f()
desc = "Set 2, vector#225"
key = "E1E1E1E1E1E1E1E1E1E1E1E1E1E1E1E1"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "5C7BA38DF4789D45C75FCC71EC9E5751B3A60AD62367952C6A87C0657D6DB3E71053AC73E75FF4B66177B3325B1BBE69AEE30AD5867D68B660603FE4F0BF8AA6" }
{ "low" : 192, "hi" : 255, "bytes" : "B9C7460E3B6C313BA17F7AE115FC6A8A499943C70BE40B8EF9842C8A934061E1E9CB9B4ED3503165C528CA6E0CF2622BB1F16D24657BDAEDB9BA8F9E193B65EB" }
{ "low" : 256, "hi" : 319, "bytes" : "406CD92883E991057DFD80BC8201067F35700264A4DFC28CF23EE32573DCB42091FEF27548613999E5C5463E840FE95760CF80CC5A05A74DE49E7724273C9EA6" }
{ "low" : 448, "hi" : 511, "bytes" : "F13D615B49786D74B6591BA6887A7669136F34B69D31412D4A9CB90234DAFCC41551743113701EF6191A577C7DB72E2CB723C738317848F7CC917E1510F02791" } ]
xor_digest = "B31C13C287692760C2710CC4812A4CD3535248839E0B5220185BE58BBCE6A70D629E0749D40D9E79F698FFAFF7B9C53006419AAAD9AC1FAC2286F66DEC96AEB3"
f()
desc = "Set 2, vector#234"
key = "EAEAEAEAEAEAEAEAEAEAEAEAEAEAEAEA"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "5B06F5B01529B8C57B73A410A61DD757FE5810970AA0CBFAD3404F17E7C7B6459DD7F615913A0EF2DCC91AFC57FA660D6C7352B537C65CD090F1DE51C1036AB5" }
{ "low" : 192, "hi" : 255, "bytes" : "0F613F9E9F03199DF0D0A5C5BE253CDF138903876DE7F7B0F40B2F840F322F270C0618D05ABB1F013D8744B231555A8ECB14A9E9C9AF39EDA91D36700F1C25B3" }
{ "low" : 256, "hi" : 319, "bytes" : "4D9FAB87C56867A687A03BF3EDCC224AC54D04450AB6F78A642715AF62CF519215E2CDF5338E45554B852B6FB552BCAF5C599BDF9FA679962F038976CDA2DEFA" }
{ "low" : 448, "hi" : 511, "bytes" : "E0F80A9BF168EB523FD9D48F19CA96A18F89C1CF11A3ED6EC8AEAB99082DE99BE46DE2FB23BE4A305F185CF3A8EA377CCA1EF46FD3192D03DCAE13B79960FEF4" } ]
xor_digest = "AB020EA09B2573D7106EAA1D177F2E4A1F8E2237AD1481F9923DDF973A79CFC21A0B8CDDD22D3D78C488D0CC9BE8FAA8C74F0F2CFE619B7D7EA5B2E697E23372"
f()
desc = "Set 2, vector#243"
key = "F3F3F3F3F3F3F3F3F3F3F3F3F3F3F3F3"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "E7BC9C13F83F51E8855E83B81AF1FFB9676300ABAB85986B0B44441DDEFAB83B8569C4732D8D991696BD7B6694C6CB20872A2D4542192BE81AA7FF8C1634FC61" }
{ "low" : 192, "hi" : 255, "bytes" : "0B429A2957CBD422E94012B49C443CBC2E13EFDE3B867C6018BABFDE9ED3B8036A913C770D77C60DCD91F23E03B3A57666847B1CACFCBCFF57D9F2A2BAD6131D" }
{ "low" : 256, "hi" : 319, "bytes" : "EA2CBD32269BB804DD2D641452DC09F964CB2BCD714180E94609C1209A8C26D1256067F1B86AA4F886BB3602CF96B4DD7039F0326CD24D7C2D69DE22D9E24624" }
{ "low" : 448, "hi" : 511, "bytes" : "CA0DD398EA7E543F1F680BF83E2B773BBB5B0A931DEADDEC0884F7B823FC686E71D7E4C033C65B03B292426CE4E1A7A8A9D037303E6D1F0F45FDFB0FFE322F93" } ]
xor_digest = "0D67BC1CFE545A6AE2F51A7FB2F32FC62E08707F9CBF2E08245E4594E9DB2A7ECBB6AB7190831C3D7D8F9D606231668E447C4EA29D69B4344952A97A77CC71CB"
f()
desc = "Set 2, vector#252"
key = "FCFCFCFCFCFCFCFCFCFCFCFCFCFCFCFC"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "C93DA97CB6851BCB95ABFAF547C20DF8A54836178971F748CF6D49AEF3C9CE8CE7D284571D871EFD51B6A897AF698CD8F2B050B6EB21A1A58A9FC77200B1A032" }
{ "low" : 192, "hi" : 255, "bytes" : "5B4144FD0C46CEE4348B598EEF76D16B1A71CBF85F4D9926402133846136C59FBE577B8B7EB8D6A67A48358573C068766AC76A308A14154E2FA9BD9DCA8842E6" }
{ "low" : 256, "hi" : 319, "bytes" : "3BF67A79DF6FE3C32DA7A53CD0D3723716A99BF7D168A25C93C29DF2945D9BCBF78B669195411BD86D3F890A462734AB10F488E9952334D7242E51AC6D886D60" }
{ "low" : 448, "hi" : 511, "bytes" : "65629AA9654930681578EEC971A48D8390FBF82469A385B8BCF28B2C1E9F13CEFC06F54335B4D5DE011F3DCE2B94D38F1A04871E273FCD2A8FA32C0E08710E69" } ]
xor_digest = "E308FAEC064EC30CA1BEA7C2A02E95F4ABCBF7D7762557BE9872726F9020162F9B4EA11F621426EED6297C947BB3FAC269A8D0F38672EFBD72FDCCBEB8475221"
f()
desc = "Set 3, vector# 0"
key = "000102030405060708090A0B0C0D0E0F"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "2DD5C3F7BA2B20F76802410C688688895AD8C1BD4EA6C9B140FB9B90E21049BF583F527970EBC1A4C4C5AF117A5940D92B98895B1902F02BF6E9BEF8D6B4CCBE" }
{ "low" : 192, "hi" : 255, "bytes" : "AB56CC2C5BFFEF174BBE28C48A17039ECB795F4C2541E2F4AE5C69CA7FC2DED4D39B2C7B936ACD5C2ECD4719FD6A3188323A14490281CBE8DAC48E4664FF3D3B" }
{ "low" : 256, "hi" : 319, "bytes" : "9A18E827C33633E932FC431D697F0775B4C5B0AD26D1ACD5A643E3A01A06582142A43F48E5D3D9A91858887310D39969D65E7DB788AFE27D03CD985641967357" }
{ "low" : 448, "hi" : 511, "bytes" : "752357191E8041ABB8B5761FAF9CB9D73072E10B4A3ED8C6ADA2B05CBBAC298F2ED6448360F63A51E073DE02338DBAF2A8384157329BC31A1036BBB4CBFEE660" } ]
xor_digest = "F3BCF4D6381742839C5627050D4B227FEB1ECCC527BF605C4CB9D6FB0618F419B51846707550BBEEE381E44A50A406D020C8433D08B19C98EFC867ED9897EDBB"
f()
desc = "Set 3, vector# 9"
key = "090A0B0C0D0E0F101112131415161718"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "0F8DB5661F92FB1E7C760741430E15BB36CD93850A901F88C40AB5D03C3C5FCE71E8F16E239795862BEC37F63490335BB13CD83F86225C8257AB682341C2D357" }
{ "low" : 192, "hi" : 255, "bytes" : "002734084DF7F9D6613508E587A4DD421D317B45A6918B48E007F53BEB3685A9235E5F2A7FACC41461B1C22DC55BF82B54468C8523508167AAF83ABBFC39C67B" }
{ "low" : 256, "hi" : 319, "bytes" : "3C9F43ED10724681186AC02ACFEC1A3A090E6C9AC1D1BC92A5DBF407664EBCF4563676257518554C90656AC1D4F167B8B0D3839EB8C9E9B127665DCE0B1FD78C" }
{ "low" : 448, "hi" : 511, "bytes" : "46B7C56E7ED713AAB757B24056AF58C6AD3C86270CFEAE4AADB35F0DB2D969321A38388D00ED9C2AD3A3F6D8BE0DE7F7ADA068F67525A0996DE5E4DF490DF700" } ]
xor_digest = "FDAEDE318DDD9EE44670318D51E812A2F9B6EAEB18B9EBDC0FB76D95CD0AE8C95792F6EA71332404798505D947B89B041D56FAD3B0D92BEC06428EC5A841EB82"
f()
desc = "Set 3, vector# 18"
key = "12131415161718191A1B1C1D1E1F2021"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "4B135E9A5C9D54E6E019B5A2B48B9E6E17F6E6667B9D43BC3F892AD6ED64C5844FE52F75BD67F5C01523EE026A3851083FBA5AC0B6080CE3E6A2F5A65808B0AC" }
{ "low" : 192, "hi" : 255, "bytes" : "E45A7A605BCFBBE77E781BBE78C270C5AC7DAD21F015E90517672F1553724DDA12692D23EC7E0B420A93D249C438356622D45809034A1A92B3DE34AEB4421168" }
{ "low" : 256, "hi" : 319, "bytes" : "14DEA7F82A4D3C1796C3911ABC2EFE9DC9EB79C42F72691F8CB8C353ECBCC0DC6159EC13DFC08442F99F0F68355D704E5649D8B34836B5D2C46F8999CD570B17" }
{ "low" : 448, "hi" : 511, "bytes" : "CA6A357766527EA439B56C970E2E089C30C94E62CB07D7FE1B1403540C2DA9A6362732811EF811C9D04ED4880DC0038D5FDCE22BDE2668CD75107D7926EC98B5" } ]
xor_digest = "DE518E6B67BAEC2A516CCAB0475341C4BCC652ABE49ECCAA64E87248441A8F727BE173CACEBF8895B07DE8DDD28F1EE8AA739855F1E6DB70765AB1B55BC3B1ED"
f()
desc = "Set 3, vector# 27"
key = "1B1C1D1E1F202122232425262728292A"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "E04A423EF2E928DCA81E10541980CDE5C8054CC3CF437025B629C13677D4116721123EE13F889A991C03A2E5ADC0B12B9BBC63CB60A23543445919AF49EBC829" }
{ "low" : 192, "hi" : 255, "bytes" : "F6E1D7DBD22E05430EBFBEA15E751C8376B4743681DE6AC3E257A3C3C1F9EC6A63D0A04BF3A07F64E6B167A49CD3FDAAB89A05E438B1847E0DC6E9108A8D4C71" }
{ "low" : 256, "hi" : 319, "bytes" : "FC2B2A1A96CF2C73A8901D334462ED56D57ABD985E4F2210D7366456D2D1CDF3F99DFDB271348D00C7E3F51E6738218D9CD0DDEFF12341F295E762C50A50D228" }
{ "low" : 448, "hi" : 511, "bytes" : "1F324485CC29D2EAEC7B31AE7664E8D2C97517A378A9B8184F50801524867D376652416A0CA96EE64DDF26138DB5C58A3B22EF9037E74A9685162EE3DB174A0E" } ]
xor_digest = "697048C59621DBC7D47B6BE93A5060C4B2DFBDB1E7E444F1FC292C06C12974D126EA9C8FD09C63945E4D9107CD0A1AC57161CA8C7CFEF55CB60E52666C705EC6"
f()
desc = "Set 3, vector# 36"
key = "2425262728292A2B2C2D2E2F30313233"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "361A977EEB47543EC9400647C0C169784C852F268B34C5B163BCA81CFC5E746F10CDB464A4B1365F3F44364331568DB2C4707BF81AA0E0B3AB585B9CE6621E64" }
{ "low" : 192, "hi" : 255, "bytes" : "E0F8B9826B20AEEC540EABA9D12AB8EB636C979B38DE75B87102C9B441876C39C2A5FD54E3B7AB28BE342E377A3288956C1A2645B6B76E8B1E21F871699F627E" }
{ "low" : 256, "hi" : 319, "bytes" : "850464EEED2251D2B5E2FE6AE2C11663E63A02E30F59186172D625CFF2A646FACB85DC275C7CA2AF1B61B95F22A5554FBAD63C0DCC4B5B333A29D270B6366AEF" }
{ "low" : 448, "hi" : 511, "bytes" : "4387292615C564C860AE78460BBEC30DECDFBCD60AD2430280E3927353CEBC21DF53F7FD16858EF7542946442A26A1C3DA4CEFF5C4B781AD6210388B7905D2C7" } ]
xor_digest = "2FADEF81A5C4051CAC55E16C68CC6EEFCEE2D4966BAE782E3D885CAA2271EFBBE33F9313FD00632DC73441823713A48794C21E812E30A1DD4B2AE858A27E7C88"
f()
desc = "Set 3, vector# 45"
key = "2D2E2F303132333435363738393A3B3C"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "9F25D8BD7FBC7102A61CB590CC69D1C72B31425F11A685B80EAC771178030AF052802311ED605FF07E81AD7AAC79B6A81B24113DB5B4F927E6481E3F2D750AB2" }
{ "low" : 192, "hi" : 255, "bytes" : "DAEF37444CB2B068124E074BAD1881953D61D5BA3BFBF37B21BC47935D74820E9187086CEF67EB86C88DDD62C48B9089A9381750DC55EA4736232AE3EDB9BFFE" }
{ "low" : 256, "hi" : 319, "bytes" : "B6C621F00A573B60571990A95A4FEC4AC2CA889C70D662BB4FF54C8FAAE0B7C45B8EC5414AE0F080B68E2943ABF76EA2ABB83F9F93EF94CB3CFE9A4CEED337CD" }
{ "low" : 448, "hi" : 511, "bytes" : "6F17EAE9346878BB98C97F6C81DD2E415FDEB54305FE2DF74AFC65627C376359FB2E7841FF75744A715DF952851C1CBCDD241BADF37B3618E0097B3A084E1B54" } ]
xor_digest = "8D1890B66A56552BE334B3472344F53DD2782D4ABB4514D0F5B761436C99740202A4B1244A1A7F485EFDB52C0065263FEE5A7D7DFC2BB754304CE9B2724119EB"
f()
desc = "Set 3, vector# 54"
key = "363738393A3B3C3D3E3F404142434445"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "3466360F26B76484D0C4FD63965E55618BDBFDB2213D8CA5A72F2FE6E0A13548D06E87C8A6EEA392FE52D3F5E0F6559D331828E96A07D99C6C0A42EFC24BA96D" }
{ "low" : 192, "hi" : 255, "bytes" : "AB7184066D8E0AB537BB24D777088BC441E00481834B5DD5F6297D6F221532BC56F638A8C84D42F322767D3D1E11A3C65085A8CA239A4FDD1CDF2AC72C1E354F" }
{ "low" : 256, "hi" : 319, "bytes" : "55F29F112B07544EDA3EBB5892DBB91E46F8CBC905D0681D8E7109DF816ABFB8AE6A0F9833CDF34A29F25D67A60D36338A10346FEBE72CCF238D8670C9F2B59C" }
{ "low" : 448, "hi" : 511, "bytes" : "0657453B7806D9EA777FFFBE05028C76DCFF718BC9B6402A3CAEC3BCCB7231E6D3DDB00D5A9637E1E714F47221FFCC11B1425D9653F7D777292B146556A89787" } ]
xor_digest = "C2A8D317E3B1CB884A2C3B07F11FD38833282A9FBD1F6AF5C33CBE1E18D99B6499A241EA83A56605BC6B99259FBAAED4BDDA788B08CAAA93D2E00C6B5392ECF0"
f()
desc = "Set 3, vector# 63"
key = "3F404142434445464748494A4B4C4D4E"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "40AD59C99464D95702727406E4C82C857FA48911319A3FCC231DC91C990E19D4D9D5972B6A6F21BD12C118365ECAABC89F9C3B63FFF77D8EA3C55B2322B57D0E" }
{ "low" : 192, "hi" : 255, "bytes" : "DBF23042C787DDF6FFCE32A792E39DF9E0332B0A2A2F2A5F96A14F51FAAB7C2714E07C3ADCA32D0DE5F8968870C7F0E81FE263352C1283965F8C210FC25DE713" }
{ "low" : 256, "hi" : 319, "bytes" : "455E3D1F5F44697DA562CC6BF77B93099C4AFAB9F7F300B44AD9783A9622BD543EFDB027D8E71236B52BEE57DD2FB3EE1F5B9022AB96A59AE7DF50E6933B3209" }
{ "low" : 448, "hi" : 511, "bytes" : "F11D47D8C57BBF862E0D6238BC0BF6A52500A62BB037B3A33E87525259B8E54735F664FCEDF11BA2C0F3AEB9C944BCE77FFD26D604674DF8905A73CB7E230A4F" } ]
xor_digest = "F021DE2B24C80A48DE6F7F807F1EF2F813D72A77E7BFC12515F9F5755CEFF64CB5829CA780627A7920F3963E28005677B85A56017A6F5A403DA49F8F8B71581D"
f()
desc = "Set 3, vector# 72"
key = "48494A4B4C4D4E4F5051525354555657"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "D8B1A4CB2A5A8DE1F798254A41F61DD4FB1226A1B4C62FD70E87B6ED7D57902A69642E7E21A71C6DC6D5430DCE89F16FCCC9AAD48743974473753A6FF7663FD9" }
{ "low" : 192, "hi" : 255, "bytes" : "D4BA9BC857F74A28CACC734844849C3EDCB9FB952023C97E80F5BFA445178CAB92B4D9AA8A6D4E79B81993B831C7376510E74E30E7E68AD3188F8817DA8243F2" }
{ "low" : 256, "hi" : 319, "bytes" : "B7039E6F6C4D5D7F750ED014E650118817994F0D3C31B071CC16932A412E627D2486CCB9E43FCA79039D3E0F63577406F5B6420F5587CF9DAC40118AA6F170A8" }
{ "low" : 448, "hi" : 511, "bytes" : "1ABA14E7E9E6BA4821774CBC2B63F410381E4D661F82BAB1B182005B6D42900DC658C6224F959E05095BC8081920C8AD11148D4F8BD746B3F0059E15C47B9414" } ]
xor_digest = "AD0620EB4E71605CDEA447A02E638F0C2A0096EA666010761DB03CFC8562968044D213B15EC69E1E5811EEBE7C96B6166BE36E42B16F9F4BE0CC71B456C1FCA1"
f()
desc = "Set 3, vector# 81"
key = "5152535455565758595A5B5C5D5E5F60"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "235E55E2759C6781BBB947133EDD4D91C9746E7E4B2E5EF833A92BE6086C57C6729655D4C4253EC17ACF359012E801757E7A6EB0F713DEC40491266604B83311" }
{ "low" : 192, "hi" : 255, "bytes" : "247BEAAC4A785EF1A55B469A1AEE853027B2D37C74B8DA58A8B92F1360968513C0296585E6745E727C34FFCE80F5C72F850B999721E3BF1B6C3A019DBEE464C1" }
{ "low" : 256, "hi" : 319, "bytes" : "E7DDB25678BF6EECA2DA2390C9F333EB61CD899DD823E7C19474643A4DA313352556E44A9C0006C8D54B1FD0313D574A08B86138394BA1194E140A62A96D7F01" }
{ "low" : 448, "hi" : 511, "bytes" : "DB417F9C1D9FD49FC96DB5E981F0C3F8484E3BDC559473963D12D982FEA287A39A36D69DDBBCF1CA2C9FB7F4B2B37F3DA755838A67C48822F4C1E82E65A07151" } ]
xor_digest = "119D1DDC7C95982B6B035FD4A4D8C5C9FD2518FFBC69C3C6A7F600174A3916146287F19BDDDAB385D2C6A39C593935F288B2F3E8895B9519EC71BA453319CC1F"
f()
desc = "Set 3, vector# 90"
key = "5A5B5C5D5E5F60616263646566676869"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "F27A0A59FA3D1274D934EACCFA0038AFC3B866D2BFA4A8BA81D698DBCA5B65D52F3A1AC9855BEEEB3B41C510F7489E35AB22CB4444816208C282C461FF16A7BC" }
{ "low" : 192, "hi" : 255, "bytes" : "522594154A2E4843083ABCA886102DA814500C5AADAAB0C8FB40381B1D750F9DA9A1831D8000B30BD1EFA854DC903D63D53CD80A10D642E332DFFC9523792150" }
{ "low" : 256, "hi" : 319, "bytes" : "5D092D8E8DDA6C878A3CFBC1EC8DD13F2A1B073916097AEC4C3E56A229D8E282DDB656DAD60DBC7DF44DF124B19920FCC27FCADB1782F1B73E0A78C161270700" }
{ "low" : 448, "hi" : 511, "bytes" : "8F75BF72995AD23E9ADFEA351F26E42BE2BE8D67FB810ABCBD5FAE552DC10D1E281D94D5239A4EA311784D7AC7A764FA88C7FD7789E803D11E65DD6AC0F9E563" } ]
xor_digest = "55AC113CC018689601F39AA80FA4FA26EE655D40F315C6B694FFAE74A09D382B62A4E7C60F75167361871A82561FFAC453BFED061D6B01672008308C92D241FF"
f()
desc = "Set 3, vector# 99"
key = "636465666768696A6B6C6D6E6F707172"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "654037B9120AEB60BD08CC07FFEC5985C914DAD04CD1277312B4264582A4D85A4CB7B6CC0EB8AD16475AD8AE99888BC3FDE6A5B744851C5FC77EAB50CFAD021D" }
{ "low" : 192, "hi" : 255, "bytes" : "E52D332CD0DE31F44CDCAB6C71BD38C94417870829D3E2CFDAC40137D066EA482786F146137491B8B9BC05675C4F88A8B58686E18D63BE71B6FEFEF8E46D0273" }
{ "low" : 256, "hi" : 319, "bytes" : "28959548CE505007768B1AA6867D2C009F969675D6E6D54496F0CC1DC8DD1AFBA739E8565323749EAA7B03387922C50B982CB8BC7D602B9B19C05CD2B87324F9" }
{ "low" : 448, "hi" : 511, "bytes" : "D420AEC936801FEE65E7D6542B37C9190E7DB10A5934D3617066BEA8CC80B8EAAAFC82F2860FA760776418B4FF148DFD58F21D322909E7BF0EC19010A168FAF7" } ]
xor_digest = "5BAFB9BEA29B3658A5BBF649E09455B70FB262AB938B65FE71652A0662FF0FB514C35AF438A72A6122AC1AA8591477AEAEB78214C63E41255E87230481D1A793"
f()
desc = "Set 3, vector#108"
key = "6C6D6E6F707172737475767778797A7B"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "0DB7EA55A79C045818C29E99D8A4B66433E4C77DF532D71BA720BD5D82629F1276EF0BF93E636A6F71F91B947DFA7CAAA1B0512AA531603197B86ABA2B0829D1" }
{ "low" : 192, "hi" : 255, "bytes" : "A62EAFD63CED0D5CE9763609697E78A759A797868B94869EC54B44887D907F01542028DEDDF420496DE84B5DA9C6A4012C3D39DF6D46CE90DD45AF10FA0F8AAF" }
{ "low" : 256, "hi" : 319, "bytes" : "7C2AD3F01023BC8E49C5B36AFE7E67DCA26CCD504C222BD6AF467D4C6B07B79261E9714FDD1E35C31DA4B44DB8D4FC0569F885F880E63B5ABB6BA0BFEE2CE80C" }
{ "low" : 448, "hi" : 511, "bytes" : "066D3C8D46F45891430A85852FF537448EBDD6CE8A799CCF7EAF88425FBD60D32A1741B39CC3C73371C2C9A36544D3C3B0F02D2596ACC61C60A6671F112F185E" } ]
xor_digest = "6EE5BF7E194B03A7DDC92FC74A398FF822471FEF6DD399426F7372E445E1EE365ED7164CD09120A79CCF03D0A2A309DC5932441B64DDC6FDC9E183DA9F825106"
f()
desc = "Set 3, vector#117"
key = "75767778797A7B7C7D7E7F8081828384"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "3FE4BD60364BAB4F323DB8097EC189E2A43ACD0F5FFA5D65D8BDB0D79588AA9D86669E143FD5915C31F7283F1180FCABCDCB64B680F2B63BFBA2AF3FC9836307" }
{ "low" : 192, "hi" : 255, "bytes" : "F1788B6CA473D314F6310675FC7162528285A538B4C1BE58D45C97349C8A36057774A4F0E057311EEA0D41DFDF131D4732E2EAACA1AB09233F8124668881E580" }
{ "low" : 256, "hi" : 319, "bytes" : "FEF434B35F024801A77400B31BD0E73522BEC7D10D8BF8743F991322C660B4FD2CEE5A9FDE0D614DE8919487CBD5C6D13FEB55C254F96094378C72D8316A8936" }
{ "low" : 448, "hi" : 511, "bytes" : "338FD71531C8D07732FD7F9145BBC368932E3F3E4C72D2200A4F780AF7B2C3AA91C1ED44DBEAA9A2F1B3C64DCE8DCD27B307A4104D5C755693D848BEA2C2D23B" } ]
xor_digest = "7ABF3C4E6E8CCAC05AA336DF2156E1957DFDAD45995FF6268B9708DAED9C2097F8F0F2A0EE5FBF4A7B511ED2E8E5617993E915E9BAABA30D758A9691E9D8578A"
f()
desc = "Set 3, vector#126"
key = "7E7F808182838485868788898A8B8C8D"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "062187DAA84742580D76E1D55EE4DE2E3B0C454F383CFDDE567A008E4E8DAA3CE645D5BEDA64A23F0522D8C15E6DA0AD88421577A78F2A4466BD0BFA243DA160" }
{ "low" : 192, "hi" : 255, "bytes" : "4CC379C5CF66AA9FB0850E50ED8CC58B72E8441361904449DAABF04D3C464DE4D56B22210B4336113DAA1A19E1E15339F047DA5A55379C0E1FE448A20BC10266" }
{ "low" : 256, "hi" : 319, "bytes" : "BD2C0F58DBD757240AEB55E06D5526FE7088123CE2F7386699C3E2780F5C3F86374B7CB9505299D639B89D7C717BA8A2AEED0C529F22F8C5006913D1BE647275" }
{ "low" : 448, "hi" : 511, "bytes" : "54D61231409D85E46023ED5EFF8FDC1F7A83CACDDB82DD8D1FA7CDEA0E088A61D02BCE7FA7EC3B73B66953DA467BE4B912EBE2A46B56A8BF0D925A919B7B22E3" } ]
xor_digest = "9F569A8133067D1D4651BAE70DB3FE201649A1DA469C7D7C0B0DF16968285BF4ED0F36ED1CF9F213B2EC4BFF83D455FFC8B19E82DAE61408141F221C255DDFAB"
f()
desc = "Set 3, vector#135"
key = "8788898A8B8C8D8E8F90919293949596"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "1A74C21E0C929282548AD36F5D6AD360E3A9100933D871388F34DAFB286471AED6ACC48B470476DC5C2BB593F59DC17EF772F56922391BF23A0B2E80D65FA193" }
{ "low" : 192, "hi" : 255, "bytes" : "B9C8DAC399EF111DE678A9BD8EC24F340F6F785B19984328B13F78072666955AB837C4E51AC95C36ECBEFFC07D9B37F2EE9981E8CF49FD5BA0EADDE2CA37CC8D" }
{ "low" : 256, "hi" : 319, "bytes" : "3B0283B5A95280B58CEC0A8D65328A7A8F3655A4B39ECBE88C6322E93011E13CFF0A370844851F4C5605504E8266B301DD9B915CA8DCD72E169AEA2033296D7F" }
{ "low" : 448, "hi" : 511, "bytes" : "4F9CA1676901DDC313D4EE17B815F6B5AC11AF03BF02517FB3B10E9302FCBF67C284B5C7612BBE7249365BCAC07FD4C2C7AE78F3FDA1880B2DAA20E4EC70F93B" } ]
xor_digest = "9B9EA936FD4385D3516304BEFC44BC6D5B60C97925B52CE269F2843496DEBD335A07ADA2EC87BA27E306CFFB884935D774EE317C7307740B884095278D1DB0C2"
f()
desc = "Set 3, vector#144"
key = "909192939495969798999A9B9C9D9E9F"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "0281FB6B767A90231AB6A19EB1E4FB76A041063FE23AC835797DFA178CC2D7C28DFAD591D2EAF26A985332F8DC74537DF7E0A5F26946BCF7D70B6C3D9DD859D2" }
{ "low" : 192, "hi" : 255, "bytes" : "088ED6D7AB26EEC97518EBF387B0644FD22266E578F141A7218F94AE2EE5885A67A9FA304F6880A781EE05C1251A7EAD4C3025D833B59739C68D3D7F3A844148" }
{ "low" : 256, "hi" : 319, "bytes" : "6B48D13EC0EB1CD0CDAC5D5E09DC7BE4AE02BE4283DDC7FA68E802A31508E6EA7197E5AC10805FDEB6824AEEF8178BAA45D7E419CF9237155D379B38F994EF98" }
{ "low" : 448, "hi" : 511, "bytes" : "7E71823935822D048B67103FF56A709A25517DCE5CFBB807B496EEF79EFFBCD10D23BAD02758814F593B2CD4AC062699AEC02B25A7E0D1BAE598AFDBE4333FE7" } ]
xor_digest = "0D4802AF0B0F92FFF2F80FE65FE5D1FBDFEF122231028FE36CC164D1D39185A1869AD43D08C6E1C9F8A9113CE2CEF0A022629C6FAC1C27E6DDF2A46C52293681"
f()
desc = "Set 3, vector#153"
key = "999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "D4ACE9BF4A76822D685E93E7F77F2A7946A76E3BF0910854C960331A41835D40902BC1CF3F8A30D4C8391087EC3A03D881E4734A5B830EFD55DA84159879D97F" }
{ "low" : 192, "hi" : 255, "bytes" : "5BD8BB7ED009652150E62CF6A17503BAE55A9F4ECD45B5E2C60DB74E9AE6C8BF44C71000912442E24ED2816243A7794D5B1203A246E40BE02F285294399388B1" }
{ "low" : 256, "hi" : 319, "bytes" : "55433BDEA349E8849D7DF899193F029A9F09405D7AFE842CB2C79F0E55C88913B0776825D8D036A69DDDCD6AFCA6588F69F0946A86D32C3585F3813B8CCB56AF" }
{ "low" : 448, "hi" : 511, "bytes" : "0B67F00FA0BB7D1ED5E4B46A687948645239422656F77EF2AFEA34FFF98DA7A890970F09137AF0FABD754C296DD3C6F27539BC3AE78FFA6CDCCC75E944660BB4" } ]
xor_digest = "9D6D8BAB5F6EDB5450EA2D5751741351199ED720B0572410FD698C99F2E0DB92C0E62E68AEE0CC6CDB6EA8898BFD29E8E106470DE4E5C66F94FE0258A2D24CA3"
f()
desc = "Set 3, vector#162"
key = "A2A3A4A5A6A7A8A9AAABACADAEAFB0B1"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "92A067C3724F662120C25FAF4B9EC419C392D98E5CB8C5EE5842C1D5C704DE878C8C68C55BA83D63C5DEEC24CFF7230D3F6FBF6E49520C20CFE422798C676A47" }
{ "low" : 192, "hi" : 255, "bytes" : "133C9A30B917C583D84FB0AAC2C63B5F6758AC8C2951196E9460ADBE3417D91490F0A195DC5682F984069506CA75DC1D79A7AE1DCDF9E0219D4E6A005BA72EDD" }
{ "low" : 256, "hi" : 319, "bytes" : "091D38749503B63238B1E3260855B76C5CFE9D012265FB7F58EB8CAA76B456459C54F051274DDAE06BEC6D7EB8B9FF595302D9D68F2AF1057581D5EE97CCEEDD" }
{ "low" : 448, "hi" : 511, "bytes" : "3FCCB960792B7136768BBA4C3D69C59788F04602C10848A7BCBED112F860998D9E9A788998D1DC760F7ECF40597446D8F39CD4D4013F472BB125DE6A43E9799D" } ]
xor_digest = "12464226235C1DDDAFA37DF12F3A044442C0EEE521DBB7B3239C86ADB61AD6A0A418D3804252DC3658A3AE82473023A8D190E1EDB1DAFA3CF566573511CF8F19"
f()
desc = "Set 3, vector#171"
key = "ABACADAEAFB0B1B2B3B4B5B6B7B8B9BA"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "AC3DE1B9F6DF6D6117B671A639BF076124A0A6D293B107554E9D662A8BFC3F3417C59437C981A0FDF9853EDF5B9C38FE74072C8B78FE5EBA6B8B970FE0CE8F1F" }
{ "low" : 192, "hi" : 255, "bytes" : "23112BD4E7F978D15F8B16F6EDB130D72F377233C463D710F302B9D7844C8A47FB2DFDD60235572859B7AF100149C87F6ED6CE2344CDF917D3E94700B05E2EEF" }
{ "low" : 256, "hi" : 319, "bytes" : "E8DDFE8916B97519B6FCC881AEDDB42F39EC77F64CAB75210B15FBE104B02FC802A775C681E79086D0802A49CE6212F177BF925D10425F7AD199AB06BD4D9802" }
{ "low" : 448, "hi" : 511, "bytes" : "F9D681342E65348868500712C2CA8481D08B7176A751EF880014391A546809926597B10E85761664558F34DA486D3D4454829C2D337BBA3483E62F2D72A0A521" } ]
xor_digest = "75BEFA10DACA457FFE4753A13543F9964CF17E6941318C931575A0865B1C86C12EE5E031EFD125A3D56C4B7846C19484507CC551C5CB558533E288BA0D2C14F1"
f()
desc = "Set 3, vector#180"
key = "B4B5B6B7B8B9BABBBCBDBEBFC0C1C2C3"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "21BD228837BFB3ACB2DFC2B6556002B6A0D63A8A0637533947615E61FE567471B26506B3D3B23F3FDB90DFAC6515961D0F07FD3D9E25B5F31B07E29657E000BF" }
{ "low" : 192, "hi" : 255, "bytes" : "2CF15E4DC1192CA86AA3B3F64841D8C5CD7067696674B6D6AB36533284DA3ABFD96DD87830AE8FA723457BE53CB3404B7A0DCBB4AF48A40FC946C5DEB7BD3A59" }
{ "low" : 256, "hi" : 319, "bytes" : "E3B15D2A87F61C2CE8F37DCEB896B5CA28D1DA6A3A71704309C0175BB61169119D5CBE34FC8F052961FF15F2C8F06CD6F8E889694E2C69E918DD29C33F125D31" }
{ "low" : 448, "hi" : 511, "bytes" : "CCD1C951D6339694972E902166A13033A1B0C07313DC5927FE9FB3910625332C4F0C96A8896E3FC26EFF2AF9484D28B8CB36FF4883634B40C2891FA53B6620B1" } ]
xor_digest = "1E6FA2DF675C21D1AA9819BA05D3C96D3463D6F0758286BBB41A63F8748B94C8B652C60C5D4655E8436F2379CA7088B49625667F386BC5A2F25FD0BFB0088FAA"
f()
desc = "Set 3, vector#189"
key = "BDBEBFC0C1C2C3C4C5C6C7C8C9CACBCC"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "7943AD4AA5F62E08E1AE450E84CFF27DE3B204A2BCA315B981906D5A13F68AB034D3396EA8A41001AF49834368805B37D5380FB14821E3F7F4B44231784306F3" }
{ "low" : 192, "hi" : 255, "bytes" : "415F5381C9A58A29045E77A1E91E6726DFCEBC71E4F52B36DBD7432D158F2ADB31CF5F52D8456952C09B45A16B289B7A32687716B8EDFF0B1E5D0FC16DCCFA88" }
{ "low" : 256, "hi" : 319, "bytes" : "CE317CB853E2AFA22392D4B8AE345A910807F8DE3A14A820CDA771C2F2F3629A65A1CC7A54DDEC182E29B4DACEA5FBFA4FAC8F54338C7B854CD58ABA74A2ACFF" }
{ "low" : 448, "hi" : 511, "bytes" : "5804F61C5C07EC3C2D37DF746E4C96A1AD5E004C2585F3F401CB3AF62CB975F864375BE3A7117079810418B07DABCCEE61B6EC98EA4F28B0D88941CB6BE2B9D2" } ]
xor_digest = "9DBDBD0C3B340F294B1EB42CAD3111F0A5CF6A0B6206976022C6A2D6303A235B717542C25397879A27480D67AC5A245D0C58334CD801764A948060CA6F99E2D6"
f()
desc = "Set 3, vector#198"
key = "C6C7C8C9CACBCCCDCECFD0D1D2D3D4D5"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "A4FB9A02500A1F86145956E16D04975E2A1F9D2283D8AD55C17A9BD6E0C8B5616658132B8928F908FEC7C6D08DBFBC5573449F28AA0EF2884E3A7637233E45CD" }
{ "low" : 192, "hi" : 255, "bytes" : "74D169573560C14692BBE2498FDA0ED7866A11EE4F26BB5B2E9E2559F089B35EC9972634C5A969DD16EB4341782C6C29FBBF4D11ECB4133D1F9CA576963973EB" }
{ "low" : 256, "hi" : 319, "bytes" : "D28966E675759B82EDE324ABA1121B82EAB964AB3E10F0FE9DF3FCC04AFC83863A43FD6B7FC0AD592C93B80BE99207CBA8A55DDEA56DD811AAD3560B9A26DE82" }
{ "low" : 448, "hi" : 511, "bytes" : "E362A817CCD304126E214D7A0C8E9EB93B33EB15DE324DDDFB5C870EA22279C78E28EFF95974C2B935FC9F1BF531D372EF7244D2CC620CEBDE5D8096AD7926B3" } ]
xor_digest = "3DD73F824FD1D9CB55B7E37C9C8A55C7EBB0866564AEA680BBBD431554D89E81FF280B563D5991438CEA5C183C607ADC23CC72CDE3A4D2CEB27B81ED8E5C9215"
f()
desc = "Set 3, vector#207"
key = "CFD0D1D2D3D4D5D6D7D8D9DADBDCDDDE"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "FF879F406EAF43FABC6BE563ADA47C27872647F244C7FAE428E4130F17B471380E1E1CD06C50309760FDEE0BC91C31D0CA797E07B173C6202D2916EEBA9B6D1C" }
{ "low" : 192, "hi" : 255, "bytes" : "61E724B288AECF393483371C1BE653F37BBA313D220173A43459F0BCE195E45C49B3B5FB1B0539DE43B5B4F2960D8E6E5BC81DAF07E9EFBB760881441FA8823B" }
{ "low" : 256, "hi" : 319, "bytes" : "F77AC22945ECD60EBCAF4BA19A59B078B3C3BC36D1DDA6B9969B458C2019D68EFD04D75DDC6041BBCD69747651D2DA7FBED721081F8147367585CABB1C50CF0C" }
{ "low" : 448, "hi" : 511, "bytes" : "7475DCD3545B810445AFCA0C0AFA93A911EA99991A5D639AB32DDF69AA21C45A53DCB998FDAE5F9A82EC8501123EAE3D99351C43311F8430DB3D230E12DA77D2" } ]
xor_digest = "A61CDBCF6F79213D2A789543B0EA3D8A22BA4FB8118C1D40AE56EC823886156620CED8AA76FFE917C1E52060F91EE73BC75E913D072C50B3D939E04F69493553"
f()
desc = "Set 3, vector#216"
key = "D8D9DADBDCDDDEDFE0E1E2E3E4E5E6E7"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "2B4C4185E2FDFAE75DABFF32632FB5D9823359F15E2D17FF74FAC844E5016A4A64C2C47498A15029FBEB6E4893381E656D2A2B9712524827B151C6E67D990388" }
{ "low" : 192, "hi" : 255, "bytes" : "D870A94C4856EF818C5D93B2187F09C732E4491103B8A49B14CDC118F1607E2D8443740F20220DF076B981D90436E9C309282C1CEAAE6375002AD1CA9CCF720C" }
{ "low" : 256, "hi" : 319, "bytes" : "5091AE53E13948DAE57F6B0BE95B8F46A1F53553767B98F9799A0F0AC468AEB340C20E23FA1A8CAE7387CEA127A7A0F3635667BF028DE15179093B706306B99C" }
{ "low" : 448, "hi" : 511, "bytes" : "02323B1FA2C863D3B4A89CFC143013A6EEA8265BBD1B8FE243DEA2F4B19A5726593564E7E7021FD042F58077A5821C2F415BC38D6DD2BE29A5400E4B1D65B2A2" } ]
xor_digest = "9B29085D13B4992B077E3A878A5918B592C98C8A83956EC20EFE673A24C48C915D8DB1A4A66F62F1A3E7D6ADF6DC8845DD7A6D43F9DBF6C1EA21639060469AD6"
f()
desc = "Set 3, vector#225"
key = "E1E2E3E4E5E6E7E8E9EAEBECEDEEEFF0"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "9A5509AB6D2AB05C7DBA61B0CC9DD844B352A293E7D96B5C0066ACDB548DB8570459E989B83AF10A2C48E9C00E02671F436B39C174494787D1ECEB3417C3A533" }
{ "low" : 192, "hi" : 255, "bytes" : "8A913EBA25B4D5B485E67F97E83E10E0B858780D482A6840C88E7981F59DC51F2A86109E9CD526FCFA5DBF30D4AB575351027E5A1C923A00007260CE7948C53D" }
{ "low" : 256, "hi" : 319, "bytes" : "0A901AB3EBC2B0E4CBC154821FB7A0E72682EC9876144C4DC9E05098B6EFCCCB90E2F03837553C579CDD0A647D6A696350000CA57628B1E48E96242226A92ECC" }
{ "low" : 448, "hi" : 511, "bytes" : "9CDB39B79A464F2CCA3637F04EBAEA357A229FC6A9BA5B83171A0A8945B6F11756EBC9F4201D0BA09C39F9776721304632AA6A68ADE5B90268AEE335E13B1D39" } ]
xor_digest = "695757EDF4992CE9E1C088D62CAB18A38F56EE71F1F4866E88D1A02E07CB89B9133F0B02A23BA39622E84E19DACDF32397F29E50151F78524B717093131A10B1"
f()
desc = "Set 3, vector#234"
key = "EAEBECEDEEEFF0F1F2F3F4F5F6F7F8F9"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "37EDAFA4F5EDC64EBF5F74E543493A5393353DE345A70467A9EC9F61EEFE0ED4532914B3EA6C2D889DA9E22D45A7DD321EA5F1F6978A7B2E2A15D705DE700CE4" }
{ "low" : 192, "hi" : 255, "bytes" : "C415739777C22430DAB2037F6287E516B1CE142111456D8919E8CD19C2B2D30D8A1B662C26137F20F87C2802A2F3E66D8CEB9D3C1B4368195856249A379BD880" }
{ "low" : 256, "hi" : 319, "bytes" : "0381733EC9B2073F9E4E9954471184112D99B23FA4A87B4025C6AF955E93E0D57DD37011E1624175F970BDA7D625224BAB0F021E6453DBA894A5074C447D24BC" }
{ "low" : 448, "hi" : 511, "bytes" : "F9D45C7E0E7A26F2E7E2C07F68AF1191CC699964C01654522924A98D6790A946A04CD9586455D5A537CBA4D10B3C2718745C24875156483FE662B11E0634EAEA" } ]
xor_digest = "E0FE8129B73BCADA14FB385E6D3DB22D84C9755D63E93141202576FB5B2D3647D47B2F6378BC8567E4416976443FAE763C2B5FA46F2670C301A5B22802513D2D"
f()
desc = "Set 3, vector#243"
key = "F3F4F5F6F7F8F9FAFBFCFDFEFF000102"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "B935A7B6D798932D879795A182E7C194BECEFF32522C2F3FFF55A5C6D32A91D2BA9F144DB280ABA7BA8A7921AFA3BD82CA742DDBEAF8AF72299936E9C2FEA59E" }
{ "low" : 192, "hi" : 255, "bytes" : "6F32248B6EF4CDAE06864B6477893440F0E0217421D7081D1F0DA197B52636740E9BDD59068BEDE48BF52C43446C12CD4F10ED22BFDDFA915FA0FB1A73F9139C" }
{ "low" : 256, "hi" : 319, "bytes" : "BF01A4ED868EF9080DF80689E589897C021DCA18073F9291E1D158DC26266556728DD130629D3760F541439147F4C1CA279FB98040E9FCE50998E42D6259DE1F" }
{ "low" : 448, "hi" : 511, "bytes" : "0F2B116CD687C91FBA1EDEAD586411E966D9EA1076863EC3FDFC254DD5C93ED6AE1B01982F63A8EB13D839B2510AD02CDE24210D97A7FA9623CAC00F4C5A1107" } ]
xor_digest = "C6970385CA89CDFCACA9E90DA2A2FE9958EF83B9BF04DBE7A3B343750368883105FF6665D9F91D4DBBBCAF31B555ED3DD07C3AC824281730BF834693C596AD54"
f()
desc = "Set 3, vector#252"
key = "FCFDFEFF000102030405060708090A0B"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "09D36BFFDDCD3ADC8EB0ABEEB3794CE1FFBDED9CFC315D21A53C221B27722FE3F10E20D47DDCFD3CCDE9C1BAAF01F5511D3F14F88BF741A7F6578C3BC9024B2B" }
{ "low" : 192, "hi" : 255, "bytes" : "552502A1B2D0F29806DE512F3314FC8E19518E35D9DB1EBC9034EA46E5815AB9DF0F403E997E676BF47C0116D5E9B81726B99D65AA4315F1E5906F6E39B1297E" }
{ "low" : 256, "hi" : 319, "bytes" : "6BF351A501E8D1B4BAF4BFD04726DC4F50200463DCC13FF3BE93E6C4D4304CE09E6A1CEA41BFB93D6DBAD713298F79CFF6F5BB81F456E33A3396D02F2E33BDC5" }
{ "low" : 448, "hi" : 511, "bytes" : "715F8FFB2BC25CD89E46B706EF871207EFE736AA3CB961B06E7B439E8E4F76E2944AF7BD49EEC47B4A2FD716D191E85859C74FD0B4A505ACE9F80EEB39403A1F" } ]
xor_digest = "D51B519D78CDBC8DF5CB1CEA5EBBA6E46530535D84CBF1696EBF238D3F7AA4A1D2F1EF5FF092DB57943E28501C64CFF04619197ED4A3D82EEEB2B2E9648D7494"
f()
desc = "Set 4, vector# 0"
key = "0053A6F94C9FF24598EB3E91E4378ADD"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "BE4EF3D2FAC6C4C3D822CE67436A407CC237981D31A65190B51053D13A19C89FC90ACB45C8684058733EDD259869C58EEF760862BEFBBCA0F6E675FD1FA25C27" }
{ "low" : 65472, "hi" : 65535, "bytes" : "F5666B7BD1F4BC8134E0E45CDB69876D1D0ADAE6E3C17BFBFE4BCE02461169C54B787C6EF602AF92BEBBD66321E0CAF044E1ADA8CCB9F9FACFC4C1031948352E" }
{ "low" : 65536, "hi" : 65599, "bytes" : "292EEB202F1E3A353D9DC6188C5DB43414C9EF3F479DF988125EC39B30C014A809683084FBCDD5271165B1B1BF54DAB440577D864CD186867876F7FDA5C79653" }
{ "low" : 131008, "hi" : 131071, "bytes" : "C012E8E03878A6E7D236FEC001A9F895B4F58B2AF2F3D237A944D93273F5F3B545B1220A6A2C732FC85E7632921F2D366B3290C7B0A73FB61D49BC7616FC02B8" } ]
xor_digest = "196D1A0977F0585B23367497D449E11DE328ECD944BC133F786348C9591B35B7189CDDD934757ED8F18FBC984DA377A807147F1A6A9A8759FD2A062FD76D275E"
f()
desc = "Set 4, vector# 1"
key = "0558ABFE51A4F74A9DF04396E93C8FE2"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "BA1A48247B8C44AAF12F5645D65FF7F4E4D7C404EE0CBB691355FAEB82D03B99AD0FDFC20A1E593973E5B8F0264F7FB0538292A4C8FE8218A1DA3EB7B71EEA64" }
{ "low" : 65472, "hi" : 65535, "bytes" : "03A24E89D69D5E1DA98B0367CF626F33D558B1208AB120B6B1778BFF640F56DA715FE1B681D8CC0F305D6645B439BA81D3C446A428B31BB18E9DA1E2A900B0FD" }
{ "low" : 65536, "hi" : 65599, "bytes" : "6A28ADD4F926759CEBB0AFC5D5DA52431F2E7ECBBD1E9DEAF368137E35F1AFBD65852214FA06310C3175FCF364810F627E3703E9AC5458A8B681EB03CEECD872" }
{ "low" : 131008, "hi" : 131071, "bytes" : "E8D8AB5E245B9A83A77B30F19E3706F037272E42F9C6CD7E8156C923535EF119B633E896E97C404C6D87565EEA08EB7FF6319FF3E631B6CDD18C53EE92CCEEA0" } ]
xor_digest = "2BD4F834BC7B3C128E291B2BCE7DA0A5BA1A17E2785093B7F32B7D605AE63276F8256998EC1E0B5A7FD2D66EE9B0B705E49435EDF8BACE1BE770738A403B8F14"
f()
desc = "Set 4, vector# 2"
key = "0A5DB00356A9FC4FA2F5489BEE4194E7"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "8313F4A86F697AAC985182862E4FC6233511C46B6DAEEDB94B63461111CB476872F1BC3B4E8EE80A4ADE7D1A8CD49C171D3A550D3F39B7775734225579B8B60A" }
{ "low" : 65472, "hi" : 65535, "bytes" : "6AFA6F539C0F3B0B9DEB0235E7EB2E14B111615D4FBC5BF7FFE75E160DEDA3D9932125469AEC00539ECE8FCF8067CB0FB542C2064267BEA7D9AD6365314D5C2C" }
{ "low" : 65536, "hi" : 65599, "bytes" : "296F2B5D22F5C96DA78304F5800E0C87C56BC1BACD7A85D35CFECE17427393E1611975CC040D27DF6A5FABC89ADDE328AE8E9CB4F64CFA0CB38FE525E39BDFE4" }
{ "low" : 131008, "hi" : 131071, "bytes" : "86C8139FD7CED7B5432E16911469C7A56BDD8567E8A8993BA9FA1394348C2283F2DF5F56E207D52A1DA070ABF7B516CF2A03C6CD42D6EA2C217EC02DF8DDCA9C" } ]
xor_digest = "DEEBF1FCF222519E26EC6556EA44908092923B357CB88D1A1C1B03341F5C6A984C70E9DB735377615C0476D46DA9897B48127A0D224241E79FE8CF51B005EF93"
f()
desc = "Set 4, vector# 3"
key = "0F62B5085BAE0154A7FA4DA0F34699EC"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "62765613D127804ECD0F82D208D701563B1685EEF67945DAE2900307CDB14EA62474A439D8BAE8005493455471E7BCB9DB75F0596F3FB47E65B94DC909FDE140" }
{ "low" : 65472, "hi" : 65535, "bytes" : "00A0D5B2CE7B95E142D21B57B187C29C19B101CD063196D9B32A3075FB5D54A20D3CE57CBEC6CA684CB0E5306D5E21E5657F35B8FB419A0251EA5CD94113E23B" }
{ "low" : 65536, "hi" : 65599, "bytes" : "AAC2D29404A015047DEFB4F11460958DA989141026FE9325F15954363FC78898D4A20F6870F4D2B124590973F6956096940E2324F7C63384A85BACF53F7755E3" }
{ "low" : 131008, "hi" : 131071, "bytes" : "0A543607FE352336ACFEDFE6B74359E0B26B19FD45A8938C6C0A6DB68A1377495B65211558D0CB9ECA9DA2C0E50702B688B2DEC53AAA2FBF11BD149F4F445696" } ]
xor_digest = "D124AA942DC1D54D5B9B4BC6804F9990543EAF31FF441F0CD16B961C817EA4A76AF71F678BBB482052B2BA767B4F9265B65C3D839D182D093B560AEB09184C0C"
f()
desc = "Set 5, vector# 0"
key = "00000000000000000000000000000000"
IV = "8000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "B66C1E4446DD9557E578E223B0B768017B23B267BB0234AE4626BF443F219776436FB19FD0E8866FCD0DE9A9538F4A09CA9AC0732E30BCF98E4F13E4B9E201D9" }
{ "low" : 192, "hi" : 255, "bytes" : "462920041C5543954D6230C531042B999A289542FEB3C129C5286E1A4B4CF1187447959785434BEF0D05C6EC8950E469BBA6647571DDD049C72D81AC8B75D027" }
{ "low" : 256, "hi" : 319, "bytes" : "DD84E3F631ADDC4450B9813729BD8E7CC8909A1E023EE539F12646CFEC03239A68F3008F171CDAE514D20BCD584DFD44CBF25C05D028E51870729E4087AA025B" }
{ "low" : 448, "hi" : 511, "bytes" : "5AC8474899B9E28211CC7137BD0DF290D3E926EB32D8F9C92D0FB1DE4DBE452DE3800E554B348E8A3D1B9C59B9C77B090B8E3A0BDAC520E97650195846198E9D" } ]
xor_digest = "104639D9F65C879F7DFF8A82A94C130CD6C727B3BC8127943ACDF0AB7AD6D28BF2ADF50D81F50C53D0FDFE15803854C7D67F6C9B4752275696E370A467A4C1F8"
f()
desc = "Set 5, vector# 9"
key = "00000000000000000000000000000000"
IV = "0040000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "1A643637B9A9D868F66237163E2C7D976CEDC2ED0E18C98916614C6C0D435B448105B355AE1937A3F718733CE15262316FA3243A27C9E93D29745C1B4DE6C17B" }
{ "low" : 192, "hi" : 255, "bytes" : "CDDB6BD210D7E92FBFDD18B22A03D66CC695A93F34FB033DC14605536EEEA06FFC4F1E4BACFCD6EB9DA65E36C46B26A93F60EAA9EC43307E2EA5C7A68558C01A" }
{ "low" : 256, "hi" : 319, "bytes" : "5FC02B90B39F3E90B8AEC15776F2A94FD8C26B140F798C93E1759957F99C613B8B4177A7B877D80A9B9C76C2B84E21A6DF803F0DB651E1D0C88FB3743A79938F" }
{ "low" : 448, "hi" : 511, "bytes" : "B4BC18F7279AC64BB6140A586F45AC96E549C0CA497F59B875C614DE605A8BFF63AB3F1E00DAEAE7A5CC7A7796E9BACCDD469E9100EABCD6E69301EA59C4B76A" } ]
xor_digest = "4EF8F9A7D50D7ABEC1A104565E9E20BF35FACFDD5600B0360E3ECBDE626CC6934A52173415C05BA5EE681D649CB60D186970CF18BC028AF829054903FDEB37BA"
f()
desc = "Set 5, vector# 18"
key = "00000000000000000000000000000000"
IV = "0000200000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "94B7B07E184BC24A0904290B2601FC3AC70BEAD7B1FC3294360ED4EF168134530B4D1F3F28A3C3B248B2E914A8DCBD5326A240C9BB361A8A93D023725BDCD4E3" }
{ "low" : 192, "hi" : 255, "bytes" : "27C7A2C4EAA1E2E8798CA71EA50B7E5ACD9FC82263D11781EFC16142CFD21A634DB2B860B54A9979AFA187CE0667D17623FC91EC1E5E6C31A8089628AC76F9F0" }
{ "low" : 256, "hi" : 319, "bytes" : "C2CD243516E5919D6C5C478469260813ABE8E6F54BE8E11D48FEC043CDADA19BEFE9CB0C22A9BB30B98E4CFCF1A55EF1263B209CE15FEAEF8237CFAF7E5286D6" }
{ "low" : 448, "hi" : 511, "bytes" : "84489BD680FB11E5CAA0F5535ABA86DCFF30AC031CEFED9897F252803597772670E1E164FA06A28DD9BAF625B576166A4C4BF4CADD003D5DF2B0E6D9142DD8B3" } ]
xor_digest = "783AD910F37369EFB54DD9A00D54CDB72EEAF2693C121B13344025E08DF874AC4BBC08B8FA916B423B0F4667A6D1BAEC3016B999FF9FAB317161422E4FF925AB"
f()
desc = "Set 5, vector# 27"
key = "00000000000000000000000000000000"
IV = "0000001000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "2E6C8BE7DD335292EE9152641B0E4EFB43D27434E4BE70EAC4CAFAE5C38B2E5B06E70B9966F4EDD9B4C4589E18E61F05B78E7849B6496F33E2FCA3FC8360824C" }
{ "low" : 192, "hi" : 255, "bytes" : "1006D6A04165A951C7EE31EEB0F6C32BD0B089683C001942886FCEF9E700D15ADB117652735C546D30177DC14FA68708D591C3254C05B84BF0DCBC3105F06A6F" }
{ "low" : 256, "hi" : 319, "bytes" : "2196ADA05BED2BD097A43E4C5BE6C9404A353689939DCB9C4F82278BDB0EB505F70FFD9921B46645EDDFCF47405FD3E67CAE732B367A0B0F2B57A503161FA5DE" }
{ "low" : 448, "hi" : 511, "bytes" : "4A3504DAC25F59489C769090D822E89E1338AC73F22DB2614B43D640525EF9969D6B7E3900ADCBE056AB818E0FF708E3B0A8E63531F252C384DD3DE7318EA866" } ]
xor_digest = "33533F81725EA5444E0642A07A334AE5AC3DD16214F6FE196A60A4343AFA5026E1602E84D3E672EEDB9FB5BB6F44C02366C28BD8E3CF673BB34F438CF82561E2"
f()
desc = "Set 5, vector# 36"
key = "00000000000000000000000000000000"
IV = "0000000008000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "1D3FD8BAF2A13BCD2A49B50F8DFB05228E366B4FD2ECD6973DFF116289D7E0AF55EFB875345204B5FCE27A1C6DF79531B3175647526BF5C028C454BADEFBECD6" }
{ "low" : 192, "hi" : 255, "bytes" : "F639D0D23CC5817501517216ADA14241D08495F17CDEAFB883CE619A3255EC3FEAADFA224CF354C425A74D3DDAAA0C86E44016238C142B36944EF53A1EC7DF92" }
{ "low" : 256, "hi" : 319, "bytes" : "9CAE4D4639696A188E08BC1B017746085D18418F82DC90742BB6D172414ACC13A4721B018B2CC002CB6E6FFE4A4E252CC4BF5DE975684C8805036F4C76660DC8" }
{ "low" : 448, "hi" : 511, "bytes" : "CB2A2CB3136F5CC71FD95A4A242B15E51C8E3BAE52FEC9C1B591B86DFDDC2442353DF500B2B9868A6C609655FC1A3E03347608D12D3923457EEEB34960F4DB31" } ]
xor_digest = "D623CA4753D2197E68B87B1ACBD84CC9A056EC02F83D7E399CE2C4ACCF7934A5A0CAE68FC0EB88098AA39DA88881C7B24C137195F32DA5CA86631CB84A6BC3B2"
f()
desc = "Set 5, vector# 45"
key = "00000000000000000000000000000000"
IV = "0000000000040000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "2DCAD75F5621A673A471FDE8728FACF6D3146C10A0903DE12FBDCE134CC0F11B2D2ABBDBADFA19303E264011A1B9EFECAB4DFBC37E3D0F090D6B069505525D3A" }
{ "low" : 192, "hi" : 255, "bytes" : "02C401ACF6D160CC1D80E11CB4F3038A4C5B61C995CD94E15D7F95A0A18C49D5DA265F6D88D68A39B55DB3505039D13EAB9DEBD408CE7A79C375FD3FEBEF86C8" }
{ "low" : 256, "hi" : 319, "bytes" : "83D92AF769F5BF1FA894613D3DF447EBD461CFFC0CA3A9843E8441EC91DEBC67BE9162EABC5607A6D3FCAD4426EF4F9F3B42CEC8C287C194B2211DEA4549D5D5" }
{ "low" : 448, "hi" : 511, "bytes" : "D3F86930112EAFC7AA430444693BAE773F014D0798CAF3652A3432460F326DA88E82BE1E08C220B5FCBCE238B982E37D1E60DCBF1747D437D42DB21ADF5EECF2" } ]
xor_digest = "0BF26BADEFCB5BB32C43410920FF5E0F2720E8BB1C94DD5D04F0853F298C3ABA8FF670AF163C5D24BCAF13AD0A04196A2B89E82CF88846C77C77A097E234010F"
f()
desc = "Set 5, vector# 54"
key = "00000000000000000000000000000000"
IV = "0000000000000200"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "D8E137C510CDBB1C788677F44F3D3F2E4C19FCEB51E7C2ECBDB175E933F44625C7B0168E446CCCA900B9DB12D53E89E1B917A69BDB888935B3B795D743D0D0E6" }
{ "low" : 192, "hi" : 255, "bytes" : "E168F81B5BFB769F3380690D423E251E0F4BEEBE0B02F19AFFADBD94212B8063D77A665FD53F8F1A1CC682599C74F4153642EC7DADA034403A90E1E5DA40C896" }
{ "low" : 256, "hi" : 319, "bytes" : "574774CFB8452E82777371616E0AC224E29939E725B99EA8CFB4A9BF459A70D6AB1991E85E06905ACCDA8D1911F828359C4FD7614A55C1E30171934412D46B3E" }
{ "low" : 448, "hi" : 511, "bytes" : "21FE9B1F82E865CC305F04FA2C69EA976D90A41590A3BD242337D87D28E3041D3D0F74CA24A74453CB679FDFFEE45AA63B2DDE513D3F9E28E86346D9A4114CD7" } ]
xor_digest = "3E25D50331D9840FBD4F8B0FD10A9D646A5E8E0ADE57CCDECF346B2973631740382139165B0E0E78A53E4B6CAABE6517BF02B7B2905F9A64A60F412CA78E6929"
f()
desc = "Set 5, vector# 63"
key = "00000000000000000000000000000000"
IV = "0000000000000001"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "42DCF10EA1BCBA82C88DDCDF905C9C7842A78AE57117F09CE51517C0C70063CF1F6BC955EF8806300972BD5FC715B0ED38A111610A81EBA855BB5CD1AEA0D74E" }
{ "low" : 192, "hi" : 255, "bytes" : "261E70245994E208CDF3E868A19E26D3B74DBFCB6416DE95E202228F18E56622521759F43A9A71EB5F8F705932B0448B42987CEC39A4DF03E62D2C24501B4BDE" }
{ "low" : 256, "hi" : 319, "bytes" : "9E433A4BF223AA0126807E8041179CC4760516D3537109F72124E3534A24EA7DB225C60063190FD57FF8595D60B2A8B4AE37384BB4FCD5B65234EE4FB0A1EBEA" }
{ "low" : 448, "hi" : 511, "bytes" : "3F9803DD763449758F008D77C8940F8AFB755833ED080A10513D800BA3A83B1C028A53AED0A65177C58B116E574745D0F28506A9DACD6F8A3D81613E00B12FDB" } ]
xor_digest = "C0CA35A30730FCE3A6B08FD9707EBD1C8154F54266696A99430BCA8B9F94FDD1A78CCB43CB67C58EFF3B171A38597F12AA6A424088C062B97613691B7D12CDE6"
f()
desc = "Set 6, vector# 0"
key = "0053A6F94C9FF24598EB3E91E4378ADD"
IV = "0D74DB42A91077DE"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "05E1E7BEB697D999656BF37C1B978806735D0B903A6007BD329927EFBE1B0E2A8137C1AE291493AA83A821755BEE0B06CD14855A67E46703EBF8F3114B584CBA" }
{ "low" : 65472, "hi" : 65535, "bytes" : "1A70A37B1C9CA11CD3BF988D3EE4612D15F1A08D683FCCC6558ECF2089388B8E555E7619BF82EE71348F4F8D0D2AE464339D66BFC3A003BF229C0FC0AB6AE1C6" }
{ "low" : 65536, "hi" : 65599, "bytes" : "4ED220425F7DDB0C843232FB03A7B1C7616A50076FB056D3580DB13D2C295973D289CC335C8BC75DD87F121E85BB998166C2EF415F3F7A297E9E1BEE767F84E2" }
{ "low" : 131008, "hi" : 131071, "bytes" : "E121F8377E5146BFAE5AEC9F422F474FD3E9C685D32744A76D8B307A682FCA1B6BF790B5B51073E114732D3786B985FD4F45162488FEEB04C8F26E27E0F6B5CD" } ]
xor_digest = "620BB4C2ED20F4152F0F86053D3F55958E1FBA48F5D86B25C8F31559F31580726E7ED8525D0B9EA5264BF977507134761EF65FE195274AFBF000938C03BA59A7"
f()
desc = "Set 6, vector# 1"
key = "0558ABFE51A4F74A9DF04396E93C8FE2"
IV = "167DE44BB21980E7"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "EF5236C33EEEC2E337296AB237F99F56A48639744788E128BC05275D4873B9F0FAFDA8FAF24F0A61C2903373F3DE3E459928CD6F2172EA6CDBE7B0FBF45D3DAD" }
{ "low" : 65472, "hi" : 65535, "bytes" : "29412152F2750DC2F951EC969B4E9587DCD2A23DAADCBC20677DDFE89096C883E65721FC8F7BFC2D0D1FD6143D8504CB7340E06FE324CE3445081D3B7B72F3B3" }
{ "low" : 65536, "hi" : 65599, "bytes" : "49BFE800381794D264028A2E32D318E7F6FD9B377ED3A12274CE21D40CCEF04D55791AF99849989C21D00E7D4E7B9FF4D46AABC44AED676B5C69CF32BE386205" }
{ "low" : 131008, "hi" : 131071, "bytes" : "C3E16260DD666D8D8FBF1529D0E8151A931663D75FA0046132E4AD78D8BE7F8D7F41AAEFDE58BA80B962B8B68762CDF3E4B06E05D73D22CC33F1E1592D5116F4" } ]
xor_digest = "10879B33D24115E4774C71711B563B67CCD891E3825EDB58E182EC92648AE51CDDC29A6A776C0AB3182DDDA1E180D55DFAB024A3121BE45ECA59FF1A3715434C"
f()
desc = "Set 6, vector# 2"
key = "0A5DB00356A9FC4FA2F5489BEE4194E7"
IV = "1F86ED54BB2289F0"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "8B354C8F8384D5591EA0FF23E7960472B494D04B2F787FC87B6569CB9021562FF5B1287A4D89FB316B69971E9B861A109CF9204572E3DE7EAB4991F4C7975427" }
{ "low" : 65472, "hi" : 65535, "bytes" : "B8B26382B081B45E135DF7F8C468ACEA56EB33EC38F292E3246F5A90233DDDC1CD977E0996641C3FA4BB42E7438EE04D8C275C57A69EEA872A440FC6EE39DB21" }
{ "low" : 65536, "hi" : 65599, "bytes" : "C0BA18C9F84D6A2E10D2CCCC041D736A943592BB626D2832A9A6CCC1005DDB9EA1694370FF15BD486B77629BB363C3B121811BCCFB18537502712A63061157D8" }
{ "low" : 131008, "hi" : 131071, "bytes" : "870355A6A03D4BC9038EA0CB2F4B8006B42D70914FBFF76A80D2567BE8404B03C1124BCE2FD863CE7438A5680D23C5E1F8ED3C8A6DB656BFF7B060B8A8966E09" } ]
xor_digest = "888FA87DB4EC690A180EF022AF6615F0677DB73B6A9E0CFACEBBB5B2A8816B2AD0338A812E03F4DFB26AF9D66160348CB9EE72B63B2866E8281A2DB793A3A68E"
f()
desc = "Set 6, vector# 3"
key = "0F62B5085BAE0154A7FA4DA0F34699EC"
IV = "288FF65DC42B92F9"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "71DAEE5142D0728B41B6597933EBF467E43279E30978677078941602629CBF68B73D6BD2C95F118D2B3E6EC955DABB6DC61C4143BC9A9B32B99DBE6866166DC0" }
{ "low" : 65472, "hi" : 65535, "bytes" : "906258725DDD0323D8E3098CBDAD6B7F941682A4745E4A42B3DC6EDEE565E6D9C65630610CDB14B5F110425F5A6DBF1870856183FA5B91FC177DFA721C5D6BF0" }
{ "low" : 65536, "hi" : 65599, "bytes" : "09033D9EBB07648F92858913E220FC528A10125919C891CCF8051153229B958BA9236CADF56A0F328707F7E9D5F76CCBCAF5E46A7BB9675655A426ED377D660E" }
{ "low" : 131008, "hi" : 131071, "bytes" : "F9876CA5B5136805445520CDA425508AE0E36DE975DE381F80E77D951D885801CEB354E4F45A2ED5F51DD61CE09942277F493452E0768B2624FACA4D9E0F7BE4" } ]
xor_digest = "0F4039E538DAB20139A4FEDCF07C00C45D81FD259D0C64A29799A6EE2FF2FA8B480A8A3CC7C7027A6CE0A197C44322955E4D4B00C94BF5B751E61B891F3FD906"
f()
console.log "exports.data = #{JSON.stringify out, null, 4};"
| 175564 | # These test vectors can be found here:
#
# http://www.ecrypt.eu.org/stream/svn/viewcvs.cgi/ecrypt/trunk/submissions/salsa20/full/verified.test-vectors?logsort=rev&rev=210&view=markup"
#
# They specify keystreams for various inputs
#
out = []
f = () ->
out.push { desc, key, IV, stream, xor_digest }
desc = "Set 1, vector# 0"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "4DFA5E481DA23EA09A31022050859936DA52FCEE218005164F267CB65F5CFD7F2B4F97E0FF16924A52DF269515110A07F9E460BC65EF95DA58F740B7D1DBB0AA" }
{ "low" : 192, "hi" : 255, "bytes" : "DA9C1581F429E0A00F7D67E23B730676783B262E8EB43A25F55FB90B3E753AEF8C6713EC66C51881111593CCB3E8CB8F8DE124080501EEEB389C4BCB6977CF95" }
{ "low" : 256, "hi" : 319, "bytes" : "7D5789631EB4554400E1E025935DFA7B3E9039D61BDC58A8697D36815BF1985CEFDF7AE112E5BB81E37ECF0616CE7147FC08A93A367E08631F23C03B00A8DA2F" }
{ "low" : 448, "hi" : 511, "bytes" : "B375703739DACED4DD4059FD71C3C47FC2F9939670FAD4A46066ADCC6A5645783308B90FFB72BE04A6B147CBE38CC0C3B9267C296A92A7C69873F9F263BE9703" } ]
xor_digest = "F7A274D268316790A67EC058F45C0F2A067A99FCDE6236C0CEF8E056349FE54C5F13AC74D2539570FD34FEAB06C572053949B59585742181A5A760223AFA22D4"
f()
desc = "Set 1, vector# 9"
key = "<KEY>"
IV = "0<KEY>000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "0471076057830FB99202291177FBFE5D38C888944DF8917CAB82788B91B53D1CFB06D07A304B18BB763F888A61BB6B755CD58BEC9C4CFB7569CB91862E79C459" }
{ "low" : 192, "hi" : 255, "bytes" : "D1D7E97556426E6CFC21312AE38114259E5A6FB10DACBD88E4354B04725569352B6DA5ACAFACD5E266F9575C2ED8E6F2EFE4B4D36114C3A623DD49F4794F865B" }
{ "low" : 256, "hi" : 319, "bytes" : "AF06FAA82C73291231E1BD916A773DE152FD2126C40A10C3A6EB40F22834B8CC68BD5C6DBD7FC1EC8F34165C517C0B639DB0C60506D3606906B8463AA0D0EC2F" }
{ "low" : 448, "hi" : 511, "bytes" : "AB3216F1216379EFD5EC589510B8FD35014D0AA0B613040BAE63ECAB90A9AF79661F8DA2F853A5204B0F8E72E9D9EB4DBA5A4690E73A4D25F61EE7295215140C" } ]
xor_digest = "B76A7991D5EE58FC51B9035E077E1315D81F131FA1F26CF22005C6C4F2412243C401A850AFEFAADC5B052435B51177C70AE68CB9DF9B44681C2D8B7049D89333"
f()
desc = "Set 1, vector# 18"
key = "<KEY>"
IV = "000<KEY>00000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "BACFE4145E6D4182EA4A0F59D4076C7E83FFD17E7540E5B7DE70EEDDF9552006B291B214A43E127EED1DA1540F33716D83C3AD7D711CD03251B78B2568F2C844" }
{ "low" : 192, "hi" : 255, "bytes" : "56824347D03D9084ECCF358A0AE410B94F74AE7FAD9F73D2351E0A44DF1274343ADE372BDA2971189623FD1EAA4B723D76F5B9741A3DDC7E5B3E8ED4928EF421" }
{ "low" : 256, "hi" : 319, "bytes" : "999F4E0F54C62F9211D4B1F1B79B227AFB3116C9CF9ADB9715DE856A8EB3108471AB40DFBF47B71389EF64C20E1FFDCF018790BCE8E9FDC46527FE1545D3A6EA" }
{ "low" : 448, "hi" : 511, "bytes" : "76F1B87E93EB9FEFEC3AED69210FE4AB2ED577DECE01A75FD364CD1CD7DE10275A002DDBC494EE8350E8EEC1D8D6925EFD6FE7EA7F610512F1F0A83C8949AEB1" } ]
xor_digest = "B9D233247408CD459A027430A23E6FCF3E9A3BAF0D0FC59E623F04D9C107D402880620C64A111318ECE60C22737BECA421F7D3D004E7191ECE2C7075289B31BF"
f()
desc = "Set 1, vector# 27"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "24F4E317B675336E68A8E2A3A04CA967AB96512ACBA2F832015E9BE03F08830FCF32E93D14FFBD2C901E982831ED806221D7DC8C32BBC8E056F21BF9BDDC8020" }
{ "low" : 192, "hi" : 255, "bytes" : "E223DE7299E51C94623F8EAD3A6DB0454091EE2B54A498F98690D7D84DB7EFD5A2A8202435CAC1FB34C842AEECF643C63054C424FAC5A632502CD3146278498A" }
{ "low" : 256, "hi" : 319, "bytes" : "5A111014076A6D52E94C364BD7311B64411DE27872FC8641D92C9D811F2B518594935F959D064A9BE806FAD06517819D2321B248E1F37E108E3412CE93FA8970" }
{ "low" : 448, "hi" : 511, "bytes" : "8A9AB11BD5360D8C7F34887982B3F6586C34C1D6CB49100EA5D09A24C6B835D577C1A1C776902D785CB5516D74E8748079878FDFDDF0126B1867E762546E4D72" } ]
xor_digest = "0423874278AE11EF0A29B3E6E1A5BA41E43671636615E3F1F6215750E5A1749ACDFE0CEB74A11AC4862527C5849110C9A7A6F01E419372824BCAB90550340E81"
f()
desc = "Set 1, vector# 36"
key = "<KEY>"
IV = "0<KEY>0000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "9907DB5E2156427AD15B167BEB0AD445452478AFEE3CF71AE1ED8EAF43E001A1C8199AF9CFD88D2B782AA2F39845A26A7AC54E5BE15DB7BDFBF873E16BC05A1D" }
{ "low" : 192, "hi" : 255, "bytes" : "EBA0DCC03E9EB60AE1EE5EFE3647BE456E66733AA5D6353447981184A05F0F0CB0AD1CB630C35DC253DE3FEBD10684CADBA8B4B85E02B757DED0FEB1C31D71A3" }
{ "low" : 256, "hi" : 319, "bytes" : "BD24858A3DB0D9E552345A3C3ECC4C69BBAE4901016A944C0D7ECCAAB9027738975EEA6A4240D94DA183A74D649B789E24A0849E26DC367BDE4539ADCCF0CAD8" }
{ "low" : 448, "hi" : 511, "bytes" : "EE20675194FA404F54BAB7103F6821C137EE2347560DC31D338B01026AB6E57165467215315F06360D85F3C5FE7A359E80CBFE735F75AA065BC18EFB2829457D" } ]
xor_digest = "19B8E721CD10577375FC6D0E6DC39B054E371860CE2AA310906EA7BAB28D737F2357B42E7DC1C48D597EA58B87602CE5C37EEDED2E0F4819938878AE7C50E151"
f()
desc = "Set 1, vector# 45"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "A59CE982636F2C8C912B1E8105E2577D9C86861E61FA3BFF757D74CB9EDE6027D7D6DE775643FAF5F2C04971BDCB56E6BE8144366235AC5E01C1EDF8512AF78B" }
{ "low" : 192, "hi" : 255, "bytes" : "DF8F13F1059E54DEF681CD554439BAB724CDE604BE5B77D85D2829B3EB137F4F2466BEADF4D5D54BA4DC36F1254BEC4FB2B367A59EA6DDAC005354949D573E68" }
{ "low" : 256, "hi" : 319, "bytes" : "B3F542ECBAD4ACA0A95B31D281B930E8021993DF5012E48A333316E712C4E19B58231AAE7C90C91C9CC135B12B490BE42CF9C9A2727621CA81B2C3A081716F76" }
{ "low" : 448, "hi" : 511, "bytes" : "F64A6449F2F13030BE554DB00D24CD50A89F80CCFE97435EBF0C49EB08747BF7B2C89BE612629F231C1B3398D8B4CC3F35DBECD1CF1CFDFDECD481B72A51276A" } ]
xor_digest = "4134A74A52EA89BF22E05A467E37E08215537896BE4D2BBDF29EA52A2303E64BD954A18928543C82B68A21E4B830A775CBA9D1176EBF8DB92938DF6E59117B74"
f()
desc = "Set 1, vector# 54"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "7A8131B777F7FBFD33A06E396FF32D7D8C3CEEE9573F405F98BD6083FE57BAB6FC87D5F34522D2440F649741D9F87849BC8751EF432DEE5DCC6A88B34B6A1EA9" }
{ "low" : 192, "hi" : 255, "bytes" : "6573F813310565DB22219984E09194459E5BB8613237F012EBB8249666582ACA751ED59380199117DDB29A5298F95FF065D271AB66CF6BC6CDE0EA5FC4D304EB" }
{ "low" : 256, "hi" : 319, "bytes" : "0E65CB6944AFBD84F5B5D00F307402B8399BF02852ED2826EA9AA4A55FB56DF2A6B83F7F228947DFAB2E0B10EAAA09D75A34F165ECB4D06CE6AB4796ABA3206A" }
{ "low" : 448, "hi" : 511, "bytes" : "11F69B4D034B1D7213B9560FAE89FF2A53D9D0C9EAFCAA7F27E9D119DEEEA299AC8EC0EA0529846DAF90CF1D9BFBE406043FE03F1713F249084BDD32FD98CD72" } ]
xor_digest = "E9CFBD15B5F4AD02903851F46728F2DD5910273E7360F1571EF1442199143B6C28E5368A2E00E08ADAE73AF3489E0D6F0D8032984ADD139B6BF508A5EEE4434B"
f()
desc = "Set 1, vector# 63"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "FE4DF972E982735FFAEC4D66F929403F7246FB5B2794118493DF068CD310DEB63EEEF12344E221A2D163CC666F5685B502F4883142FA867B0BA46BF17D011984" }
{ "low" : 192, "hi" : 255, "bytes" : "4694F79AB2F3877BD590BA09B413F1BDF394C4D8F2C20F551AA5A07207433204C2BC3A3BA014886A08F4EC5E4D91CDD01D7A039C5B815754198B2DBCE68D25EA" }
{ "low" : 256, "hi" : 319, "bytes" : "D1340204FB4544EFD5DAF28EDCC6FF03B39FBEE708CAEF6ABD3E2E3AB5738B3204EF38CACCC40B9FBD1E6F0206A2B564E2F9EA05E10B6DD061F6AB94374681C0" }
{ "low" : 448, "hi" : 511, "bytes" : "BB802FB53E11AFDC3104044D7044807941FDAEF1042E0D35972D80CE77B4D560083EB4113CDBC4AC56014D7FF94291DC9387CEF74A0E165042BC12373C6E020C" } ]
xor_digest = "FF021AEC5DC82F40BBF44CEA85287BCFD70F16F557F07B1BF970407051F71C415B703A67CAF8E81CB22D9F09E0CBD2475E9859355A48FDA9F48E38E2748BE41B"
f()
desc = "Set 1, vector# 72"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "8F8121BDD7B286465F03D64CA45A4A154BDF44560419A40E0B482CED194C4B324F2E9295C452B73B292BA7F55A692DEEA5129A49167BA7AABBEED26E39B25E7A" }
{ "low" : 192, "hi" : 255, "bytes" : "7E4388EDBBA6EC5882E9CBF01CFA67860F10F0A5109FCA7E865C3814EB007CC89585C2653BDCE30F667CF95A2AA425D35A531F558180EF3E32A9543AE50E8FD6" }
{ "low" : 256, "hi" : 319, "bytes" : "527FF72879B1B809C027DFB7B39D02B304D648CD8D70F4E0465615B334ED9E2D59703745467F1168A8033BA861841DC00E7E1AB5E96469F6DA01B8973D0D414A" }
{ "low" : 448, "hi" : 511, "bytes" : "82653E0949A5D8E32C4D0A81BBF96F6A7249D4D1E0DCDCC72B90565D9AF4D0AC461C1EAC85E254DD5E567A009EEB38979A2FD1E4F32FAD15D177D766932190E1" } ]
xor_digest = "B2F239692CE50EECABD7A846AC33388543CFC1061F33420B6F205809F3965D899C56C02D208DD3E9A1F0D5BBED8F5DACB164FD005DF907002302F40ADB6665CC"
f()
desc = "Set 1, vector# 81"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "52FA8BD042682CD5AA21188EBF3B9E4AEE3BE38AE052C5B37730E52C6CEE33C91B492F95A67F2F6C15425A8623C0C2AE7275FFD0FCF13A0A293A784289BEACB4" }
{ "low" : 192, "hi" : 255, "bytes" : "5F43C508BA6F728D032841618F96B10319B094027E7719C28A8A8637D4B0C4D225D602EA23B40D1541A3F8487F25B14A8CBD8D2001AC28EADFDC0325BA2C140E" }
{ "low" : 256, "hi" : 319, "bytes" : "5C802C813FF09CAF632CA8832479F891FB1016F2F44EFA81B3C872E37468B8183EB32D8BD8917A858AEF47524FCC05D3688C551FC8A42C8D9F0509018706E40E" }
{ "low" : 448, "hi" : 511, "bytes" : "4CDD40DC6E9C0E4F84810ABE712003F64B23C6D0C88E61D1F303C3BBD89B58AA098B44B5CD82EDCFC618D324A41317AC6FED20C9A0C54A9ED1F4DA3BF2EC3C66" } ]
xor_digest = "B72D2FEE4BFBC0F65005EE2797B0608A7A6D9CD1114B67C0ADEC7B4B6D793182880777B0279E3DF27CBA820714629A96034E4C71F5356254A0116CF3E9F7EF5C"
f()
desc = "Set 1, vector# 90"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "6262315C736E88717E9627EECF4F6B55BD10D5960A9961D572EFC7CBDB9A1F011733D3E17E4735BEFA16FE6B148F86614C1E37065A48ACF287FFE65C9DC44A58" }
{ "low" : 192, "hi" : 255, "bytes" : "B43439584FB2FAF3B2937838D8000AC4CD4BC4E582212A7741A0192F71C1F11B58D7F779CA0E6E4B8BD58E00B50C3C53DAF843467064A2DBE2FAD6FF6F40ECD8" }
{ "low" : 256, "hi" : 319, "bytes" : "EE51EE875F6F1B8AF0334F509DF5692B9B43CC63A586C2380AF3AE490DCD6CFF7907BC3724AE3BBEAD79D436E6DADDB22141B3BA46C9BEC0E01B9D4F7657B387" }
{ "low" : 448, "hi" : 511, "bytes" : "E5A4FE4A2FCA9A9ED779A9574283DC21C85216D54486D9B182300D0593B1E2B010814F7066AEB955C057609CE9AF0D63F057E17B19F57FFB7287EB2067C43B8D" } ]
xor_digest = "8866D8F9E6F423A7DF10C77625014AA582C06CD861A88F40FB9CD1EBF09111884344BEEA5A724E6FD8DB98BF4E6B9BEA5318FA62813D1B49A2D529FC00CB5777"
f()
desc = "Set 1, vector# 99"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "82FD629BD82C3BE22910951E2E41F8FE187E2BD198F6113AFF44B9B0689AA520C8CCE4E8D3FBA69EDE748BCF18397214F98D7ACF4424866A8670E98EBAB715A3" }
{ "low" : 192, "hi" : 255, "bytes" : "342D80E30E2FE7A00B02FC62F7090CDDECBDFD283D42A00423113196A87BEFD8B9E8AAF61C93F73CC6CBE9CC5AEC182F3948B7857F96B017F3477A2EEC3AEB3B" }
{ "low" : 256, "hi" : 319, "bytes" : "8233712B6D3CCB572474BE200D67E5403FC62128D74CE5F790202C696BFFB7EE3CAD255324F87291273A7719278FA3131ABA12342692A2C0C58D27BA3725761B" }
{ "low" : 448, "hi" : 511, "bytes" : "782600E7357AC69EA158C725B3E1E94051A0CB63D0D1B4B3DF5F5037E3E1DE45850578E9D513B90B8E5882D4DCA9F42BE32621F4DCC1C77B38F1B0AC1227C196" } ]
xor_digest = "F8AE82F9B77EF090AE0C72A5EAE2140568BEF0B354BCDF4BD39732CD86C63A82AFD27F58C459272B3E8A4B9B558D856F8475CF3A1AD99074822A836CFE520DC5"
f()
desc = "Set 1, vector#108"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "D244F87EB315A7EEF02CA314B440777EC6C44660020B43189693500F3279FA017257BE0AB087B81F85FD55AAC5845189C66E259B5412C4BDFD0EBE805FC70C8A" }
{ "low" : 192, "hi" : 255, "bytes" : "5A2D8D3E431FB40E60856F05C797620642B35DAB0255764D986740699040702F6CDE058458E842CB6E1843EBD336D37423833EC01DFFF9086FEECAB8A165D29F" }
{ "low" : 256, "hi" : 319, "bytes" : "443CEF4570C83517ED55C2F57058BB70294CC8D7342597E2CD850F6C02E355CAEB43C0A41F4BB74FFE9F6B0D25799140D03792D667601AD7954D21BD7C174C43" }
{ "low" : 448, "hi" : 511, "bytes" : "959C8B16A0ADEC58B544BE33CCF03277E48C7916E333F549CDE16E2B4B6DCE2D8D76C50718C0E77BFBEB3A3CB3CA14BF40F65EBFAE1A5001EAB36E531414E87F" } ]
xor_digest = "4DC82B00DC54141CC890348496115C681DB10ABE8454FBD10B49EF951CD20C6F7FE8AAA10906E57CF05<KEY>838<KEY>76C8B7A3F9E6BD6D21C49F1590C913026C71A3E"
f()
desc = "Set 1, vector#117"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "44A74D35E73A7E7C37B009AE712783AC86ACE0C02CB175656AF79023D91C909ED2CB2F5C94BF8593DDC5E054D7EB726E0E867572AF954F88E05A4DAFD00CCF0A" }
{ "low" : 192, "hi" : 255, "bytes" : "FEC113A0255391D48A37CDF607AE122686305DDAD4CF1294598F2336AB6A5A029D927393454C2E014868137688C0417A2D31D0FE9540D7246FE2F84D6052DE40" }
{ "low" : 256, "hi" : 319, "bytes" : "79C2F7431D69E54C0474D8160113F3648156A8963817C34AC9A9AD222543666E7EAF03AF4EE03271C3ECED262E7B4C66B0F618BAF3395423274DD1F73E2675E3" }
{ "low" : 448, "hi" : 511, "bytes" : "75C1295C871B1100F27DAF19E5D5BF8D880B9A54CEFDF1561B4351A32898F3C26A04AB1149C24FBFA2AC963388E64C4365D716BCE8330BC03FA178DBE5C1E6B0" } ]
xor_digest = "65D58F845F973928ADF5803799901856A08952CF215154C52A5FF2DAD71E8B703DE107E5531491666353F323E790EB021B5EF66C13F43401F4F6A27F08CE11D5"
f()
desc = "Set 1, vector#126"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "E23A3638C836B1ACF7E27296E1F5A2413C4CC351EFEF65E3672E7C2FCD1FA1052D2C26778DB774B8FBA29ABED72D058EE35EBA376BA5BC3D84F8E44ABD5DC2CC" }
{ "low" : 192, "hi" : 255, "bytes" : "2A8BEB3C372A6570F54EB429FA7F562D6EF14DF725861EDCE8132620EAA00D8B1DFEF653B64E9C328930904A0EEB0132B277BB3D9888431E1F28CDB0238DE685" }
{ "low" : 256, "hi" : 319, "bytes" : "CCBEB5CA57104B95BF7BA5B12C8B85534CE9548F628CF53EF02C337D788BCE71D2D3D9C355E7D5EB75C56D079CB7D99D6AF0C8A86024B3AF5C2FC8A028413D93" }
{ "low" : 448, "hi" : 511, "bytes" : "D00A5FDCE01A334C37E75634A8037B49BEC06ACBD2243320E2CA41FB5619E6D875AB2007310D4149379C91EF4E199805BE261E5C744F0DF21737E01243B7116F" } ]
xor_digest = "2D72232A4485E0D2EEDC0619396020774C100C5424FF742B2868E3A68E67E1654C4711C54A34DA937359A26B8386AD2039EB2021DCFBB6A11603AF56225DE098"
f()
desc = "Set 2, vector# 0"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "6513ADAECFEB124C1CBE6BDAEF690B4FFB00B0FCACE33CE806792BB41480199834BFB1CFDD095802C6E95E251002989AC22AE588D32AE79320D9BD7732E00338" }
{ "low" : 192, "hi" : 255, "bytes" : "75E9D0493CA05D2820408719AFC75120692040118F76B8328AC279530D84667065E735C52ADD4BCFE07C9D93C00917902B187D46A25924767F91A6B29C961859" }
{ "low" : 256, "hi" : 319, "bytes" : "0E47D68F845B3D31E8B47F3BEA660E2ECA484C82F5E3AE00484D87410A1772D0FA3B88F8024C170B21E50E0989E94A2669C91973B3AE5781D305D8122791DA4C" }
{ "low" : 448, "hi" : 511, "bytes" : "CCBA51D3DB400E7EB780C0CCBD3D2B5BB9AAD82A75A1F746824EE5B9DAF7B7947A4B808DF48CE94830F6C9146860611DA649E735ED5ED6E3E3DFF7C218879D63" } ]
xor_digest = "6D3937FFA13637648E477623277644ADAD3854E6B2B3E4D68155356F68B30490842B2AEA2E32239BE84E613C6CE1B9BD026094962CB1A6757AF5A13DDAF8252C"
f()
desc = "Set 2, vector# 9"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "169060CCB42BEA7BEE4D8012A02F3635EB7BCA12859FA159CD559094B3507DB801735D1A1300102A9C9415546829CBD2021BA217B39B81D89C55B13D0C603359" }
{ "low" : 192, "hi" : 255, "bytes" : "23EF24BB24195B9FD574823CD8A40C29D86BD35C191E2038779FF696C712B6D82E7014DBE1AC5D527AF076C088C4A8D44317958189F6EF54933A7E0816B5B916" }
{ "low" : 256, "hi" : 319, "bytes" : "D8F12ED8AFE9422B85E5CC9B8ADEC9D6CFABE8DBC1082BCCC02F5A7266AA074CA284E583A35837798CC0E69D4CE937653B8CDD65CE414B89138615CCB165AD19" }
{ "low" : 448, "hi" : 511, "bytes" : "F70A0FF4ECD155E0F033604693A51E2363880E2ECF98699E7174AF7C2C6B0FC659AE329599A3949272A37B9B2183A0910922A3F325AE124DCBDD735364055CEB" } ]
xor_digest = "30209DD68D46E5A30034EF6DCE74FE1AB6C772AB22CD3D6C354A9C4607EF3F82900423D29FB65E07FFA3<KEY>AD94E940D6E52E305A10D60936D34BD03B3F342AB1"
f()
desc = "Set 2, vector# 18"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "05835754A1333770BBA8262F8A84D0FD70ABF58CDB83A54172B0C07B6CCA5641060E3097D2B19F82E918CB697D0F347DC7DAE05C14355D09B61B47298FE89AEB" }
{ "low" : 192, "hi" : 255, "bytes" : "5525C22F425949A5E51A4EAFA18F62C6E01A27EF78D79B073AEBEC436EC8183BC683CD3205CF80B795181DAFF3DC98486644C6310F09D865A7A75EE6D5105F92" }
{ "low" : 256, "hi" : 319, "bytes" : "2EE7A4F9C576EADE7EE325334212196CB7A61D6FA693238E6E2C8B53B900FF1A133A6E53F58AC89D6A695594CE03F7758DF9ABE981F23373B3680C7A4AD82680" }
{ "low" : 448, "hi" : 511, "bytes" : "CB7A0595F3A1B755E9070E8D3BACCF9574F881E4B9D91558E19317C4C254988F42184584E5538C63D964F8EF61D86B09D983998979BA3F44BAF527128D3E5393" } ]
xor_digest = "AD29013FD0A222EEBE65126380A26477BD86751B3B0A2B4922602E63E6ECDA523BA789633BEE6CFF64436A8644CCD7E8F81B062187A9595A8D2507ED774FA5CD"
f()
desc = "Set 2, vector# 27"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "72A8D26F2DF3B6713C2A053B3354DBA6C10743C7A8F19261CF0E7957905748DDD6D3333E2CBC6611B68C458D5CDBA2A230AC5AB03D59E71FE9C993E7B8E7E09F" }
{ "low" : 192, "hi" : 255, "bytes" : "7B6132DC5E2990B0049A5F7F357C9D997733948018AE1D4F9DB999F4605FD78CB548D75AC4657D93A20AA451B8F35E0A3CD08880CCED7D4A508BA7FB49737C17" }
{ "low" : 256, "hi" : 319, "bytes" : "EF7A7448D019C76ED0B9C18B5B2867CF9AD84B789FB037E6B107B0A4615737B5C1C113F91462CDA0BCB9ADDC09E8EA6B99E4835FED25F5CC423EEFF56D851838" }
{ "low" : 448, "hi" : 511, "bytes" : "6B75BDD0EC8D581CB7567426F0B92C9BB5057A89C3F604583DB700A46D6B8DE41AF315AE99BB5C1B52C76272D1E262F9FC7022CE70B435C27AE443284F5F84C1" } ]
xor_digest = "484F9FCB516547DD89AF46991B18F1DEC4C6CBC7D52735E00FC3201B4650151C3D4FB9C119442B368B28E3C68ED83F10D9DA2FDED7DEB8F04827FA91CCDBF65B"
f()
desc = "Set 2, vector# 36"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "76240D13C7E59CBD4183D162834A5D3637CD09EE4F5AFE9C28CFA9466A4089F65C80C224A87F956459B173D720274D09C573FCD128498D810460FDA1BB50F934" }
{ "low" : 192, "hi" : 255, "bytes" : "71AF115217F3B7F77A05B56E32AD0889BFA470B6DDC256D852C63B45688D7BC8DC610D347A2600D7769C67B28D1FA25F1AACFB8F9BB68BFE17357335D8FAC993" }
{ "low" : 256, "hi" : 319, "bytes" : "6573CC1ADC0DE744F6694E5FBB59E5BF5939CE5D13793E2F683C7F2C7DD9A460575746688A0F17D419FE3E5F886545597B6705E1390542B4F953D568025F5BB3" }
{ "low" : 448, "hi" : 511, "bytes" : "809179FAD4AD9B5C355A09E99C8BE9314B9DF269F162C1317206EB3580CAE58AB93A408C23739EF9538730FE687C8DAC1CE95290BA4ACBC886153E63A613857B" } ]
xor_digest = "D1781DCE3EFB8B13740F016264051354F323C81A13D42CE75E67180849AC49FFA7EA95720696F86848A1A4B8506A95E3A61371DDE7F21167CC147173BFC4D78F"
f()
desc = "Set 2, vector# 45"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "3117FD618A1E7821EA08CDED410C8A67BDD8F7BE3FCA9649BD3E297FD83A80AD814C8904C9D7A2DC0DCAA641CFFF502D78AFF1832D34C263C1938C1ADF01238F" }
{ "low" : 192, "hi" : 255, "bytes" : "1E8CB540F19EC7AFCB366A25F74C0004B682E06129030617527BECD16E3E3E0027D818F035EDCDF56D8D4752AEF28BDBFA0D3B008235173475F5FA105B91BEED" }
{ "low" : 256, "hi" : 319, "bytes" : "637C3B4566BBEBBE703E4BF1C978CCD277AE3B8768DB97DF01983CDF3529B3EC6B1137CA6F231047C13EA38649D0058EBE5EF7B7BBA140F22338E382F1D6AB3F" }
{ "low" : 448, "hi" : 511, "bytes" : "D407259B6355C343D64A5130DA55C057E4AF722B70AC8A074262233677A457AFEAA34E7FD6F15959A4C781C4C978F7B3BC571BF66674F015A1EA5DB262E25BDC" } ]
xor_digest = "1F64F78101768FF5067B9A918444EF703FF06561E23B31C61BD43BCF86CFAD249942F73DC8F40AE49B14874B08F2A527A53DF496F37D067F1168268D4A134740"
f()
desc = "Set 2, vector# 54"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "7FED83B9283449AD8EBFC935F5F364075C9008ADE8626D350770E2DBD058F053F7E5300B088B1341EC54C2BEE72A520C35C673E79CC4ED0A6D8F4C15FBDD090B" }
{ "low" : 192, "hi" : 255, "bytes" : "D780206A2537106610D1C95BF7E9121BEDE1F0B8DFBE83CBC49C2C653DD187F7D84A2F4607BF99A96B3B84FB792340D4E67202FB74EC24F38955F345F21CF3DB" }
{ "low" : 256, "hi" : 319, "bytes" : "6CA21C5DC289674C13CFD4FCBDEA83560A90F53BB54F16DBF274F5CC56D7857CD3E3B06C81C70C828DC30DADEBD92F38BB8C24136F37797A647584BCEE68DF91" }
{ "low" : 448, "hi" : 511, "bytes" : "471936CE9C84E131C4C5792B769654B89644BFAFB1149130E580FD805A325B628CDE5FAE0F5C7CFFEF0D931F8F517A929E892D3789B74217A81BAEFE441E47ED" } ]
xor_digest = "0073DA29855E96EA5C414B9BD2E1C0F4987D3F1EB1CA73C4AA10180B99A437744857EB36586593B81088AADE5D89BBC68FBD8B0D268080746D6BE38DBC9396CD"
f()
desc = "Set 2, vector# 63"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "C224F33B124D6692263733DFD5BF52717D1FB45EC1CEDCA6BF92BA44C1EADA85F7B031BCC581A890FD275085C7AD1C3D652BCA5F4D7597DECDB2232318EABC32" }
{ "low" : 192, "hi" : 255, "bytes" : "090325F54C0350AD446C19ABDCAEFF52EC57F5A13FB55FEDE4606CEC44EC658BBB13163481D2C84BF9409313F6470A0DA9803936094CC29A8DE7613CBFA77DD5" }
{ "low" : 256, "hi" : 319, "bytes" : "1F66F5B70B9D12BC7092C1846498A2A0730AA8FA8DD97A757BBB878320CE6633E5BCC3A5090F3F75BE6E72DD1E8D95B0DE7DBFDD764E484E1FB854B68A7111C6" }
{ "low" : 448, "hi" : 511, "bytes" : "F8AE560041414BE888C7B5EB3082CC7C4DFBBA5FD103F522FBD95A7166B91DE6C78FB47413576EC83F0EDE6338C9EDDB81757B58C45CBD3A3E29E491DB1F04E2" } ]
xor_digest = "542B2672401C5D1225CC704365753E33D0827A863C4897FFCE1B724CD10B2A0E8A4E4CDAB7357424FC6DC78440037240B8FD5299907A946CE77DAFA5322AB73D"
f()
desc = "Set 2, vector# 72"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "11BF31E22D7458C189092A1DE3A4905BA2FA36858907E3511FB63FDFF2C5C2A15B651B2C2F1A3A43A7186421528069672B6BB0AEC10452F1DAA9FC73FF5A396A" }
{ "low" : 192, "hi" : 255, "bytes" : "D1E1619E4BD327D2A124FC52BC15B1940B05394ECE5926E1E1ADE7D3FC8C6E91E43889F6F9C1FD5C094F6CA25025AE4CCC4FDC1824936373DBEE16D62B81112D" }
{ "low" : 256, "hi" : 319, "bytes" : "F900E9B0665F84C939D5FE4946FA7B41E34F06058522A2DB49E210E3E5385E5897C24F6350C6CCA578285325CC16F5586DC662FFBEA41BAC68996BAAB9F32D1F" }
{ "low" : 448, "hi" : 511, "bytes" : "40587ECAD15841F1BD1D236A61051574A974E15292F777ABDED64D2B761892BEF3DD69E479DE0D02CC73AF76E81E8A77F3CEE74180CB5685ACD4F0039DFFC3B0" } ]
xor_digest = "C3E5CC5C7CEA1B3885EB9CEF2D1FAF18E7DE1CFD7237F2D6D344F3DF7168A88EC88C1314CB6F5A3EAE1BC468B4FAD75E8A42BE8607705C9A7950302461AD9B3F"
f()
desc = "Set 2, vector# 81"
key = "<KEY>"
IV = "<KEY>0000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "EBC464423EADEF13E845C595A9795A585064F478A1C8582F07A4BA68E81329CB26A13C2EA0EFE9094B0A749FDB1CC6F9C2D293F0B395E14EB63075A39A2EDB4C" }
{ "low" : 192, "hi" : 255, "bytes" : "F4BBBBCE9C5869DE6BAF5FD4AE835DBE5B7F1752B2972086F3383E9D180C2FE55618846B10EB68AC0EB0865E0B167C6D3A843B29336BC1100A4AB7E8A3369959" }
{ "low" : 256, "hi" : 319, "bytes" : "3CEB39E3D740771BD49002EA8CD998518A8C70772679ECAF2030583AED43F77F565FECDBEF333265A2E1CC42CB606980AEF3B24C436A12C85CBDC5EBD97A9177" }
{ "low" : 448, "hi" : 511, "bytes" : "EF651A98A98C4C2B61EA8E7A673F5D4FD832D1F9FD19EE4537B6FEC7D11C6B2F3EF5D764EEAD396A7A2E32662647BFC07F02A557BA6EF046C8DE3781D74332B0" } ]
xor_digest = "88A96FF895BF2A827FC26DB2BB75DC698E8E1B7E231997AB2942E981EF1633EA061F6B323B99519828FB41A6F5CCC79C57<KEY>6DDDD34DEAB38<KEY>14A54C4886626E5"
f()
desc = "Set 2, vector# 90"
key = "<KEY>"
IV = "0<KEY>0000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "F40253BAA835152E1582646FD5BD3FED638EB3498C80BFB941644A7750BBA5653130CC97A937A2B27AFBB3E679BC42BE87F83723DC6F0D61DCE9DE8608AC62AA" }
{ "low" : 192, "hi" : 255, "bytes" : "A5A1CD35A230ED57ADB8FE16CD2D2EA6055C32D3E621A0FD6EB6717AA916D47857CD987C16E6112EDE60CCB0F70146422788017A6812202362691FDA257E5856" }
{ "low" : 256, "hi" : 319, "bytes" : "81F0D04A929DB4676F6A3E6C15049779C4EC9A12ACF80168D7E9AA1D6FA9C13EF2956CEE750A89103B48F22C06439C5CE9129996455FAE2D7775A1D8D39B00CE" }
{ "low" : 448, "hi" : 511, "bytes" : "3F6D60A0951F0747B94E4DDE3CA4ED4C96694B7534CD9ED97B96FAAD3CF00D4AEF12919D410CD9777CD5F2F3F2BF160EBBA3561CC24345D9A09978C3253F6DCB" } ]
xor_digest = "554F89BF1AD5602655B800DB9B3CCFFA1B267D57654DCF3FDDA81A59DF68B022555E63DE51E7A83668E7F1AE09EEB5B8748DEF8580B304199C4D117CF9A94E78"
f()
desc = "Set 2, vector# 99"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "ED5FF13649F7D8EDFC783EFDF2F843B368776B19390AF110BEF12EAC8EC58A2E8CDAB6EC9049FBDA23A615C536C3A313799E21668C248EC864D5D5D99DED80B3" }
{ "low" : 192, "hi" : 255, "bytes" : "845ACE9B870CF9D77597201988552DE53FD40D2C8AC51ABE1335F6A2D0035DF8B10CACAD851E000BAC6EA8831B2FBCFEB7C94787E41CC541BAC3D9D26DB4F19D" }
{ "low" : 256, "hi" : 319, "bytes" : "981580764B81A4E12CA1F36634B591365E4BDB6C12DE13F2F337E72E018029C5A0BECDA7B6723DD609D81A314CE396190E82848893E5A44478B08340F90A73F3" }
{ "low" : 448, "hi" : 511, "bytes" : "4CD3B072D5720E6C64C9476552D1CFF4D4EF68DCBD11E8D516F0C248F9250B571990DD3AFC0AE8452896CCCC0BD0EFDF17B616691AB3DF9AF6A42EDCA54BF9CD" } ]
xor_digest = "52D590BB5E396FCC2E00D9C51B3C0BF073E123C7EE69B528B0F0F87B57DC6907F4B57FD5F5B10D602B1F723E9FDD5510AEC60CD0DD50ED4B60FA355859638C2C"
f()
desc = "Set 2, vector#108"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "78ED06021C5C7867D176DA2A96C4BBAA494F451F21875446393E9688205ED63DEA8ADEB1A2381201F576C5A541BC88874078608CA8F2C2A6BDCDC1081DD254CC" }
{ "low" : 192, "hi" : 255, "bytes" : "C1747F85DB1E4FB3E29621015314E3CB261808FA6485E59057B60BE82851CFC948966763AF97CB9869567B763C7454575022249DFE729BD5DEF41E6DBCC68128" }
{ "low" : 256, "hi" : 319, "bytes" : "1EE4C7F63AF666D8EDB2564268ECD127B4D015CB59487FEAF87D0941D42D0F8A24BD353D4EF765FCCF07A3C3ACF71B90E03E8AEA9C3F467FE2DD36CEC00E5271" }
{ "low" : 448, "hi" : 511, "bytes" : "7AFF4F3A284CC39E5EAF07BA6341F065671147CA0F073CEF2B992A7E21690C8271639ED678D6A675EBDAD4833658421315A2BA74754467CCCE128CCC62668D0D" } ]
xor_digest = "FB3FE601D4E58B0766F02FA15C3323913CD745E905AD74EA5DABA77BC25D282DD66D98204E101F06D60BA446A21331AF6DDEB70679DEF46B886EB8<KEY>"
f()
desc = "Set 2, vector#117"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "D935C93A8EBB90DB53A27BF9B41B334523E1DFDE3BFFC09EA97EFB9376D38C7D6DC67AAB21EA3A5C07B6503F986F7E8D9E11B3150BF0D38F36C284ADB31FACF8" }
{ "low" : 192, "hi" : 255, "bytes" : "DA88C48115010D3CD5DC0640DED2E6520399AAFED73E573CBAF552C6FE06B1B3F3ADE3ADC19DA311B675A6D83FD48E3846825BD36EB88001AE1BD69439A0141C" }
{ "low" : 256, "hi" : 319, "bytes" : "14EA210224DAF4FC5D647C78B6BFEF7D724DC56DCDF832B496DEAD31DD948DB1944E17AB2966973FD7CCB1BC9EC0335F35326D5834EE3B08833358C4C28F70DE" }
{ "low" : 448, "hi" : 511, "bytes" : "D5346E161C083E00E247414F44E0E7375B435F426B58D482A37694331D7C5DC97D8953E6A852625282973ECCFD012D664C0AFA5D481A59D7688FDB54C55CD04F" } ]
xor_digest = "BB5EAC1AB84C70857245294309C023C4B1A4199D16877BC847BCBB1B0A8D1B544289D6C8BF27212AAFFD42021669BB2477A4F815FA01B3F7E88299240155265B"
f()
desc = "Set 2, vector#126"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "45A43A587C45607441CE3AE20046797788879C5B77FDB90B76F7D2DF27EE8D9428A5B5AF35E2AAE242E6577BEC92DA0929A6AFB3CB8F8496375C98085460AB95" }
{ "low" : 192, "hi" : 255, "bytes" : "14AE0BA973AE19E6FD674413C276AB9D99AA0048822AFB6F0B68A2741FB5CE2F64F3D862106EF2BDE19B39209F75B92BDBE9015D63FDFD7B9E8A776291F4E831" }
{ "low" : 256, "hi" : 319, "bytes" : "C26FA1812FFC32EFF2954592A0E1E5B126D5A2196624156E3DFD0481205B24D5613B0A75AF3CBC8BBE5911BE93125BD3D3C50C92910DBA05D80666632E5DF9EF" }
{ "low" : 448, "hi" : 511, "bytes" : "AD0DABE5AF74AB4F62B4699E0D667BBF01B4DCF0A45514554CAC4DFDE453EFF1E51BE5B74B37512C40E3608FB0E65A3FD4EAFA27A3BB0D6E1300C594CB0D1254" } ]
xor_digest = "0F1A4B0994EE03B6C381FE4BB8E33C0EE47C395BB59922C5537EEBFD125494220F743B93D867085E027E56623F79505608179A39FF52D4C00A45A5FB8F618C49"
f()
desc = "Set 2, vector#135"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "09E15E82DFA9D821B8F68789978D094048892C624167BA88AD767CAEFDE80E25F57467156B8054C8E88F3478A2897A20344C4B05665E7438AD1836BE86A07B83" }
{ "low" : 192, "hi" : 255, "bytes" : "2D752E53C3FCA8D3CC4E760595D588A6B321F910B8F96459DBD42C663506324660A527C66A53B406709262B0E42F11CB0AD2450A1FB2F48EA85C1B39D4408DB9" }
{ "low" : 256, "hi" : 319, "bytes" : "1EC94A21BD2C0408D3E15104FA25D15D6E3E0D3F8070D84184D35B6302BF62AEA282E3640820CC09E1528B684B7400180598D6960EC92E4EC4C9E533E1BA06F1" }
{ "low" : 448, "hi" : 511, "bytes" : "D0AC302C5CC256351E24CFFD11F0BD8A0BE1277EDDCB3EE4D530E051712A710DF4513FD6438B7A355CCF4FEDA9A60F2AC375508F998C642E6C51724FE9462F7F" } ]
xor_digest = "B7F32B6FADB48BB8DA231BDBDC4697232BAE5F8F8345F9F14A991FF851CC3C641DF4913A5C550FC898F95AC299ED89155A434DC4B1E37D82EA137BB763F68BC7"
f()
desc = "Set 2, vector#144"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "EA869D49E7C75E07B551C24EBE351B4E7FD9CB26413E55A8A977B766650F81EFCA06E30107F76DC97EA9147FFA7CA66AFD4D4DA538CDA1C27E8D948CC406FB89" }
{ "low" : 192, "hi" : 255, "bytes" : "436A8EC10421116CD03BF95A4DAAE6301BB8C724B3D481099C70B26109971CCEACBCE35C8EE98BBB0CD553B5C418112500262C7EA10FAAC8BA9A30A04222D8E2" }
{ "low" : 256, "hi" : 319, "bytes" : "47487A34DE325E79838475B1757D5D293C931F9E57579FCA5E04A40E4A0A38CFD1614F9CEF75F024FFF5D972BD671DC9FB2A80F64E8A2D82C3BAA5DDFD1E6821" }
{ "low" : 448, "hi" : 511, "bytes" : "3FDCAD4E7B069391FAB74C836D58DE2395B27FFAE47D633912AE97E7E3E60264CA0DC540D33122320311C5CFC9E26D632753AC45B6A8E81AC816F5CA3BBDB1D6" } ]
xor_digest = "E30E770C75C94EE022BEA6B95241E5D7163D7C55AAF20FE7150768CEE6E1103742902FA4F928CDCF31335944DCDEBADDE36FE089D2EB93677E9DF75234E1B3C8"
f()
desc = "Set 2, vector#153"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "7B3AA4599561C9059739C7D18D342CF2E73B3B9E1E85D38EDB41AEFADD81BF241580885078CA10D338598D18B3E4B693155D12D362D533494BA48142AB068F68" }
{ "low" : 192, "hi" : 255, "bytes" : "D27864FC30D5FD278A9FB83FADADFD2FE72CE78A2563C031791D55FF31CF59464BE7422C81968A70E040164603DC0B0AEEE93AC497CC0B770779CE6058BE80CF" }
{ "low" : 256, "hi" : 319, "bytes" : "4C5A87029660B65782FD616F48CFD6006DFB158682DC80E085E52163BE2947E270A0FD74DC8DC2F5920E59F28E225280FAC96BA78B8007E3D0DF6EF7BF835993" }
{ "low" : 448, "hi" : 511, "bytes" : "F5A2ECD04452358970E4F8914FC08E82926ECFF33D9FC0977F10241E7A50E528996A7FB71F79FC30BF881AF6BA19016DDC077ED22C58DC57E2BDBDA1020B30B2" } ]
xor_digest = "8C9995B52F4AC9CA25E5C956850FFE90D396530617298D89659C2F863995FB060B65ADFED6AA977EDBB4FC2F6774335E9DEBC61E05E92718A340F79368E74273"
f()
desc = "Set 2, vector#162"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "9776A232A31A22E2F10D203A2A1B60B9D28D64D6D0BF32C8CCA1BBF6B57B1482BCC9FCF7BBE0F8B61C4BF64C540474BCF1F9C1C808CCBE6693668632A4E8653B" }
{ "low" : 192, "hi" : 255, "bytes" : "5C746D64A3195079079028D74CE029A87F72B30B34B6C7459998847C42F2E44D843CF196229EED471B6BBDBA63BE3B529B8AF4B5846EB0AB008261E161707B76" }
{ "low" : 256, "hi" : 319, "bytes" : "F780FE5204AC188A680F41068A9F50182D9154D6D5F1886034C270A8C3AF61DF945381B7ADCA546E153DBF0E6EA2DDDA4EDA3E7F7CF4E2043C5E20AF659282B4" }
{ "low" : 448, "hi" : 511, "bytes" : "71D24CD8B4A70554906A32A5EFDFA8B834C324E6F35240257A0A27485103616DD41C8F4108D1FC76AB72AF166100AB17212492A72099ACF6F9EB53AC50BD8B8B" } ]
xor_digest = "B2217FF55077D373B735C1A7D8B784F5187AF2F028FE906F85B938277CAC918CE87BEA508AFF86B9071F2B7E4F88A3B1F3323151C9DF441FE6F266CF8F01A0B9"
f()
desc = "Set 2, vector#171"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "62DF49A919AF1367D2AAF1EB608DE1FDF8B93C2026389CEBE93FA389C6F2845848EBBE70B3A3C8E79061D78E9ED24ED9AA7BB6C1D726AA060AEFC4FFE70F0169" }
{ "low" : 192, "hi" : 255, "bytes" : "E7A4DF0D61453F612FB558D1FAE198AAB1979F91E1792C99423E0C573345936570915B60210F1F9CA8845120E6372659B02A179A4D679E8EDDDDF8843ABAB7A4" }
{ "low" : 256, "hi" : 319, "bytes" : "C9501A02DD6AFB536BD2045917B016B83C5150A7232E945A53B4A61F90C5D0FB6E6AC45182CBF428772049B32C825D1C33290DBEEC9EF3FE69F5EF4FAC95E9B1" }
{ "low" : 448, "hi" : 511, "bytes" : "B8D487CDD057282A0DDF21CE3F421E2AC9696CD36416FA900D12A20199FE001886C904AB629194AECCC28E59A54A135747B7537D4E017B66538E5B1E83F88367" } ]
xor_digest = "4EB0E761F6BD6A738DC295C0B1B737FCFDB2A68FF50EB198D699CC71141EC6EB54434D40B592A65F2F5C50B6027D4F529307969E1D74028FF4BD6A44CEAA121C"
f()
desc = "Set 2, vector#180"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "6F703F3FF0A49665AC70CD9675902EE78C60FF8BEB931011FC89B0F28D6E176A9AD4D494693187CB5DB08FF727477AE64B2EF7383E76F19731B9E23186212720" }
{ "low" : 192, "hi" : 255, "bytes" : "AD26886ABF6AD6E0CA4E305E468DA1B369F0ADD3E14364C8A95BD78C5F2762B72915264A022AD11B3C6D312B5F6526E0183D581B57973AFB824945BFB78CEB8F" }
{ "low" : 256, "hi" : 319, "bytes" : "FE29F08A5C157B87C600CE4458F274C986451983FE5AE561DF56139FF33755D71100286068A32559B169D8C2161E215DBC32FAEA11B652284795C144CF3E693E" }
{ "low" : 448, "hi" : 511, "bytes" : "7974578366C3E999028FA8318D82AAAA8ED3FD4DFB111CBF0F529C251BA91DC6ACFA9795C90C954CEA287D23AD979028E974393B4C3ABA251BCB6CECCD09210E" } ]
xor_digest = "88BE85838404EA4F0FFDD192C43E3B93329C4A4919234D116E4393EA26110022BED2B427EC719178E6F1A9B9B08BEF5BF2FE4A9CC869CB6BD2D989F750EDA78F"
f()
desc = "Set 2, vector#189"
key = "<KEY>DBDBDBD"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "61900F2EF2BEA2F59971C82CDFB52F279D81B444833FF02DD0178A53A8BFB9E1FF3B8D7EC799A7FBB60EADE8B1630C121059AA3E756702FEF9EEE7F233AFC79F" }
{ "low" : 192, "hi" : 255, "bytes" : "D27E0784038D1B13833ACD396413FF10D35F3C5C04A710FC58313EEBC1113B2CFA20CBD1AEA4433C6650F16E7C3B68302E5F6B58D8E4F26D91F19FE981DEF939" }
{ "low" : 256, "hi" : 319, "bytes" : "B658FB693E80CE50E3F64B910B660BEB142B4C4B61466424A9884D22EB80B8B40C26BEA869118ED068DCC83F9E4C68F17A3597D0FE0E36700D01B4252EE0010E" }
{ "low" : 448, "hi" : 511, "bytes" : "9FC658A20D3107A34680CC75EB3F76D6A2150490E9F6A3428C9AD57F2A252385C956B01C31C978E219BE351A534DB23B99908DACC6726196742D0B7E1D88472C" } ]
xor_digest = "DA74A6EC8D54723B1797751F786CB1B517995EBF297A034AF744EEF86833CC5BA3DCBDB4D3FAB47F5BA37463CEC80F45DAE1A48FBB80148A39CA789BAE09D39F"
f()
desc = "Set 2, vector#198"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "42D1C40F11588014006445E81C8219C4370E55E06731E09514956834B2047EE28A9DAECC7EB25F34A311CC8EA28EDCD24A539160A0D8FDAA1A26E9F0CDFE0BE3" }
{ "low" : 192, "hi" : 255, "bytes" : "976201744266DEABBA3BFE206295F40E8D9D169475C11659ADA3F6F25F11CEF8CD6<KEY>851B1F72CD3E7D6F0ABAF8FB929DDB7CF0C7B128B4E4C2C977297B2C5FC9" }
{ "low" : 256, "hi" : 319, "bytes" : "D3601C4CD44BBEEFD5DAD1BDFF12C190A5F0B0CE95C019972863F4309CE566DE62BECB0C5F43360A9A09EB5BAB87CF13E7AB42D71D5E1229AF88667D95E8C96F" }
{ "low" : 448, "hi" : 511, "bytes" : "69EAA4BAAAA795BCF3B96E79C931A1F2D2DD16A242714358B106F38C1234A5BBD269E68A03539EFAFA79455ADBE1B984E9766B0720947E1365FDF076F73639CD" } ]
xor_digest = "54E422EB1EB2DBDB338798E0D352A87AD5F5A28BC5F77E1B42913E6500723A936D4019D703DC93A1DF7C65AB74F1FC1A4D38C519A8338B73A435FC7491DFC769"
f()
desc = "Set 2, vector#207"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "9C09F353BF5ED33EDEF88D73985A14DBC1390F08236461F08FDCAF9A7699FD7C4C602BE458B3437CEB1464F451ED021A0E1C906BA59C73A8BA745979AF213E35" }
{ "low" : 192, "hi" : 255, "bytes" : "437E3C1DE32B0DB2F0A57E41A7282670AC223D9FD958D111A8B45A70A1F863E2989A97386758D44060F6BFFF5434C90888B4BB4EDAE6528AAADC7B81B8C7BEA3" }
{ "low" : 256, "hi" : 319, "bytes" : "94007100350C946B6D12B7C6A2FD1215682C867257C12C74E343B79E3DE79A782D74663347D8E633D8BE9D288A2A64A855C71B4496587ADECCB4F30706BB4BD9" }
{ "low" : 448, "hi" : 511, "bytes" : "585D0C2DB901F4004846ADBAA754BCA82B66A94C9AF06C914E3751243B87581AFAE281312A492DBEE8D6BB64DD748F445EF88F82AB44CBA33D767678914BDE77" } ]
xor_digest = "BB97F09B9FCEC06B6124310BBDD1E9CE8D3793F62FF1337F520DE2A90FE2592AF2636DFA20466FDAA9329443ACC0E9A50492621AF5790CAE5642E6F7D9AF400D"
f()
desc = "Set 2, vector#216"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "4965F30797EE95156A0C141D2ACA523204DD7C0F89C6B3F5A2AC1C59B8CF0DA401B3906A6A3C94DA1F1E0046BD895052CB9E95F667407B4EE9E579D7A2C91861" }
{ "low" : 192, "hi" : 255, "bytes" : "8EDF23D6C8B062593C6F32360BF271B7ACEC1A4F7B66BF964DFB6C0BD93217<KEY>C5FACC720B286E93D3E9<KEY>31FA8C4C762DF1F8A3836A8FD8ACBA384B8093E0817" }
{ "low" : 256, "hi" : 319, "bytes" : "44FA82E9E469170BA6E5E8833117DAE9E65401105C5F9FEA0AF682E53A627B4A4A621B63F7CE5265D3DFADFBFD4A2B6C2B40D2249EB0385D959F9FE73B37D67D" }
{ "low" : 448, "hi" : 511, "bytes" : "828BA57593BC4C2ACB0E8E4B8266C1CC095CE9A761FB68FC57D7A2FCFF768EFB39629D3378549FEE08CCF48A4A4DC2DD17E72A1454B7FA82E2ACF90B4B8370A7" } ]
xor_digest = "8A365EE7E7BC9198EC88A39F5047431D1632CBB0D1E812957595E7A0763DFA46953070863838812A9504F7A376078FEA9444B27E15FC043AE2D375D37DB1C6C3"
f()
desc = "Set 2, vector#225"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "5C7BA38DF4789D45C75FCC71EC9E5751B3A60AD62367952C6A87C0657D6DB3E71053AC73E75FF4B66177B3325B1BBE69AEE30AD5867D68B660603FE4F0BF8AA6" }
{ "low" : 192, "hi" : 255, "bytes" : "B9C7460E3B6C313BA17F7AE115FC6A8A499943C70BE40B8EF9842C8A934061E1E9CB9B4ED3503165C528CA6E0CF2622BB1F16D24657BDAEDB9BA8F9E193B65EB" }
{ "low" : 256, "hi" : 319, "bytes" : "406CD92883E991057DFD80BC8201067F35700264A4DFC28CF23EE32573DCB42091FEF27548613999E5C5463E840FE95760CF80CC5A05A74DE49E7724273C9EA6" }
{ "low" : 448, "hi" : 511, "bytes" : "F13D615B49786D74B6591BA6887A7669136F34B69D31412D4A9CB90234DAFCC41551743113701EF6191A577C7DB72E2CB723C738317848F7CC917E1510F02791" } ]
xor_digest = "B31C13C287692760C2710CC4812A4CD3535248839E0B5220185BE58BBCE6A70D629E0749D40D9E79F698FFAFF7B9C53006419AAAD9AC1FAC2286F66DEC96AEB3"
f()
desc = "Set 2, vector#234"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "5B06F5B01529B8C57B73A410A61DD757FE5810970AA0CBFAD3404F17E7C7B6459DD7F615913A0EF2DCC91AFC57FA660D6C7352B537C65CD090F1DE51C1036AB5" }
{ "low" : 192, "hi" : 255, "bytes" : "0F613F9E9F03199DF0D0A5C5BE253CDF138903876DE7F7B0F40B2F840F322F270C0618D05ABB1F013D8744B231555A8ECB14A9E9C9AF39EDA91D36700F1C25B3" }
{ "low" : 256, "hi" : 319, "bytes" : "4D9FAB87C56867A687A03BF3EDCC224AC54D04450AB6F78A642715AF62CF519215<KEY>5338<KEY>8<KEY>599<KEY>9FA679962F038976CDA2DEFA" }
{ "low" : 448, "hi" : 511, "bytes" : "E0F80A9BF168EB523FD9D48F19CA96A18F89C1CF11A3ED6EC8AEAB99082DE99BE46DE2FB23BE4A305F185CF3A8EA377CCA1EF46FD3192D03DCAE13B79960FEF4" } ]
xor_digest = "AB020EA09B2573D7106EAA1D177F2E4A1F8E2237AD1481F9923DDF973A79CFC21A0B8CDDD22D3D78C488D0CC9BE8FAA8C74F0F2CFE619B7D7EA5B2E697E23372"
f()
desc = "Set 2, vector#243"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "E7BC9C13F83F51E8855E83B81AF1FFB9676300ABAB85986B0B44441DDEFAB83B8569C4732D8D991696BD7B6694C6CB20872A2D4542192BE81AA7FF8C1634FC61" }
{ "low" : 192, "hi" : 255, "bytes" : "0B429A2957CBD422E94012B49C443CBC2E13EFDE3B867C6018BABFDE9ED3B8036A913C770D77C60DCD91F23E03B3A57666847B1CACFCBCFF57D9F2A2BAD6131D" }
{ "low" : 256, "hi" : 319, "bytes" : "EA2CBD32269BB804DD2D641452DC09F964CB2BCD714180E94609C1209A8C26D1256067F1B86AA4F886BB3602CF96B4DD7039F0326CD24D7C2D69DE22D9E24624" }
{ "low" : 448, "hi" : 511, "bytes" : "CA0DD398EA7E543F1F680BF83E2B773BBB5B0A931DEADDEC0884F7B823FC686E71D7E4C033C65B03B292426CE4E1A7A8A9D037303E6D1F0F45FDFB0FFE322F93" } ]
xor_digest = "0D67BC1CFE545A6AE2F51A7FB2F32FC62E08707F9CBF2E08245E4594E9DB2A7ECBB6AB7190831C3D7D8F9D606231668E447C4EA29D69B4344952A97A77CC71CB"
f()
desc = "Set 2, vector#252"
key = "<KEY>"
IV = "00000000000<KEY>0"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "C93DA97CB6851BCB95ABFAF547C20DF8A54836178971F748CF6D49AEF3C9CE8CE7D284571D871EFD51B6A897AF698CD8F2B050B6EB21A1A58A9FC77200B1A032" }
{ "low" : 192, "hi" : 255, "bytes" : "5B4144FD0C46CEE4348B598EEF76D16B1A71CBF85F4D9926402133846136C59FBE577B8B7EB8D6A67A48358573C068766AC76A308A14154E2FA9BD9DCA8842E6" }
{ "low" : 256, "hi" : 319, "bytes" : "3BF67A79DF6FE3C32DA7A53CD0D3723716A99BF7D168A25C93C29DF2945D9BCBF78B669195411BD86D3F890A462734AB10F488E9952334D7242E51AC6D886D60" }
{ "low" : 448, "hi" : 511, "bytes" : "65629AA9654930681578EEC971A48D8390FBF82469A385B8BCF28B2C1E9F13CEFC06F54335B4D5DE011F3DCE2B94D38F1A04871E273FCD2A8FA32C0E08710E69" } ]
xor_digest = "E308FAEC064EC30CA1BEA7C2A02E95F4ABCBF7D7762557BE9872726F9020162F9B4EA11F621426EED6297C947BB3FAC269A8D0F38672EFBD72FDCCBEB8475221"
f()
desc = "Set 3, vector# 0"
key = "<KEY>"
IV = "0<KEY>00<KEY>00000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "2DD5C3F7BA2B20F76802410C688688895AD8C1BD4EA6C9B140FB9B90E21049BF583F527970EBC1A4C4C5AF117A5940D92B98895B1902F02BF6E9BEF8D6B4CCBE" }
{ "low" : 192, "hi" : 255, "bytes" : "AB56CC2C5BFFEF174BBE28C48A17039ECB795F4C2541E2F4AE5C69CA7FC2DED4D39B2C7B936ACD5C2ECD4719FD6A3188323A14490281CBE8DAC48E4664FF3D3B" }
{ "low" : 256, "hi" : 319, "bytes" : "9A18E827C33633E932FC431D697F0775B4C5B0AD26D1ACD5A643E3A01A06582142A43F48E5D3D9A91858887310D39969D65E7DB788AFE27D03CD985641967357" }
{ "low" : 448, "hi" : 511, "bytes" : "752357191E8041ABB8B5761FAF9CB9D73072E10B4A3ED8C6ADA2B05CBBAC298F2ED6448360F63A51E073DE02338DBAF2A8384157329BC31A1036BBB4CBFEE660" } ]
xor_digest = "F3BCF4D6381742839C5627050D4B227FEB1ECCC527BF605C4CB9D6FB0618F419B51846707550BBEEE381E44A50A406D020C8433D08B19C98EFC867ED9897EDBB"
f()
desc = "Set 3, vector# 9"
key = "<KEY>"
IV = "0<KEY>000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "0F8DB5661F92FB1E7C760741430E15BB36CD93850A901F88C40AB5D03C3C5FCE71E8F16E239795862BEC37F63490335BB13CD83F86225C8257AB682341C2D357" }
{ "low" : 192, "hi" : 255, "bytes" : "002734084DF7F9D6613508E587A4DD421D317B45A6918B48E007F53BEB3685A9235E5F2A7FACC41461B1C22DC55BF82B54468C8523508167AAF83ABBFC39C67B" }
{ "low" : 256, "hi" : 319, "bytes" : "3C9F43ED10724681186AC02ACFEC1A3A090E6C9AC1D1BC92A5DBF407664EBCF4563676257518554C90656AC1D4F167B8B0D3839EB8C9E9B127665DCE0B1FD78C" }
{ "low" : 448, "hi" : 511, "bytes" : "46B7C56E7ED713AAB757B24056AF58C6AD3C86270CFEAE4AADB35F0DB2D969321A38388D00ED9C2AD3A3F6D8BE0DE7F7ADA068F67525A0996DE5E4DF490DF700" } ]
xor_digest = "FDAEDE318DDD9EE44670318D51E812A2F9B6EAEB18B9EBDC0FB76D95CD0AE8C95792F6EA71332404798505D947B89B041D56FAD3B0D92BEC06428EC5A841EB82"
f()
desc = "Set 3, vector# 18"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "4B135E9A5C9D54E6E019B5A2B48B9E6E17F6E6667B9D43BC3F892AD6ED64C5844FE52F75BD67F5C01523EE026A3851083FBA5AC0B6080CE3E6A2F5A65808B0AC" }
{ "low" : 192, "hi" : 255, "bytes" : "E45A7A605BCFBBE77E781BBE78C270C5AC7DAD21F015E90517672F1553724DDA12692D23EC7E0B420A93D249C438356622D45809034A1A92B3DE34AEB4421168" }
{ "low" : 256, "hi" : 319, "bytes" : "14DEA7F82A4D3C1796C3911ABC2EFE9DC9EB79C42F72691F8CB8C353ECBCC0DC6159EC13DFC08442F99F0F68355D704E5649D8B34836B5D2C46F8999CD570B17" }
{ "low" : 448, "hi" : 511, "bytes" : "CA6A357766527EA439B56C970E2E089C30C94E62CB07D7FE1B1403540C2DA9A6362732811EF811C9D04ED4880DC0038D5FDCE22BDE2668CD75107D7926EC98B5" } ]
xor_digest = "DE518E6B67BAEC2A516CCAB0475341C4BCC652ABE49ECCAA64E87248441A8F727BE173CACEBF8895B07DE8DDD28F1EE8AA739855F1E6DB70765AB1B55BC3B1ED"
f()
desc = "Set 3, vector# 27"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "E04A423EF2E928DCA81E10541980CDE5C8054CC3CF437025B629C13677D4116721123EE13F889A991C03A2E5ADC0B12B9BBC63CB60A23543445919AF49EBC829" }
{ "low" : 192, "hi" : 255, "bytes" : "F6E1D7DBD22E05430EBFBEA15E751C8376B4743681DE6AC3E257A3C3C1F9EC6A63D0A04BF3A07F64E6B167A49CD3FDAAB89A05E438B1847E0DC6E9108A8D4C71" }
{ "low" : 256, "hi" : 319, "bytes" : "FC2B2A1A96CF2C73A8901D334462ED56D57ABD985E4F2210D7366456D2D1CDF3F99DFDB271348D00C7E3F51E6738218D9CD0DDEFF12341F295E762C50A50D228" }
{ "low" : 448, "hi" : 511, "bytes" : "1F324485CC29D2EAEC7B31AE7664E8D2C97517A378A9B8184F50801524867D376652416A0CA96EE64DDF26138DB5C58A3B22EF9037E74A9685162EE3DB174A0E" } ]
xor_digest = "697048C59621DBC7D47B6BE93A5060C4B2DFBDB1E7E444F1FC292C06C12974D126EA9C8FD09C63945E4D9107CD0A1AC57161CA8C7CFEF55CB60E52666C705EC6"
f()
desc = "Set 3, vector# 36"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "361A977EEB47543EC9400647C0C169784C852F268B34C5B163BCA81CFC5E746F10CDB464A4B1365F3F44364331568DB2C4707BF81AA0E0B3AB585B9CE6621E64" }
{ "low" : 192, "hi" : 255, "bytes" : "E0F8B9826B20AEEC540EABA9D12AB8EB636C979B38DE75B87102C9B441876C39C2A5FD54E3B7AB28BE342E377A3288956C1A2645B6B76E8B1E21F871699F627E" }
{ "low" : 256, "hi" : 319, "bytes" : "850464EEED2251D2B5E2FE6AE2C11663E63A02E30F59186172D625CFF2A646FACB85DC275C7CA2AF1B61B95F22A5554FBAD63C0DCC4B5B333A29D270B6366AEF" }
{ "low" : 448, "hi" : 511, "bytes" : "4387292615C564C860AE78460BBEC30DECDFBCD60AD2430280E3927353CEBC21DF53F7FD16858EF7542946442A26A1C3DA4CEFF5C4B781AD6210388B7905D2C7" } ]
xor_digest = "2FADEF81A5C4051CAC55E16C68CC6EEFCEE2D4966BAE782E3D885CAA2271EFBBE33F9313FD00632DC73441823713A48794C21E812E30A1DD4B2AE858A27E7C88"
f()
desc = "Set 3, vector# 45"
key = "<KEY>"
IV = "0<KEY>0000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "9F25D8BD7FBC7102A61CB590CC69D1C72B31425F11A685B80EAC771178030AF052802311ED605FF07E81AD7AAC79B6A81B24113DB5B4F927E6481E3F2D750AB2" }
{ "low" : 192, "hi" : 255, "bytes" : "DAEF37444CB2B068124E074BAD1881953D61D5BA3BFBF37B21BC47935D74820E9187086CEF67EB86C88DDD62C48B9089A9381750DC55EA4736232AE3EDB9BFFE" }
{ "low" : 256, "hi" : 319, "bytes" : "B6C621F00A573B60571990A95A4FEC4AC2CA889C70D662BB4FF54C8FAAE0B7C45B8EC5414AE0F080B68E2943ABF76EA2ABB83F9F93EF94CB3CFE9A4CEED337CD" }
{ "low" : 448, "hi" : 511, "bytes" : "6F17EAE9346878BB98C97F6C81DD2E415FDEB54305FE2DF74AFC65627C376359FB2E7841FF75744A715DF952851C1CBCDD241BADF37B3618E0097B3A084E1B54" } ]
xor_digest = "8D1890B66A56552BE334B3472344F53DD2782D4ABB4514D0F5B761436C99740202A4B1244A1A7F485EFDB52C0065263FEE5A7D7DFC2BB754304CE9B2724119EB"
f()
desc = "Set 3, vector# 54"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "3466360F26B76484D0C4FD63965E55618BDBFDB2213D8CA5A72F2FE6E0A13548D06E87C8A6EEA392FE52D3F5E0F6559D331828E96A07D99C6C0A42EFC24BA96D" }
{ "low" : 192, "hi" : 255, "bytes" : "AB7184066D8E0AB537BB24D777088BC441E00481834B5DD5F6297D6F221532BC56F638A8C84D42F322767D3D1E11A3C65085A8CA239A4FDD1CDF2AC72C1E354F" }
{ "low" : 256, "hi" : 319, "bytes" : "55F29F112B07544EDA3EBB5892DBB91E46F8CBC905D0681D8E7109DF816ABFB8AE6A0F9833CDF34A29F25D67A60D36338A10346FEBE72CCF238D8670C9F2B59C" }
{ "low" : 448, "hi" : 511, "bytes" : "0657453B7806D9EA777FFFBE05028C76DCFF718BC9B6402A3CAEC3BCCB7231E6D3DDB00D5A9637E1E714F47221FFCC11B1425D9653F7D777292B146556A89787" } ]
xor_digest = "C2A8D317E3B1CB884A2C3B07F11FD38833282A9FBD1F6AF5C33CBE1E18D99B6499A241EA83A56605BC6B99259FBAAED4BDDA788B08CAAA93D2E00C6B5392ECF0"
f()
desc = "Set 3, vector# 63"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "40AD59C99464D95702727406E4C82C857FA48911319A3FCC231DC91C990E19D4D9D5972B6A6F21BD12C118365ECAABC89F9C3B63FFF77D8EA3C55B2322B57D0E" }
{ "low" : 192, "hi" : 255, "bytes" : "DBF23042C787DDF6FFCE32A792E39DF9E0332B0A2A2F2A5F96A14F51FAAB7C2714E07C3ADCA32D0DE5F8968870C7F0E81FE263352C1283965F8C210FC25DE713" }
{ "low" : 256, "hi" : 319, "bytes" : "455E3D1F5F44697DA562CC6BF77B93099C4AFAB9F7F300B44AD9783A9622BD543EFDB027D8E71236B52BEE57DD2FB3EE1F5B9022AB96A59AE7DF50E6933B3209" }
{ "low" : 448, "hi" : 511, "bytes" : "F11D47D8C57BBF862E0D6238BC0BF6A52500A62BB037B3A33E87525259B8E54735F664FCEDF11BA2C0F3AEB9C944BCE77FFD26D604674DF8905A73CB7E230A4F" } ]
xor_digest = "F021DE2B24C80A48DE6F7F807F1EF2F813D72A77E7BFC12515F9F5755CEFF64CB5829CA780627A7920F3963E28005677B85A56017A6F5A403DA49F8F8B71581D"
f()
desc = "Set 3, vector# 72"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "D8B1A4CB2A5A8DE1F798254A41F61DD4FB1226A1B4C62FD70E87B6ED7D57902A69642E7E21A71C6DC6D5430DCE89F16FCCC9AAD48743974473753A6FF7663FD9" }
{ "low" : 192, "hi" : 255, "bytes" : "D4BA9BC857F74A28CACC734844849C3EDCB9FB952023C97E80F5BFA445178CAB92B4D9AA8A6D4E79B81993B831C7376510E74E30E7E68AD3188F8817DA8243F2" }
{ "low" : 256, "hi" : 319, "bytes" : "B7039E6F6C4D5D7F750ED014E650118817994F0D3C31B071CC16932A412E627D2486CCB9E43FCA79039D3E0F63577406F5B6420F5587CF9DAC40118AA6F170A8" }
{ "low" : 448, "hi" : 511, "bytes" : "1ABA14E7E9E6BA4821774CBC2B63F410381E4D661F82BAB1B182005B6D42900DC658C6224F959E05095BC8081920C8AD11148D4F8BD746B3F0059E15C47B9414" } ]
xor_digest = "AD0620EB4E71605CDEA447A02E638F0C2A0096EA666010761DB03CFC8562968044D213B15EC69E1E5811EEBE7C96B6166BE36E42B16F9F4BE0CC71B456C1FCA1"
f()
desc = "Set 3, vector# 81"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "235E55E2759C6781BBB947133EDD4D91C9746E7E4B2E5EF833A92BE6086C57C6729655D4C4253EC17ACF359012E801757E7A6EB0F713DEC40491266604B83311" }
{ "low" : 192, "hi" : 255, "bytes" : "247BEAAC4A785EF1A55B469A1AEE853027B2D37C74B8DA58A8B92F1360968513C0296585E6745E727C34FFCE80F5C72F850B999721E3BF1B6C3A019DBEE464C1" }
{ "low" : 256, "hi" : 319, "bytes" : "E7DDB25678BF6EECA2DA2390C9F333EB61CD899DD823E7C19474643A4DA313352556E44A9C0006C8D54B1FD0313D574A08B86138394BA1194E140A62A96D7F01" }
{ "low" : 448, "hi" : 511, "bytes" : "DB417F9C1D9FD49FC96DB5E981F0C3F8484E3BDC559473963D12D982FEA287A39A36D69DDBBCF1CA2C9FB7F4B2B37F3DA755838A67C48822F4C1E82E65A07151" } ]
xor_digest = "119D1DDC7C95982B6B035FD4A4D8C5C9FD2518FFBC69C3C6A7F600174A3916146287F19BDDDAB385D2C6A39C593935F288B2F3E8895B9519EC71BA453319CC1F"
f()
desc = "Set 3, vector# 90"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "F27A0A59FA3D1274D934EACCFA0038AFC3B866D2BFA4A8BA81D698DBCA5B65D52F3A1AC9855BEEEB3B41C510F7489E35AB22CB4444816208C282C461FF16A7BC" }
{ "low" : 192, "hi" : 255, "bytes" : "522594154A2E4843083ABCA886102DA814500C5AADAAB0C8FB40381B1D750F9DA9A1831D8000B30BD1EFA854DC903D63D53CD80A10D642E332DFFC9523792150" }
{ "low" : 256, "hi" : 319, "bytes" : "5D092D8E8DDA6C878A3CFBC1EC8DD13F2A1B073916097AEC4C3E56A229D8E282DDB656DAD60DBC7DF44DF124B19920FCC27FCADB1782F1B73E0A78C161270700" }
{ "low" : 448, "hi" : 511, "bytes" : "8F75BF72995AD23E9ADFEA351F26E42BE2BE8D67FB810ABCBD5FAE552DC10D1E281D94D5239A4EA311784D7AC7A764FA88C7FD7789E803D11E65DD6AC0F9E563" } ]
xor_digest = "55AC113CC018689601F39AA80FA4FA26EE655D40F315C6B694FFAE74A09D382B62A4E7C60F75167361871A82561FFAC453BFED061D6B01672008308C92D241FF"
f()
desc = "Set 3, vector# 99"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "654037B9120AEB60BD08CC07FFEC5985C914DAD04CD1277312B4264582A4D85A4CB7B6CC0EB8AD16475AD8AE99888BC3FDE6A5B744851C5FC77EAB50CFAD021D" }
{ "low" : 192, "hi" : 255, "bytes" : "E52D332CD0DE31F44CDCAB6C71BD38C94417870829D3E2CFDAC40137D066EA482786F146137491B8B9BC05675C4F88A8B58686E18D63BE71B6FEFEF8E46D0273" }
{ "low" : 256, "hi" : 319, "bytes" : "28959548CE505007768B1AA6867D2C009F969675D6E6D54496F0CC1DC8DD1AFBA739E8565323749EAA7B03387922C50B982CB8BC7D602B9B19C05CD2B87324F9" }
{ "low" : 448, "hi" : 511, "bytes" : "D420AEC936801FEE65E7D6542B37C9190E7DB10A5934D3617066BEA8CC80B8EAAAFC82F2860FA760776418B4FF148DFD58F21D322909E7BF0EC19010A168FAF7" } ]
xor_digest = "5BAFB9BEA29B3658A5BBF649E09455B70FB262AB938B65FE71652A0662FF0FB514C35AF438A72A6122AC1AA8591477AEAEB78214C63E41255E87230481D1A793"
f()
desc = "Set 3, vector#108"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "0DB7EA55A79C045818C29E99D8A4B66433E4C77DF532D71BA720BD5D82629F1276EF0BF93E636A6F71F91B947DFA7CAAA1B0512AA531603197B86ABA2B0829D1" }
{ "low" : 192, "hi" : 255, "bytes" : "A62EAFD63CED0D5CE9763609697E78A759A797868B94869EC54B44887D907F01542028DEDDF420496DE84B5DA9C6A4012C3D39DF6D46CE90DD45AF10FA0F8AAF" }
{ "low" : 256, "hi" : 319, "bytes" : "7C2AD3F01023BC8E49C5B36AFE7E67DCA26CCD504C222BD6AF467D4C6B07B79261E9714FDD1E35C31DA4B44DB8D4FC0569F885F880E63B5ABB6BA0BFEE2CE80C" }
{ "low" : 448, "hi" : 511, "bytes" : "066D3C8D46F45891430A85852FF537448EBDD6CE8A799CCF7EAF88425FBD60D32A1741B39CC3C73371C2C9A36544D3C3B0F02D2596ACC61C60A6671F112F185E" } ]
xor_digest = "6EE5BF7E194B03A7DDC92FC74A398FF822471FEF6DD399426F7372E445E1EE365ED7164CD09120A79CCF03D0A2A309DC5932441B64DDC6FDC9E183DA9F825106"
f()
desc = "Set 3, vector#117"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "3FE4BD60364BAB4F323DB8097EC189E2A43ACD0F5FFA5D65D8BDB0D79588AA9D86669E143FD5915C31F7283F1180FCABCDCB64B680F2B63BFBA2AF3FC9836307" }
{ "low" : 192, "hi" : 255, "bytes" : "F1788B6CA473D314F6310675FC7162528285A538B4C1BE58D45C97349C8A36057774A4F0E057311EEA0D41DFDF131D4732E2EAACA1AB09233F8124668881E580" }
{ "low" : 256, "hi" : 319, "bytes" : "FEF434B35F024801A77400B31BD0E73522BEC7D10D8BF8743F991322C660B4FD2CEE5A9FDE0D614DE8919487CBD5C6D13FEB55C254F96094378C72D8316A8936" }
{ "low" : 448, "hi" : 511, "bytes" : "338FD71531C8D07732FD7F9145BBC368932E3F3E4C72D2200A4F780AF7B2C3AA91C1ED44DBEAA9A2F1B3C64DCE8DCD27B307A4104D5C755693D848BEA2C2D23B" } ]
xor_digest = "7ABF3C4E6E8CCAC05AA336DF2156E1957DFDAD45995FF6268B9708DAED9C2097F8F0F2A0EE5FBF4A7B511ED2E8E5617993E915E9BAABA30D758A9691E9D8578A"
f()
desc = "Set 3, vector#126"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "062187DAA84742580D76E1D55EE4DE2E3B0C454F383CFDDE567A008E4E8DAA3CE645D5BEDA64A23F0522D8C15E6DA0AD88421577A78F2A4466BD0BFA243DA160" }
{ "low" : 192, "hi" : 255, "bytes" : "4CC379C5CF66AA9FB0850E50ED8CC58B72E8441361904449DAABF04D3C464DE4D56B22210B4336113DAA1A19E1E15339F047DA5A55379C0E1FE448A20BC10266" }
{ "low" : 256, "hi" : 319, "bytes" : "BD2C0F58DBD757240AEB55E06D5526FE7088123CE2F7386699C3E2780F5C3F86374B7CB9505299D639B89D7C717BA8A2AEED0C529F22F8C5006913D1BE647275" }
{ "low" : 448, "hi" : 511, "bytes" : "54D61231409D85E46023ED5EFF8FDC1F7A83CACDDB82DD8D1FA7CDEA0E088A61D02BCE7FA7EC3B73B66953DA467BE4B912EBE2A46B56A8BF0D925A919B7B22E3" } ]
xor_digest = "9F569A8133067D1D4651BAE70DB3FE201649A1DA469C7D7C0B0DF16968285BF4ED0F36ED1CF9F213B2EC4BFF83D455FFC8B19E82DAE61408141F221C255DDFAB"
f()
desc = "Set 3, vector#135"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "1A74C21E0C929282548AD36F5D6AD360E3A9100933D871388F34DAFB286471AED6ACC48B470476DC5C2BB593F59DC17EF772F56922391BF23A0B2E80D65FA193" }
{ "low" : 192, "hi" : 255, "bytes" : "B9C8DAC399EF111DE678A9BD8EC24F340F6F785B19984328B13F78072666955AB837C4E51AC95C36ECBEFFC07D9B37F2EE9981E8CF49FD5BA0EADDE2CA37CC8D" }
{ "low" : 256, "hi" : 319, "bytes" : "3B0283B5A95280B58CEC0A8D65328A7A8F3655A4B39ECBE88C6322E93011E13CFF0A370844851F4C5605504E8266B301DD9B915CA8DCD72E169AEA2033296D7F" }
{ "low" : 448, "hi" : 511, "bytes" : "4F9CA1676901DDC313D4EE17B815F6B5AC11AF03BF02517FB3B10E9302FCBF67C284B5C7612BBE7249365BCAC07FD4C2C7AE78F3FDA1880B2DAA20E4EC70F93B" } ]
xor_digest = "9B9EA936FD4385D3516304BEFC44BC6D5B60C97925B52CE269F2843496DEBD335A07ADA2EC87BA27E306CFFB884935D774EE317C7307740B884095278D1DB0C2"
f()
desc = "Set 3, vector#144"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "0281FB6B767A90231AB6A19EB1E4FB76A041063FE23AC835797DFA178CC2D7C28DFAD591D2EAF26A985332F8DC74537DF7E0A5F26946BCF7D70B6C3D9DD859D2" }
{ "low" : 192, "hi" : 255, "bytes" : "088ED6D7AB26EEC97518EBF387B0644FD22266E578F141A7218F94AE2EE5885A67A9FA304F6880A781EE05C1251A7EAD4C3025D833B59739C68D3D7F3A844148" }
{ "low" : 256, "hi" : 319, "bytes" : "6B48D13EC0EB1CD0CDAC5D5E09DC7BE4AE02BE4283DDC7FA68E802A31508E6EA7197E5AC10805FDEB6824AEEF8178BAA45D7E419CF9237155D379B38F994EF98" }
{ "low" : 448, "hi" : 511, "bytes" : "7E71823935822D048B67103FF56A709A25517DCE5CFBB807B496EEF79EFFBCD10D23BAD02758814F593B2CD4AC062699AEC02B25A7E0D1BAE598AFDBE4333FE7" } ]
xor_digest = "0D4802AF0B0F92FFF2F80FE65FE5D1FBDFEF122231028FE36CC164D1D39185A1869AD43D08C6E1C9F8A9113CE2CEF0A022629C6FAC1C27E6DDF2A46C52293681"
f()
desc = "Set 3, vector#153"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "D4ACE9BF4A76822D685E93E7F77F2A7946A76E3BF0910854C960331A41835D40902BC1CF3F8A30D4C8391087EC3A03D881E4734A5B830EFD55DA84159879D97F" }
{ "low" : 192, "hi" : 255, "bytes" : "5BD8BB7ED009652150E62CF6A17503BAE55A9F4ECD45B5E2C60DB74E9AE6C8BF44C71000912442E24ED2816243A7794D5B1203A246E40BE02F285294399388B1" }
{ "low" : 256, "hi" : 319, "bytes" : "55433BDEA349E8849D7DF899193F029A9F09405D7AFE842CB2C79F0E55C88913B0776825D8D036A69DDDCD6AFCA6588F69F0946A86D32C3585F3813B8CCB56AF" }
{ "low" : 448, "hi" : 511, "bytes" : "0B67F00FA0BB7D1ED5E4B46A687948645239422656F77EF2AFEA34FFF98DA7A890970F09137AF0FABD754C296DD3C6F27539BC3AE78FFA6CDCCC75E944660BB4" } ]
xor_digest = "9D6D8BAB5F6EDB5450EA2D5751741351199ED720B0572410FD698C99F2E0DB92C0E62E68AEE0CC6CDB6EA8898BFD29E8E106470DE4E5C66F94FE0258A2D24CA3"
f()
desc = "Set 3, vector#162"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "92A067C3724F662120C25FAF4B9EC419C392D98E5CB8C5EE5842C1D5C704DE878C8C68C55BA83D63C5DEEC24CFF7230D3F6FBF6E49520C20CFE422798C676A47" }
{ "low" : 192, "hi" : 255, "bytes" : "133C9A30B917C583D84FB0AAC2C63B5F6758AC8C2951196E9460ADBE3417D91490F0A195DC5682F984069506CA75DC1D79A7AE1DCDF9E0219D4E6A005BA72EDD" }
{ "low" : 256, "hi" : 319, "bytes" : "091D38749503B63238B1E3260855B76C5CFE9D012265FB7F58EB8CAA76B456459C54F051274DDAE06BEC6D7EB8B9FF595302D9D68F2AF1057581D5EE97CCEEDD" }
{ "low" : 448, "hi" : 511, "bytes" : "3FCCB960792B7136768BBA4C3D69C59788F04602C10848A7BCBED112F860998D9E9A788998D1DC760F7ECF40597446D8F39CD4D4013F472BB125DE6A43E9799D" } ]
xor_digest = "12464226235C1DDDAFA37DF12F3A044442C0EEE521DBB7B3239C86ADB61AD6A0A418D3804252DC3658A3AE82473023A8D190E1EDB1DAFA3CF566573511CF8F19"
f()
desc = "Set 3, vector#171"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "AC3DE1B9F6DF6D6117B671A639BF076124A0A6D293B107554E9D662A8BFC3F3417C59437C981A0FDF9853EDF5B9C38FE74072C8B78FE5EBA6B8B970FE0CE8F1F" }
{ "low" : 192, "hi" : 255, "bytes" : "23112BD4E7F978D15F8B16F6EDB130D72F377233C463D710F302B9D7844C8A47FB2DFDD60235572859B7AF100149C87F6ED6CE2344CDF917D3E94700B05E2EEF" }
{ "low" : 256, "hi" : 319, "bytes" : "E8DDFE8916B97519B6FCC881AEDDB42F39EC77F64CAB75210B15FBE104B02FC802A775C681E79086D0802A49CE6212F177BF925D10425F7AD199AB06BD4D9802" }
{ "low" : 448, "hi" : 511, "bytes" : "F9D681342E65348868500712C2CA8481D08B7176A751EF880014391A546809926597B10E85761664558F34DA486D3D4454829C2D337BBA3483E62F2D72A0A521" } ]
xor_digest = "75BEFA10DACA457FFE4753A13543F9964CF17E6941318C931575A0865B1C86C12EE5E031EFD125A3D56C4B7846C19484507CC551C5CB558533E288BA0D2C14F1"
f()
desc = "Set 3, vector#180"
key = "<KEY>"
IV = "<KEY>000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "21BD228837BFB3ACB2DFC2B6556002B6A0D63A8A0637533947615E61FE567471B26506B3D3B23F3FDB90DFAC6515961D0F07FD3D9E25B5F31B07E29657E000BF" }
{ "low" : 192, "hi" : 255, "bytes" : "2CF15E4DC1192CA86AA3B3F64841D8C5CD7067696674B6D6AB36533284DA3ABFD96DD87830AE8FA723457BE53CB3404B7A0DCBB4AF48A40FC946C5DEB7BD3A59" }
{ "low" : 256, "hi" : 319, "bytes" : "E3B15D2A87F61C2CE8F37DCEB896B5CA28D1DA6A3A71704309C0175BB61169119D5CBE34FC8F052961FF15F2C8F06CD6F8E889694E2C69E918DD29C33F125D31" }
{ "low" : 448, "hi" : 511, "bytes" : "CCD1C951D6339694972E902166A13033A1B0C07313DC5927FE9FB3910625332C4F0C96A8896E3FC26EFF2AF9484D28B8CB36FF4883634B40C2891FA53B6620B1" } ]
xor_digest = "1E6FA2DF675C21D1AA9819BA05D3C96D3463D6F0758286BBB41A63F8748B94C8B652C60C5D4655E8436F2379CA7088B49625667F386BC5A2F25FD0BFB0088FAA"
f()
desc = "Set 3, vector#189"
key = "<KEY>"
IV = "0<KEY>00000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "7943AD4AA5F62E08E1AE450E84CFF27DE3B204A2BCA315B981906D5A13F68AB034D3396EA8A41001AF49834368805B37D5380FB14821E3F7F4B44231784306F3" }
{ "low" : 192, "hi" : 255, "bytes" : "415F5381C9A58A29045E77A1E91E6726DFCEBC71E4F52B36DBD7432D158F2ADB31CF5F52D8456952C09B45A16B289B7A32687716B8EDFF0B1E5D0FC16DCCFA88" }
{ "low" : 256, "hi" : 319, "bytes" : "CE317CB853E2AFA22392D4B8AE345A910807F8DE3A14A820CDA771C2F2F3629A65A1CC7A54DDEC182E29B4DACEA5FBFA4FAC8F54338C7B854CD58ABA74A2ACFF" }
{ "low" : 448, "hi" : 511, "bytes" : "5804F61C5C07EC3C2D37DF746E4C96A1AD5E004C2585F3F401CB3AF62CB975F864375BE3A7117079810418B07DABCCEE61B6EC98EA4F28B0D88941CB6BE2B9D2" } ]
xor_digest = "9DBDBD0C3B340F294B1EB42CAD3111F0A5CF6A0B6206976022C6A2D6303A235B717542C25397879A27480D67AC5A245D0C58<KEY>CD801764A948060CA6F99E2D6"
f()
desc = "Set 3, vector#198"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "A4FB9A02500A1F86145956E16D04975E2A1F9D2283D8AD55C17A9BD6E0C8B5616658132B8928F908FEC7C6D08DBFBC5573449F28AA0EF2884E3A7637233E45CD" }
{ "low" : 192, "hi" : 255, "bytes" : "74D169573560C14692BBE2498FDA0ED7866A11EE4F26BB5B2E9E2559F089B35EC9972634C5A969DD16EB4341782C6C29FBBF4D11ECB4133D1F9CA576963973EB" }
{ "low" : 256, "hi" : 319, "bytes" : "D28966E675759B82EDE324ABA1121B82EAB964AB3E10F0FE9DF3FCC04AFC83863A43FD6B7FC0AD592C93B80BE99207CBA8A55DDEA56DD811AAD3560B9A26DE82" }
{ "low" : 448, "hi" : 511, "bytes" : "E362A817CCD304126E214D7A0C8E9EB93B33EB15DE324DDDFB5C870EA22279C78E28EFF95974C2B935FC9F1BF531D372EF7244D2CC620CEBDE5D8096AD7926B3" } ]
xor_digest = "3DD73F824FD1D9CB55B7E37C9C8A55C7EBB0866564AEA680BBBD431554D89E81FF280B563D5991438CEA5C183C607ADC23CC72CDE3A4D2CEB27B81ED8E5C9215"
f()
desc = "Set 3, vector#207"
key = "<KEY>"
IV = "0<KEY>00000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "FF879F406EAF43FABC6BE563ADA47C27872647F244C7FAE428E4130F17B471380E1E1CD06C50309760FDEE0BC91C31D0CA797E07B173C6202D2916EEBA9B6D1C" }
{ "low" : 192, "hi" : 255, "bytes" : "61E724B288AECF393483371C1BE653F37BBA313D220173A43459F0BCE195E45C49B3B5FB1B0539DE43B5B4F2960D8E6E5BC81DAF07E9EFBB760881441FA8823B" }
{ "low" : 256, "hi" : 319, "bytes" : "F77AC22945ECD60EBCAF4BA19A59B078B3C3BC36D1DDA6B9969B458C2019D68EFD04D75DDC6041BBCD69747651D2DA7FBED721081F8147367585CABB1C50CF0C" }
{ "low" : 448, "hi" : 511, "bytes" : "7475DCD3545B810445AFCA0C0AFA93A911EA99991A5D639AB32DDF69AA21C45A53DCB998FDAE5F9A82EC8501123EAE3D99351C43311F8430DB3D230E12DA77D2" } ]
xor_digest = "A61CDBCF6F79213D2A789543B0EA3D8A22BA4FB8118C1D40AE56EC823886156620CED8AA76FFE917C1E52060F91EE73BC75E913D072C50B3D939<KEY>04F69493553"
f()
desc = "Set 3, vector#216"
key = "<KEY>"
IV = "0<KEY>000000<KEY>"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "2B4C4185E2FDFAE75DABFF32632FB5D9823359F15E2D17FF74FAC844E5016A4A64C2C47498A15029FBEB6E4893381E656D2A2B9712524827B151C6E67D990388" }
{ "low" : 192, "hi" : 255, "bytes" : "D870A94C4856EF818C5D93B2187F09C732E4491103B8A49B14CDC118F1607E2D8443740F20220DF076B981D90436E9C309282C1CEAAE6375002AD1CA9CCF720C" }
{ "low" : 256, "hi" : 319, "bytes" : "5091AE53E13948DAE57F6B0BE95B8F46A1F53553767B98F9799A0F0AC468AEB340C20E23FA1A8CAE7387CEA127A7A0F3635667BF028DE15179093B706306B99C" }
{ "low" : 448, "hi" : 511, "bytes" : "02323B1FA2C863D3B4A89CFC143013A6EEA8265BBD1B8FE243DEA2F4B19A5726593564E7E7021FD042F58077A5821C2F415BC38D6DD2BE29A5400E4B1D65B2A2" } ]
xor_digest = "9B29085D13B4992B077E3A878A5918B592C98C8A83956EC20EFE673A24C48C915D8DB1A4A66F62F1A3E7D6ADF6DC8845DD7A6D43F9DBF6C1EA21639060469AD6"
f()
desc = "Set 3, vector#225"
key = "<KEY>"
IV = "0<KEY>000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "9A5509AB6D2AB05C7DBA61B0CC9DD844B352A293E7D96B5C0066ACDB548DB8570459E989B83AF10A2C48E9C00E02671F436B39C174494787D1ECEB3417C3A533" }
{ "low" : 192, "hi" : 255, "bytes" : "8A913EBA25B4D5B485E67F97E83E10E0B858780D482A6840C88E7981F59DC51F2A86109E9CD526FCFA5DBF30D4AB575351027E5A1C923A00007260CE7948C53D" }
{ "low" : 256, "hi" : 319, "bytes" : "0A901AB3EBC2B0E4CBC154821FB7A0E72682EC9876144C4DC9E05098B6EFCCCB90E2F03837553C579CDD0A647D6A696350000CA57628B1E48E96242226A92ECC" }
{ "low" : 448, "hi" : 511, "bytes" : "9CDB39B79A464F2CCA3637F04EBAEA357A229FC6A9BA5B83171A0A8945B6F11756EBC9F4201D0BA09C39F9776721304632AA6A68ADE5B90268AEE335E13B1D39" } ]
xor_digest = "695757EDF4992CE9E1C088D62CAB18A38F56EE71F1F4866E88D1A02E07CB89B9133F0B02A23BA39622E84E19DACDF32397F29<KEY>0<KEY>785<KEY>4<KEY>717093131A10B1"
f()
desc = "Set 3, vector#234"
key = "<KEY>"
IV = "<KEY>"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "37EDAFA4F5EDC64EBF5F74E543493A5393353DE345A70467A9EC9F61EEFE0ED4532914B3EA6C2D889DA9E22D45A7DD321EA5F1F6978A7B2E2A15D705DE700CE4" }
{ "low" : 192, "hi" : 255, "bytes" : "C415739777C22430DAB2037F6287E516B1CE142111456D8919E8CD19C2B2D30D8A1B662C26137F20F87C2802A2F3E66D8CEB9D3C1B4368195856249A379BD880" }
{ "low" : 256, "hi" : 319, "bytes" : "0381733EC9B2073F9E4E9954471184112D99B23FA4A87B4025C6AF955E93E0D57DD37011E1624175F970BDA7D625224BAB0F021E6453DBA894A5074C447D24BC" }
{ "low" : 448, "hi" : 511, "bytes" : "F9D45C7E0E7A26F2E7E2C07F68AF1191CC699964C01654522924A98D6790A946A04CD9586455D5A537CBA4D10B3C2718745C24875156483FE662B11E0634EAEA" } ]
xor_digest = "E0FE8129B73BCADA14FB385E6D3DB22D84C9755D63E93141202576FB5B2D3647D47B2F6378BC8567E4416976443FAE763C2B5FA46F2670C301A5B22802513D2D"
f()
desc = "Set 3, vector#243"
key = "<KEY>"
IV = "<KEY>00000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "B935A7B6D798932D879795A182E7C194BECEFF32522C2F3FFF55A5C6D32A91D2BA9F144DB280ABA7BA8A7921AFA3BD82CA742DDBEAF8AF72299936E9C2FEA59E" }
{ "low" : 192, "hi" : 255, "bytes" : "6F32248B6EF4CDAE06864B6477893440F0E0217421D7081D1F0DA197B52636740E9BDD59068BEDE48BF52C43446C12CD4F10ED22BFDDFA915FA0FB1A73F9139C" }
{ "low" : 256, "hi" : 319, "bytes" : "BF01A4ED868EF9080DF80689E589897C021DCA18073F9291E1D158DC26266556728DD130629D3760F541439147F4C1CA279FB98040E9FCE50998E42D6259DE1F" }
{ "low" : 448, "hi" : 511, "bytes" : "0F2B116CD687C91FBA1EDEAD586411E966D9EA1076863EC3FDFC254DD5C93ED6AE1B01982F63A8EB13D839B2510AD02CDE24210D97A7FA9623CAC00F4C5A1107" } ]
xor_digest = "C6970385CA89CDFCACA9E90DA2A2FE9958EF83B9BF04DBE7A3B343750368883105FF6665D9F91D4DBBBCAF31B555ED3DD07C3AC8242817<KEY>0BF834693C596AD54"
f()
desc = "Set 3, vector#252"
key = "<KEY>"
IV = "0<KEY>0000<KEY>"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "09D36BFFDDCD3ADC8EB0ABEEB3794CE1FFBDED9CFC315D21A53C221B27722FE3F10E20D47DDCFD3CCDE9C1BAAF01F5511D3F14F88BF741A7F6578C3BC9024B2B" }
{ "low" : 192, "hi" : 255, "bytes" : "552502A1B2D0F29806DE512F3314FC8E19518E35D9DB1EBC9034EA46E5815AB9DF0F403E997E676BF47C0116D5E9B81726B99D65AA4315F1E5906F6E39B1297E" }
{ "low" : 256, "hi" : 319, "bytes" : "6BF351A501E8D1B4BAF4BFD04726DC4F50200463DCC13FF3BE93E6C4D4304CE09E6A1CEA41BFB93D6DBAD713298F79CFF6F5BB81F456E33A3396D02F2E33BDC5" }
{ "low" : 448, "hi" : 511, "bytes" : "715F8FFB2BC25CD89E46B706EF871207EFE736AA3CB961B06E7B439E8E4F76E2944AF7BD49EEC47B4A2FD716D191E85859C74FD0B4A505ACE9F80EEB39403A1F" } ]
xor_digest = "D51B519D78CDBC8DF5CB1CEA5EBBA6E46530535D84CBF1696EBF238D3F7AA4A1D2F1EF5FF092DB57943E28501C64CFF04619197ED4A3D82EE<KEY>"
f()
desc = "Set 4, vector# 0"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "BE4EF3D2FAC6C4C3D822CE67436A407CC237981D31A65190B51053D13A19C89FC90ACB45C8684058733EDD259869C58EEF760862BEFBBCA0F6E675FD1FA25C27" }
{ "low" : 65472, "hi" : 65535, "bytes" : "F5666B7BD1F4BC8134E0E45CDB69876D1D0ADAE6E3C17BFBFE4BCE02461169C54B787C6EF602AF92BEBBD66321E0CAF044E1ADA8CCB9F9FACFC4C1031948352E" }
{ "low" : 65536, "hi" : 65599, "bytes" : "292EEB202F1E3A353D9DC6188C5DB43414C9EF3F479DF988125EC39B30C014A809683084FBCDD5271165B1B1BF54DAB440577D864CD186867876F7FDA5C79653" }
{ "low" : 131008, "hi" : 131071, "bytes" : "C012E8E03878A6E7D236FEC001A9F895B4F58B2AF2F3D237A944D93273F5F3B545B1220A6A2C732FC85E7632921F2D366B3290C7B0A73FB61D49BC7616FC02B8" } ]
xor_digest = "196D1A0977F0585B23367497D449E11DE328ECD944BC133F786348C9591B35B7189CDDD934757ED8F18FBC984DA377A807147F1A6A9A8759FD2A062FD76D275E"
f()
desc = "Set 4, vector# 1"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "BA1A48247B8C44AAF12F5645D65FF7F4E4D7C404EE0CBB691355FAEB82D03B99AD0FDFC20A1E593973E5B8F0264F7FB0538292A4C8FE8218A1DA3EB7B71EEA64" }
{ "low" : 65472, "hi" : 65535, "bytes" : "03A24E89D69D5E1DA98B0367CF626F33D558B1208AB120B6B1778BFF640F56DA715FE1B681D8CC0F305D6645B439BA81D3C446A428B31BB18E9DA1E2A900B0FD" }
{ "low" : 65536, "hi" : 65599, "bytes" : "6A28ADD4F926759CEBB0AFC5D5DA52431F2E7ECBBD1E9DEAF368137E35F1AFBD65852214FA06310C3175FCF364810F627E3703E9AC5458A8B681EB03CEECD872" }
{ "low" : 131008, "hi" : 131071, "bytes" : "E8D8AB5E245B9A83A77B30F19E3706F037272E42F9C6CD7E8156C923535EF119B633E896E97C404C6D87565EEA08EB7FF6319FF3E631B6CDD18C53EE92CCEEA0" } ]
xor_digest = "2BD4F834BC7B3C128E291B2BCE7DA0A5BA1A17E2785093B7F32B7D605AE63276F8256998EC1E0B5A7FD2D66EE9B0B705E49435EDF8BACE1BE770738A403<KEY>8F14"
f()
desc = "Set 4, vector# 2"
key = "<KEY>"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "8313F4A86F697AAC985182862E4FC6233511C46B6DAEEDB94B63461111CB476872F1BC3B4E8EE80A4ADE7D1A8CD49C171D3A550D3F39B7775734225579B8B60A" }
{ "low" : 65472, "hi" : 65535, "bytes" : "6AFA6F539C0F3B0B9DEB0235E7EB2E14B111615D4FBC5BF7FFE75E160DEDA3D9932125469AEC00539ECE8FCF8067CB0FB542C2064267BEA7D9AD6365314D5C2C" }
{ "low" : 65536, "hi" : 65599, "bytes" : "296F2B5D22F5C96DA78304F5800E0C87C56BC1BACD7A85D35CFECE17427393E1611975CC040D27DF6A5FABC89ADDE328AE8E9CB4F64CFA0CB38FE525E39BDFE4" }
{ "low" : 131008, "hi" : 131071, "bytes" : "86C8139FD7CED7B5432E16911469C7A56BDD8567E8A8993BA9FA1394348C2283F2DF5F56E207D52A1DA070ABF7B516CF2A03C6CD42D6EA2C217EC02DF8DDCA9C" } ]
xor_digest = "DEEBF1FCF222519E26EC6556EA44908092923B357CB88D1A1C1B03341F5C6A984C70E9DB735377615C0476D46DA9897B48127A0D224241<KEY>8CF51B005EF93"
f()
desc = "Set 4, vector# 3"
key = "<KEY>"
IV = "0<KEY>0000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "62765613D127804ECD0F82D208D701563B1685EEF67945DAE2900307CDB14EA62474A439D8BAE8005493455471E7BCB9DB75F0596F3FB47E65B94DC909FDE140" }
{ "low" : 65472, "hi" : 65535, "bytes" : "00A0D5B2CE7B95E142D21B57B187C29C19B101CD063196D9B32A3075FB5D54A20D3CE57CBEC6CA684CB0E5306D5E21E5657F35B8FB419A0251EA5CD94113E23B" }
{ "low" : 65536, "hi" : 65599, "bytes" : "AAC2D29404A015047DEFB4F11460958DA989141026FE9325F15954363FC78898D4A20F6870F4D2B124590973F6956096940E2324F7C63384A85BACF53F7755E3" }
{ "low" : 131008, "hi" : 131071, "bytes" : "0A543607FE352336ACFEDFE6B74359E0B26B19FD45A8938C6C0A6DB68A1377495B65211558D0CB9ECA9DA2C0E50702B688B2DEC53AAA2FBF11BD149F4F445696" } ]
xor_digest = "D124AA942DC1D54D5B9B4BC6804F9990543EAF31FF441F0CD16B961C817EA4A76AF71F678BBB482052B2BA767B4F9265B65C3D839D182D093B560AEB09184C0C"
f()
desc = "Set 5, vector# 0"
key = "<KEY>"
IV = "8000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "B66C1E4446DD9557E578E223B0B768017B23B267BB0234AE4626BF443F219776436FB19FD0E8866FCD0DE9A9538F4A09CA9AC0732E30BCF98E4F13E4B9E201D9" }
{ "low" : 192, "hi" : 255, "bytes" : "462920041C5543954D6230C531042B999A289542FEB3C129C5286E1A4B4CF1187447959785434BEF0D05C6EC8950E469BBA6647571DDD049C72D81AC8B75D027" }
{ "low" : 256, "hi" : 319, "bytes" : "DD84E3F631ADDC4450B9813729BD8E7CC8909A1E023EE539F12646CFEC03239A68F3008F171CDAE514D20BCD584DFD44CBF25C05D028E51870729E4087AA025B" }
{ "low" : 448, "hi" : 511, "bytes" : "5AC8474899B9E28211CC7137BD0DF290D3E926EB32D8F9C92D0FB1DE4DBE452DE3800E554B348E8A3D1B9C59B9C77B090B8E3A0BDAC520E97650195846198E9D" } ]
xor_digest = "104639D9F65C879F7DFF8A82A94C130CD6C727B3BC8127943ACDF0AB7AD6D28BF2ADF50D81F50C53D0FDFE15803854C7D67F6C9B4752275696E370A467A4C1F8"
f()
desc = "Set 5, vector# 9"
key = "<KEY>"
IV = "004<KEY>00000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "1A643637B9A9D868F66237163E2C7D976CEDC2ED0E18C98916614C6C0D435B448105B355AE1937A3F718733CE15262316FA3243A27C9E93D29745C1B4DE6C17B" }
{ "low" : 192, "hi" : 255, "bytes" : "CDDB6BD210D7E92FBFDD18B22A03D66CC695A93F34FB033DC14605536EEEA06FFC4F1E4BACFCD6EB9DA65E36C46B26A93F60EAA9EC43307E2EA5C7A68558C01A" }
{ "low" : 256, "hi" : 319, "bytes" : "5FC02B90B39F3E90B8AEC15776F2A94FD8C26B140F798C93E1759957F99C613B8B4177A7B877D80A9B9C76C2B84E21A6DF803F0DB651E1D0C88FB3743A79938F" }
{ "low" : 448, "hi" : 511, "bytes" : "B4BC18F7279AC64BB6140A586F45AC96E549C0CA497F59B875C614DE605A8BFF63AB3F1E00DAEAE7A5CC7A7796E9BACCDD469E9100EABCD6E69301EA59C4B76A" } ]
xor_digest = "4EF8F9A7D50D7ABEC1A104565E9E20BF35FACFDD5600B0360E3ECBDE626CC6934A52173415C05BA5EE681D649CB60D186970CF18BC028AF829054903FDEB37BA"
f()
desc = "Set 5, vector# 18"
key = "<KEY>"
IV = "0000200000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "94B7B07E184BC24A0904290B2601FC3AC70BEAD7B1FC3294360ED4EF168134530B4D1F3F28A3C3B248B2E914A8DCBD5326A240C9BB361A8A93D023725BDCD4E3" }
{ "low" : 192, "hi" : 255, "bytes" : "27C7A2C4EAA1E2E8798CA71EA50B7E5ACD9FC82263D11781EFC16142CFD21A634DB2B860B54A9979AFA187CE0667D17623FC91EC1E5E6C31A8089628AC76F9F0" }
{ "low" : 256, "hi" : 319, "bytes" : "C2CD243516E5919D6C5C478469260813ABE8E6F54BE8E11D48FEC043CDADA19BEFE9CB0C22A9BB30B98E4CFCF1A55EF1263B209CE15FEAEF8237CFAF7E5286D6" }
{ "low" : 448, "hi" : 511, "bytes" : "84489BD680FB11E5CAA0F5535ABA86DCFF30AC031CEFED9897F252803597772670E1E164FA06A28DD9BAF625B576166A4C4BF4CADD003D5DF2B0E6D9142DD8B3" } ]
xor_digest = "783AD910F37369EFB54DD9A00D54CDB72EEAF2693C121B13344025E08DF874AC4BBC08B8FA916B423B0F4667A6D1BAEC3016B999FF9<KEY>6<KEY>22<KEY>FF925AB"
f()
desc = "Set 5, vector# 27"
key = "<KEY>"
IV = "0<KEY>1<KEY>0000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "2E6C8BE7DD335292EE9152641B0E4EFB43D27434E4BE70EAC4CAFAE5C38B2E5B06E70B9966F4EDD9B4C4589E18E61F05B78E7849B6496F33E2FCA3FC8360824C" }
{ "low" : 192, "hi" : 255, "bytes" : "1006D6A04165A951C7EE31EEB0F6C32BD0B089683C001942886FCEF9E700D15ADB117652735C546D30177DC14FA68708D591C3254C05B84BF0DCBC3105F06A6F" }
{ "low" : 256, "hi" : 319, "bytes" : "2196ADA05BED2BD097A43E4C5BE6C9404A353689939DCB9C4F82278BDB0EB505F70FFD9921B46645EDDFCF47405FD3E67CAE732B367A0B0F2B57A503161FA5DE" }
{ "low" : 448, "hi" : 511, "bytes" : "4A3504DAC25F59489C769090D822E89E1338AC73F22DB2614B43D640525EF9969D6B7E3900ADCBE056AB818E0FF708E3B0A8E63531F252C384DD3DE7318EA866" } ]
xor_digest = "33533F81725EA5444E0642A07A334AE5AC3DD16214F6FE196A60A4343AFA5026E1602E84D3E672EEDB9FB5BB6F44C02366C28BD8E3<KEY>673<KEY>438<KEY>82561<KEY>"
f()
desc = "Set 5, vector# 36"
key = "<KEY>"
IV = "00<KEY>0000008000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "1D3FD8BAF2A13BCD2A49B50F8DFB05228E366B4FD2ECD6973DFF116289D7E0AF55EFB875345204B5FCE27A1C6DF79531B3175647526BF5C028C454BADEFBECD6" }
{ "low" : 192, "hi" : 255, "bytes" : "F639D0D23CC5817501517216ADA14241D08495F17CDEAFB883CE619A3255EC3FEAADFA224CF354C425A74D3DDAAA0C86E44016238C142B36944EF53A1EC7DF92" }
{ "low" : 256, "hi" : 319, "bytes" : "9CAE4D4639696A188E08BC1B017746085D18418F82DC90742BB6D172414ACC13A4721B018B2CC002CB6E6FFE4A4E252CC4BF5DE975684C8805036F4C76660DC8" }
{ "low" : 448, "hi" : 511, "bytes" : "CB2A2CB3136F5CC71FD95A4A242B15E51C8E3BAE52FEC9C1B591B86DFDDC2442353DF500B2B9868A6C609655FC1A3E03347608D12D3923457EEEB34960F4DB31" } ]
xor_digest = "D623CA4753D2197E68B87B1ACBD84CC9A056EC02F83D7E399CE2C4ACCF7934A5A0CAE68FC0EB88098AA39DA88881C7B24C137195F32DA5CA86631CB84A6BC3B2"
f()
desc = "Set 5, vector# 45"
key = "<KEY>"
IV = "0000000000040000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "2DCAD75F5621A673A471FDE8728FACF6D3146C10A0903DE12FBDCE134CC0F11B2D2ABBDBADFA19303E264011A1B9EFECAB4DFBC37E3D0F090D6B069505525D3A" }
{ "low" : 192, "hi" : 255, "bytes" : "02C401ACF6D160CC1D80E11CB4F3038A4C5B61C995CD94E15D7F95A0A18C49D5DA265F6D88D68A39B55DB3505039D13EAB9DEBD408CE7A79C375FD3FEBEF86C8" }
{ "low" : 256, "hi" : 319, "bytes" : "83D92AF769F5BF1FA894613D3DF447EBD461CFFC0CA3A9843E8441EC91DEBC67BE9162EABC5607A6D3FCAD4426EF4F9F3B42CEC8C287C194B2211DEA4549D5D5" }
{ "low" : 448, "hi" : 511, "bytes" : "D3F86930112EAFC7AA430444693BAE773F014D0798CAF3652A3432460F326DA88E82BE1E08C220B5FCBCE238B982E37D1E60DCBF1747D437D42DB21ADF5EECF2" } ]
xor_digest = "0BF26BADEFCB5BB32C43410920FF5E0F2720E8BB1C94DD5D04F0853F298C3ABA8FF670AF163C5D24BCAF13AD0A04196A2B89E82CF88846C77C77A097E234010F"
f()
desc = "Set 5, vector# 54"
key = "<KEY>"
IV = "0000000000000200"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "D8E137C510CDBB1C788677F44F3D3F2E4C19FCEB51E7C2ECBDB175E933F44625C7B0168E446CCCA900B9DB12D53E89E1B917A69BDB888935B3B795D743D0D0E6" }
{ "low" : 192, "hi" : 255, "bytes" : "E168F81B5BFB769F3380690D423E251E0F4BEEBE0B02F19AFFADBD94212B8063D77A665FD53F8F1A1CC682599C74F4153642EC7DADA034403A90E1E5DA40C896" }
{ "low" : 256, "hi" : 319, "bytes" : "574774CFB8452E82777371616E0AC224E29939E725B99EA8CFB4A9BF459A70D6AB1991E85E06905ACCDA8D1911F828359C4FD7614A55C1E30171934412D46B3E" }
{ "low" : 448, "hi" : 511, "bytes" : "21FE9B1F82E865CC305F04FA2C69EA976D90A41590A3BD242337D87D28E3041D3D0F74CA24A74453CB679FDFFEE45AA63B2DDE513D3F9E28E86346D9A4114CD7" } ]
xor_digest = "3E25D50331D9840FBD4F8B0FD10A9D646A5E8E0ADE57CCDECF346B2973631740382139165B0E0E78A53E4B6CAABE6517BF02B7B2905F9A64A60F412CA78E6929"
f()
desc = "Set 5, vector# 63"
key = "<KEY>"
IV = "0000000000000001"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "42DCF10EA1BCBA82C88DDCDF905C9C7842A78AE57117F09CE51517C0C70063CF1F6BC955EF8806300972BD5FC715B0ED38A111610A81EBA855BB5CD1AEA0D74E" }
{ "low" : 192, "hi" : 255, "bytes" : "261E70245994E208CDF3E868A19E26D3B74DBFCB6416DE95E202228F18E56622521759F43A9A71EB5F8F705932B0448B42987CEC39A4DF03E62D2C24501B4BDE" }
{ "low" : 256, "hi" : 319, "bytes" : "9E433A4BF223AA0126807E8041179CC4760516D3537109F72124E3534A24EA7DB225C60063190FD57FF8595D60B2A8B4AE37384BB4FCD5B65234EE4FB0A1EBEA" }
{ "low" : 448, "hi" : 511, "bytes" : "3F9803DD763449758F008D77C8940F8AFB755833ED080A10513D800BA3A83B1C028A53AED0A65177C58B116E574745D0F28506A9DACD6F8A3D81613E00B12FDB" } ]
xor_digest = "C0CA35A30730FCE3A6B08FD9707EBD1C8154F54266696A99430BCA8B9F94FDD1A78CCB43CB67C58EFF3B171A38597F12AA6A424088C062B97613691B7D12CDE6"
f()
desc = "Set 6, vector# 0"
key = "<KEY>"
IV = "0D74DB42A91077DE"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "05E1E7BEB697D999656BF37C1B978806735D0B903A6007BD329927EFBE1B0E2A8137C1AE291493AA83A821755BEE0B06CD14855A67E46703EBF8F3114B584CBA" }
{ "low" : 65472, "hi" : 65535, "bytes" : "1A70A37B1C9CA11CD3BF988D3EE4612D15F1A08D683FCCC6558ECF2089388B8E555E7619BF82EE71348F4F8D0D2AE464339D66BFC3A003BF229C0FC0AB6AE1C6" }
{ "low" : 65536, "hi" : 65599, "bytes" : "4ED220425F7DDB0C843232FB03A7B1C7616A50076FB056D3580DB13D2C295973D289CC335C8BC75DD87F121E85BB998166C2EF415F3F7A297E9E1BEE767F84E2" }
{ "low" : 131008, "hi" : 131071, "bytes" : "E121F8377E5146BFAE5AEC9F422F474FD3E9C685D32744A76D8B307A682FCA1B6BF790B5B51073E114732D3786B985FD4F45162488FEEB04C8F26E27E0F6B5CD" } ]
xor_digest = "620BB4C2ED20F4152F0F86053D3F55958E1FBA48F5D86B25C8F31559F31580726E7ED8525D0B9EA5264BF977507134761EF65FE195274AF<KEY>000938C03BA59A7"
f()
desc = "Set 6, vector# 1"
key = "<KEY>"
IV = "167DE44BB21980E7"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "EF5236C33EEEC2E337296AB237F99F56A48639744788E128BC05275D4873B9F0FAFDA8FAF24F0A61C2903373F3DE3E459928CD6F2172EA6CDBE7B0FBF45D3DAD" }
{ "low" : 65472, "hi" : 65535, "bytes" : "29412152F2750DC2F951EC969B4E9587DCD2A23DAADCBC20677DDFE89096C883E65721FC8F7BFC2D0D1FD6143D8504CB7340E06FE324CE3445081D3B7B72F3B3" }
{ "low" : 65536, "hi" : 65599, "bytes" : "49BFE800381794D264028A2E32D318E7F6FD9B377ED3A12274CE21D40CCEF04D55791AF99849989C21D00E7D4E7B9FF4D46AABC44AED676B5C69CF32BE386205" }
{ "low" : 131008, "hi" : 131071, "bytes" : "C3E16260DD666D8D8FBF1529D0E8151A931663D75FA0046132E4AD78D8BE7F8D7F41AAEFDE58BA80B962B8B68762CDF3E4B06E05D73D22CC33F1E1592D5116F4" } ]
xor_digest = "10879B33D24115E4774C71711B563B67CCD891E3825EDB58E182EC92648AE51CDDC29A6A776C0AB3182DDDA1E180D55DFAB024A3121BE45ECA59FF1A3715434C"
f()
desc = "Set 6, vector# 2"
key = "<KEY>"
IV = "1F86ED54BB2289F0"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "8B354C8F8384D5591EA0FF23E7960472B494D04B2F787FC87B6569CB9021562FF5B1287A4D89FB316B69971E9B861A109CF9204572E3DE7EAB4991F4C7975427" }
{ "low" : 65472, "hi" : 65535, "bytes" : "B8B26382B081B45E135DF7F8C468ACEA56EB33EC38F292E3246F5A90233DDDC1CD977E0996641C3FA4BB42E7438EE04D8C275C57A69EEA872A440FC6EE39DB21" }
{ "low" : 65536, "hi" : 65599, "bytes" : "C0BA18C9F84D6A2E10D2CCCC041D736A943592BB626D2832A9A6CCC1005DDB9EA1694370FF15BD486B77629BB363C3B121811BCCFB18537502712A63061157D8" }
{ "low" : 131008, "hi" : 131071, "bytes" : "870355A6A03D4BC9038EA0CB2F4B8006B42D70914FBFF76A80D2567BE8404B03C1124BCE2FD863CE7438A5680D23C5E1F8ED3C8A6DB656BFF7B060B8A8966E09" } ]
xor_digest = "888FA87DB4EC690A180EF022AF6615F0677DB73B6A9E0CFACEBBB5B2A8816B2AD0338A812E03F4DFB26AF9D66160348CB9EE<KEY>2B6<KEY>8<KEY>81A2DB79<KEY>A3A68E"
f()
desc = "Set 6, vector# 3"
key = "<KEY>"
IV = "288FF6<KEY>9"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "71DAEE5142D0728B41B6597933EBF467E43279E30978677078941602629CBF68B73D6BD2C95F118D2B3E6EC955DABB6DC61C4143BC9A9B32B99DBE6866166DC0" }
{ "low" : 65472, "hi" : 65535, "bytes" : "906258725DDD0323D8E3098CBDAD6B7F941682A4745E4A42B3DC6EDEE565E6D9C65630610CDB14B5F110425F5A6DBF1870856183FA5B91FC177DFA721C5D6BF0" }
{ "low" : 65536, "hi" : 65599, "bytes" : "09033D9EBB07648F92858913E220FC528A10125919C891CCF8051153229B958BA9236CADF56A0F328707F7E9D5F76CCBCAF5E46A7BB9675655A426ED377D660E" }
{ "low" : 131008, "hi" : 131071, "bytes" : "F9876CA5B5136805445520CDA425508AE0E36DE975DE381F80E77D951D885801CEB354E4F45A2ED5F51DD61CE09942277F493452E0768B2624FACA4D9E0F7BE4" } ]
xor_digest = "0F4039E538DAB20139A4FEDCF07C00C45D81FD259D0C64A29799A6EE2FF2FA8B480A8A3CC7C7027A6CE0A197C44322955E4D4B00C94BF5B751E61B891F3FD906"
f()
console.log "exports.data = #{JSON.stringify out, null, 4};"
| true | # These test vectors can be found here:
#
# http://www.ecrypt.eu.org/stream/svn/viewcvs.cgi/ecrypt/trunk/submissions/salsa20/full/verified.test-vectors?logsort=rev&rev=210&view=markup"
#
# They specify keystreams for various inputs
#
out = []
f = () ->
out.push { desc, key, IV, stream, xor_digest }
desc = "Set 1, vector# 0"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "4DFA5E481DA23EA09A31022050859936DA52FCEE218005164F267CB65F5CFD7F2B4F97E0FF16924A52DF269515110A07F9E460BC65EF95DA58F740B7D1DBB0AA" }
{ "low" : 192, "hi" : 255, "bytes" : "DA9C1581F429E0A00F7D67E23B730676783B262E8EB43A25F55FB90B3E753AEF8C6713EC66C51881111593CCB3E8CB8F8DE124080501EEEB389C4BCB6977CF95" }
{ "low" : 256, "hi" : 319, "bytes" : "7D5789631EB4554400E1E025935DFA7B3E9039D61BDC58A8697D36815BF1985CEFDF7AE112E5BB81E37ECF0616CE7147FC08A93A367E08631F23C03B00A8DA2F" }
{ "low" : 448, "hi" : 511, "bytes" : "B375703739DACED4DD4059FD71C3C47FC2F9939670FAD4A46066ADCC6A5645783308B90FFB72BE04A6B147CBE38CC0C3B9267C296A92A7C69873F9F263BE9703" } ]
xor_digest = "F7A274D268316790A67EC058F45C0F2A067A99FCDE6236C0CEF8E056349FE54C5F13AC74D2539570FD34FEAB06C572053949B59585742181A5A760223AFA22D4"
f()
desc = "Set 1, vector# 9"
key = "PI:KEY:<KEY>END_PI"
IV = "0PI:KEY:<KEY>END_PI000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "0471076057830FB99202291177FBFE5D38C888944DF8917CAB82788B91B53D1CFB06D07A304B18BB763F888A61BB6B755CD58BEC9C4CFB7569CB91862E79C459" }
{ "low" : 192, "hi" : 255, "bytes" : "D1D7E97556426E6CFC21312AE38114259E5A6FB10DACBD88E4354B04725569352B6DA5ACAFACD5E266F9575C2ED8E6F2EFE4B4D36114C3A623DD49F4794F865B" }
{ "low" : 256, "hi" : 319, "bytes" : "AF06FAA82C73291231E1BD916A773DE152FD2126C40A10C3A6EB40F22834B8CC68BD5C6DBD7FC1EC8F34165C517C0B639DB0C60506D3606906B8463AA0D0EC2F" }
{ "low" : 448, "hi" : 511, "bytes" : "AB3216F1216379EFD5EC589510B8FD35014D0AA0B613040BAE63ECAB90A9AF79661F8DA2F853A5204B0F8E72E9D9EB4DBA5A4690E73A4D25F61EE7295215140C" } ]
xor_digest = "B76A7991D5EE58FC51B9035E077E1315D81F131FA1F26CF22005C6C4F2412243C401A850AFEFAADC5B052435B51177C70AE68CB9DF9B44681C2D8B7049D89333"
f()
desc = "Set 1, vector# 18"
key = "PI:KEY:<KEY>END_PI"
IV = "000PI:KEY:<KEY>END_PI00000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "BACFE4145E6D4182EA4A0F59D4076C7E83FFD17E7540E5B7DE70EEDDF9552006B291B214A43E127EED1DA1540F33716D83C3AD7D711CD03251B78B2568F2C844" }
{ "low" : 192, "hi" : 255, "bytes" : "56824347D03D9084ECCF358A0AE410B94F74AE7FAD9F73D2351E0A44DF1274343ADE372BDA2971189623FD1EAA4B723D76F5B9741A3DDC7E5B3E8ED4928EF421" }
{ "low" : 256, "hi" : 319, "bytes" : "999F4E0F54C62F9211D4B1F1B79B227AFB3116C9CF9ADB9715DE856A8EB3108471AB40DFBF47B71389EF64C20E1FFDCF018790BCE8E9FDC46527FE1545D3A6EA" }
{ "low" : 448, "hi" : 511, "bytes" : "76F1B87E93EB9FEFEC3AED69210FE4AB2ED577DECE01A75FD364CD1CD7DE10275A002DDBC494EE8350E8EEC1D8D6925EFD6FE7EA7F610512F1F0A83C8949AEB1" } ]
xor_digest = "B9D233247408CD459A027430A23E6FCF3E9A3BAF0D0FC59E623F04D9C107D402880620C64A111318ECE60C22737BECA421F7D3D004E7191ECE2C7075289B31BF"
f()
desc = "Set 1, vector# 27"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "24F4E317B675336E68A8E2A3A04CA967AB96512ACBA2F832015E9BE03F08830FCF32E93D14FFBD2C901E982831ED806221D7DC8C32BBC8E056F21BF9BDDC8020" }
{ "low" : 192, "hi" : 255, "bytes" : "E223DE7299E51C94623F8EAD3A6DB0454091EE2B54A498F98690D7D84DB7EFD5A2A8202435CAC1FB34C842AEECF643C63054C424FAC5A632502CD3146278498A" }
{ "low" : 256, "hi" : 319, "bytes" : "5A111014076A6D52E94C364BD7311B64411DE27872FC8641D92C9D811F2B518594935F959D064A9BE806FAD06517819D2321B248E1F37E108E3412CE93FA8970" }
{ "low" : 448, "hi" : 511, "bytes" : "8A9AB11BD5360D8C7F34887982B3F6586C34C1D6CB49100EA5D09A24C6B835D577C1A1C776902D785CB5516D74E8748079878FDFDDF0126B1867E762546E4D72" } ]
xor_digest = "0423874278AE11EF0A29B3E6E1A5BA41E43671636615E3F1F6215750E5A1749ACDFE0CEB74A11AC4862527C5849110C9A7A6F01E419372824BCAB90550340E81"
f()
desc = "Set 1, vector# 36"
key = "PI:KEY:<KEY>END_PI"
IV = "0PI:KEY:<KEY>END_PI0000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "9907DB5E2156427AD15B167BEB0AD445452478AFEE3CF71AE1ED8EAF43E001A1C8199AF9CFD88D2B782AA2F39845A26A7AC54E5BE15DB7BDFBF873E16BC05A1D" }
{ "low" : 192, "hi" : 255, "bytes" : "EBA0DCC03E9EB60AE1EE5EFE3647BE456E66733AA5D6353447981184A05F0F0CB0AD1CB630C35DC253DE3FEBD10684CADBA8B4B85E02B757DED0FEB1C31D71A3" }
{ "low" : 256, "hi" : 319, "bytes" : "BD24858A3DB0D9E552345A3C3ECC4C69BBAE4901016A944C0D7ECCAAB9027738975EEA6A4240D94DA183A74D649B789E24A0849E26DC367BDE4539ADCCF0CAD8" }
{ "low" : 448, "hi" : 511, "bytes" : "EE20675194FA404F54BAB7103F6821C137EE2347560DC31D338B01026AB6E57165467215315F06360D85F3C5FE7A359E80CBFE735F75AA065BC18EFB2829457D" } ]
xor_digest = "19B8E721CD10577375FC6D0E6DC39B054E371860CE2AA310906EA7BAB28D737F2357B42E7DC1C48D597EA58B87602CE5C37EEDED2E0F4819938878AE7C50E151"
f()
desc = "Set 1, vector# 45"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "A59CE982636F2C8C912B1E8105E2577D9C86861E61FA3BFF757D74CB9EDE6027D7D6DE775643FAF5F2C04971BDCB56E6BE8144366235AC5E01C1EDF8512AF78B" }
{ "low" : 192, "hi" : 255, "bytes" : "DF8F13F1059E54DEF681CD554439BAB724CDE604BE5B77D85D2829B3EB137F4F2466BEADF4D5D54BA4DC36F1254BEC4FB2B367A59EA6DDAC005354949D573E68" }
{ "low" : 256, "hi" : 319, "bytes" : "B3F542ECBAD4ACA0A95B31D281B930E8021993DF5012E48A333316E712C4E19B58231AAE7C90C91C9CC135B12B490BE42CF9C9A2727621CA81B2C3A081716F76" }
{ "low" : 448, "hi" : 511, "bytes" : "F64A6449F2F13030BE554DB00D24CD50A89F80CCFE97435EBF0C49EB08747BF7B2C89BE612629F231C1B3398D8B4CC3F35DBECD1CF1CFDFDECD481B72A51276A" } ]
xor_digest = "4134A74A52EA89BF22E05A467E37E08215537896BE4D2BBDF29EA52A2303E64BD954A18928543C82B68A21E4B830A775CBA9D1176EBF8DB92938DF6E59117B74"
f()
desc = "Set 1, vector# 54"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "7A8131B777F7FBFD33A06E396FF32D7D8C3CEEE9573F405F98BD6083FE57BAB6FC87D5F34522D2440F649741D9F87849BC8751EF432DEE5DCC6A88B34B6A1EA9" }
{ "low" : 192, "hi" : 255, "bytes" : "6573F813310565DB22219984E09194459E5BB8613237F012EBB8249666582ACA751ED59380199117DDB29A5298F95FF065D271AB66CF6BC6CDE0EA5FC4D304EB" }
{ "low" : 256, "hi" : 319, "bytes" : "0E65CB6944AFBD84F5B5D00F307402B8399BF02852ED2826EA9AA4A55FB56DF2A6B83F7F228947DFAB2E0B10EAAA09D75A34F165ECB4D06CE6AB4796ABA3206A" }
{ "low" : 448, "hi" : 511, "bytes" : "11F69B4D034B1D7213B9560FAE89FF2A53D9D0C9EAFCAA7F27E9D119DEEEA299AC8EC0EA0529846DAF90CF1D9BFBE406043FE03F1713F249084BDD32FD98CD72" } ]
xor_digest = "E9CFBD15B5F4AD02903851F46728F2DD5910273E7360F1571EF1442199143B6C28E5368A2E00E08ADAE73AF3489E0D6F0D8032984ADD139B6BF508A5EEE4434B"
f()
desc = "Set 1, vector# 63"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "FE4DF972E982735FFAEC4D66F929403F7246FB5B2794118493DF068CD310DEB63EEEF12344E221A2D163CC666F5685B502F4883142FA867B0BA46BF17D011984" }
{ "low" : 192, "hi" : 255, "bytes" : "4694F79AB2F3877BD590BA09B413F1BDF394C4D8F2C20F551AA5A07207433204C2BC3A3BA014886A08F4EC5E4D91CDD01D7A039C5B815754198B2DBCE68D25EA" }
{ "low" : 256, "hi" : 319, "bytes" : "D1340204FB4544EFD5DAF28EDCC6FF03B39FBEE708CAEF6ABD3E2E3AB5738B3204EF38CACCC40B9FBD1E6F0206A2B564E2F9EA05E10B6DD061F6AB94374681C0" }
{ "low" : 448, "hi" : 511, "bytes" : "BB802FB53E11AFDC3104044D7044807941FDAEF1042E0D35972D80CE77B4D560083EB4113CDBC4AC56014D7FF94291DC9387CEF74A0E165042BC12373C6E020C" } ]
xor_digest = "FF021AEC5DC82F40BBF44CEA85287BCFD70F16F557F07B1BF970407051F71C415B703A67CAF8E81CB22D9F09E0CBD2475E9859355A48FDA9F48E38E2748BE41B"
f()
desc = "Set 1, vector# 72"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "8F8121BDD7B286465F03D64CA45A4A154BDF44560419A40E0B482CED194C4B324F2E9295C452B73B292BA7F55A692DEEA5129A49167BA7AABBEED26E39B25E7A" }
{ "low" : 192, "hi" : 255, "bytes" : "7E4388EDBBA6EC5882E9CBF01CFA67860F10F0A5109FCA7E865C3814EB007CC89585C2653BDCE30F667CF95A2AA425D35A531F558180EF3E32A9543AE50E8FD6" }
{ "low" : 256, "hi" : 319, "bytes" : "527FF72879B1B809C027DFB7B39D02B304D648CD8D70F4E0465615B334ED9E2D59703745467F1168A8033BA861841DC00E7E1AB5E96469F6DA01B8973D0D414A" }
{ "low" : 448, "hi" : 511, "bytes" : "82653E0949A5D8E32C4D0A81BBF96F6A7249D4D1E0DCDCC72B90565D9AF4D0AC461C1EAC85E254DD5E567A009EEB38979A2FD1E4F32FAD15D177D766932190E1" } ]
xor_digest = "B2F239692CE50EECABD7A846AC33388543CFC1061F33420B6F205809F3965D899C56C02D208DD3E9A1F0D5BBED8F5DACB164FD005DF907002302F40ADB6665CC"
f()
desc = "Set 1, vector# 81"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "52FA8BD042682CD5AA21188EBF3B9E4AEE3BE38AE052C5B37730E52C6CEE33C91B492F95A67F2F6C15425A8623C0C2AE7275FFD0FCF13A0A293A784289BEACB4" }
{ "low" : 192, "hi" : 255, "bytes" : "5F43C508BA6F728D032841618F96B10319B094027E7719C28A8A8637D4B0C4D225D602EA23B40D1541A3F8487F25B14A8CBD8D2001AC28EADFDC0325BA2C140E" }
{ "low" : 256, "hi" : 319, "bytes" : "5C802C813FF09CAF632CA8832479F891FB1016F2F44EFA81B3C872E37468B8183EB32D8BD8917A858AEF47524FCC05D3688C551FC8A42C8D9F0509018706E40E" }
{ "low" : 448, "hi" : 511, "bytes" : "4CDD40DC6E9C0E4F84810ABE712003F64B23C6D0C88E61D1F303C3BBD89B58AA098B44B5CD82EDCFC618D324A41317AC6FED20C9A0C54A9ED1F4DA3BF2EC3C66" } ]
xor_digest = "B72D2FEE4BFBC0F65005EE2797B0608A7A6D9CD1114B67C0ADEC7B4B6D793182880777B0279E3DF27CBA820714629A96034E4C71F5356254A0116CF3E9F7EF5C"
f()
desc = "Set 1, vector# 90"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "6262315C736E88717E9627EECF4F6B55BD10D5960A9961D572EFC7CBDB9A1F011733D3E17E4735BEFA16FE6B148F86614C1E37065A48ACF287FFE65C9DC44A58" }
{ "low" : 192, "hi" : 255, "bytes" : "B43439584FB2FAF3B2937838D8000AC4CD4BC4E582212A7741A0192F71C1F11B58D7F779CA0E6E4B8BD58E00B50C3C53DAF843467064A2DBE2FAD6FF6F40ECD8" }
{ "low" : 256, "hi" : 319, "bytes" : "EE51EE875F6F1B8AF0334F509DF5692B9B43CC63A586C2380AF3AE490DCD6CFF7907BC3724AE3BBEAD79D436E6DADDB22141B3BA46C9BEC0E01B9D4F7657B387" }
{ "low" : 448, "hi" : 511, "bytes" : "E5A4FE4A2FCA9A9ED779A9574283DC21C85216D54486D9B182300D0593B1E2B010814F7066AEB955C057609CE9AF0D63F057E17B19F57FFB7287EB2067C43B8D" } ]
xor_digest = "8866D8F9E6F423A7DF10C77625014AA582C06CD861A88F40FB9CD1EBF09111884344BEEA5A724E6FD8DB98BF4E6B9BEA5318FA62813D1B49A2D529FC00CB5777"
f()
desc = "Set 1, vector# 99"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "82FD629BD82C3BE22910951E2E41F8FE187E2BD198F6113AFF44B9B0689AA520C8CCE4E8D3FBA69EDE748BCF18397214F98D7ACF4424866A8670E98EBAB715A3" }
{ "low" : 192, "hi" : 255, "bytes" : "342D80E30E2FE7A00B02FC62F7090CDDECBDFD283D42A00423113196A87BEFD8B9E8AAF61C93F73CC6CBE9CC5AEC182F3948B7857F96B017F3477A2EEC3AEB3B" }
{ "low" : 256, "hi" : 319, "bytes" : "8233712B6D3CCB572474BE200D67E5403FC62128D74CE5F790202C696BFFB7EE3CAD255324F87291273A7719278FA3131ABA12342692A2C0C58D27BA3725761B" }
{ "low" : 448, "hi" : 511, "bytes" : "782600E7357AC69EA158C725B3E1E94051A0CB63D0D1B4B3DF5F5037E3E1DE45850578E9D513B90B8E5882D4DCA9F42BE32621F4DCC1C77B38F1B0AC1227C196" } ]
xor_digest = "F8AE82F9B77EF090AE0C72A5EAE2140568BEF0B354BCDF4BD39732CD86C63A82AFD27F58C459272B3E8A4B9B558D856F8475CF3A1AD99074822A836CFE520DC5"
f()
desc = "Set 1, vector#108"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "D244F87EB315A7EEF02CA314B440777EC6C44660020B43189693500F3279FA017257BE0AB087B81F85FD55AAC5845189C66E259B5412C4BDFD0EBE805FC70C8A" }
{ "low" : 192, "hi" : 255, "bytes" : "5A2D8D3E431FB40E60856F05C797620642B35DAB0255764D986740699040702F6CDE058458E842CB6E1843EBD336D37423833EC01DFFF9086FEECAB8A165D29F" }
{ "low" : 256, "hi" : 319, "bytes" : "443CEF4570C83517ED55C2F57058BB70294CC8D7342597E2CD850F6C02E355CAEB43C0A41F4BB74FFE9F6B0D25799140D03792D667601AD7954D21BD7C174C43" }
{ "low" : 448, "hi" : 511, "bytes" : "959C8B16A0ADEC58B544BE33CCF03277E48C7916E333F549CDE16E2B4B6DCE2D8D76C50718C0E77BFBEB3A3CB3CA14BF40F65EBFAE1A5001EAB36E531414E87F" } ]
xor_digest = "4DC82B00DC54141CC890348496115C681DB10ABE8454FBD10B49EF951CD20C6F7FE8AAA10906E57CF05PI:KEY:<KEY>END_PI838PI:KEY:<KEY>END_PI76C8B7A3F9E6BD6D21C49F1590C913026C71A3E"
f()
desc = "Set 1, vector#117"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "44A74D35E73A7E7C37B009AE712783AC86ACE0C02CB175656AF79023D91C909ED2CB2F5C94BF8593DDC5E054D7EB726E0E867572AF954F88E05A4DAFD00CCF0A" }
{ "low" : 192, "hi" : 255, "bytes" : "FEC113A0255391D48A37CDF607AE122686305DDAD4CF1294598F2336AB6A5A029D927393454C2E014868137688C0417A2D31D0FE9540D7246FE2F84D6052DE40" }
{ "low" : 256, "hi" : 319, "bytes" : "79C2F7431D69E54C0474D8160113F3648156A8963817C34AC9A9AD222543666E7EAF03AF4EE03271C3ECED262E7B4C66B0F618BAF3395423274DD1F73E2675E3" }
{ "low" : 448, "hi" : 511, "bytes" : "75C1295C871B1100F27DAF19E5D5BF8D880B9A54CEFDF1561B4351A32898F3C26A04AB1149C24FBFA2AC963388E64C4365D716BCE8330BC03FA178DBE5C1E6B0" } ]
xor_digest = "65D58F845F973928ADF5803799901856A08952CF215154C52A5FF2DAD71E8B703DE107E5531491666353F323E790EB021B5EF66C13F43401F4F6A27F08CE11D5"
f()
desc = "Set 1, vector#126"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "E23A3638C836B1ACF7E27296E1F5A2413C4CC351EFEF65E3672E7C2FCD1FA1052D2C26778DB774B8FBA29ABED72D058EE35EBA376BA5BC3D84F8E44ABD5DC2CC" }
{ "low" : 192, "hi" : 255, "bytes" : "2A8BEB3C372A6570F54EB429FA7F562D6EF14DF725861EDCE8132620EAA00D8B1DFEF653B64E9C328930904A0EEB0132B277BB3D9888431E1F28CDB0238DE685" }
{ "low" : 256, "hi" : 319, "bytes" : "CCBEB5CA57104B95BF7BA5B12C8B85534CE9548F628CF53EF02C337D788BCE71D2D3D9C355E7D5EB75C56D079CB7D99D6AF0C8A86024B3AF5C2FC8A028413D93" }
{ "low" : 448, "hi" : 511, "bytes" : "D00A5FDCE01A334C37E75634A8037B49BEC06ACBD2243320E2CA41FB5619E6D875AB2007310D4149379C91EF4E199805BE261E5C744F0DF21737E01243B7116F" } ]
xor_digest = "2D72232A4485E0D2EEDC0619396020774C100C5424FF742B2868E3A68E67E1654C4711C54A34DA937359A26B8386AD2039EB2021DCFBB6A11603AF56225DE098"
f()
desc = "Set 2, vector# 0"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "6513ADAECFEB124C1CBE6BDAEF690B4FFB00B0FCACE33CE806792BB41480199834BFB1CFDD095802C6E95E251002989AC22AE588D32AE79320D9BD7732E00338" }
{ "low" : 192, "hi" : 255, "bytes" : "75E9D0493CA05D2820408719AFC75120692040118F76B8328AC279530D84667065E735C52ADD4BCFE07C9D93C00917902B187D46A25924767F91A6B29C961859" }
{ "low" : 256, "hi" : 319, "bytes" : "0E47D68F845B3D31E8B47F3BEA660E2ECA484C82F5E3AE00484D87410A1772D0FA3B88F8024C170B21E50E0989E94A2669C91973B3AE5781D305D8122791DA4C" }
{ "low" : 448, "hi" : 511, "bytes" : "CCBA51D3DB400E7EB780C0CCBD3D2B5BB9AAD82A75A1F746824EE5B9DAF7B7947A4B808DF48CE94830F6C9146860611DA649E735ED5ED6E3E3DFF7C218879D63" } ]
xor_digest = "6D3937FFA13637648E477623277644ADAD3854E6B2B3E4D68155356F68B30490842B2AEA2E32239BE84E613C6CE1B9BD026094962CB1A6757AF5A13DDAF8252C"
f()
desc = "Set 2, vector# 9"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "169060CCB42BEA7BEE4D8012A02F3635EB7BCA12859FA159CD559094B3507DB801735D1A1300102A9C9415546829CBD2021BA217B39B81D89C55B13D0C603359" }
{ "low" : 192, "hi" : 255, "bytes" : "23EF24BB24195B9FD574823CD8A40C29D86BD35C191E2038779FF696C712B6D82E7014DBE1AC5D527AF076C088C4A8D44317958189F6EF54933A7E0816B5B916" }
{ "low" : 256, "hi" : 319, "bytes" : "D8F12ED8AFE9422B85E5CC9B8ADEC9D6CFABE8DBC1082BCCC02F5A7266AA074CA284E583A35837798CC0E69D4CE937653B8CDD65CE414B89138615CCB165AD19" }
{ "low" : 448, "hi" : 511, "bytes" : "F70A0FF4ECD155E0F033604693A51E2363880E2ECF98699E7174AF7C2C6B0FC659AE329599A3949272A37B9B2183A0910922A3F325AE124DCBDD735364055CEB" } ]
xor_digest = "30209DD68D46E5A30034EF6DCE74FE1AB6C772AB22CD3D6C354A9C4607EF3F82900423D29FB65E07FFA3PI:KEY:<KEY>END_PIAD94E940D6E52E305A10D60936D34BD03B3F342AB1"
f()
desc = "Set 2, vector# 18"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "05835754A1333770BBA8262F8A84D0FD70ABF58CDB83A54172B0C07B6CCA5641060E3097D2B19F82E918CB697D0F347DC7DAE05C14355D09B61B47298FE89AEB" }
{ "low" : 192, "hi" : 255, "bytes" : "5525C22F425949A5E51A4EAFA18F62C6E01A27EF78D79B073AEBEC436EC8183BC683CD3205CF80B795181DAFF3DC98486644C6310F09D865A7A75EE6D5105F92" }
{ "low" : 256, "hi" : 319, "bytes" : "2EE7A4F9C576EADE7EE325334212196CB7A61D6FA693238E6E2C8B53B900FF1A133A6E53F58AC89D6A695594CE03F7758DF9ABE981F23373B3680C7A4AD82680" }
{ "low" : 448, "hi" : 511, "bytes" : "CB7A0595F3A1B755E9070E8D3BACCF9574F881E4B9D91558E19317C4C254988F42184584E5538C63D964F8EF61D86B09D983998979BA3F44BAF527128D3E5393" } ]
xor_digest = "AD29013FD0A222EEBE65126380A26477BD86751B3B0A2B4922602E63E6ECDA523BA789633BEE6CFF64436A8644CCD7E8F81B062187A9595A8D2507ED774FA5CD"
f()
desc = "Set 2, vector# 27"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "72A8D26F2DF3B6713C2A053B3354DBA6C10743C7A8F19261CF0E7957905748DDD6D3333E2CBC6611B68C458D5CDBA2A230AC5AB03D59E71FE9C993E7B8E7E09F" }
{ "low" : 192, "hi" : 255, "bytes" : "7B6132DC5E2990B0049A5F7F357C9D997733948018AE1D4F9DB999F4605FD78CB548D75AC4657D93A20AA451B8F35E0A3CD08880CCED7D4A508BA7FB49737C17" }
{ "low" : 256, "hi" : 319, "bytes" : "EF7A7448D019C76ED0B9C18B5B2867CF9AD84B789FB037E6B107B0A4615737B5C1C113F91462CDA0BCB9ADDC09E8EA6B99E4835FED25F5CC423EEFF56D851838" }
{ "low" : 448, "hi" : 511, "bytes" : "6B75BDD0EC8D581CB7567426F0B92C9BB5057A89C3F604583DB700A46D6B8DE41AF315AE99BB5C1B52C76272D1E262F9FC7022CE70B435C27AE443284F5F84C1" } ]
xor_digest = "484F9FCB516547DD89AF46991B18F1DEC4C6CBC7D52735E00FC3201B4650151C3D4FB9C119442B368B28E3C68ED83F10D9DA2FDED7DEB8F04827FA91CCDBF65B"
f()
desc = "Set 2, vector# 36"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "76240D13C7E59CBD4183D162834A5D3637CD09EE4F5AFE9C28CFA9466A4089F65C80C224A87F956459B173D720274D09C573FCD128498D810460FDA1BB50F934" }
{ "low" : 192, "hi" : 255, "bytes" : "71AF115217F3B7F77A05B56E32AD0889BFA470B6DDC256D852C63B45688D7BC8DC610D347A2600D7769C67B28D1FA25F1AACFB8F9BB68BFE17357335D8FAC993" }
{ "low" : 256, "hi" : 319, "bytes" : "6573CC1ADC0DE744F6694E5FBB59E5BF5939CE5D13793E2F683C7F2C7DD9A460575746688A0F17D419FE3E5F886545597B6705E1390542B4F953D568025F5BB3" }
{ "low" : 448, "hi" : 511, "bytes" : "809179FAD4AD9B5C355A09E99C8BE9314B9DF269F162C1317206EB3580CAE58AB93A408C23739EF9538730FE687C8DAC1CE95290BA4ACBC886153E63A613857B" } ]
xor_digest = "D1781DCE3EFB8B13740F016264051354F323C81A13D42CE75E67180849AC49FFA7EA95720696F86848A1A4B8506A95E3A61371DDE7F21167CC147173BFC4D78F"
f()
desc = "Set 2, vector# 45"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "3117FD618A1E7821EA08CDED410C8A67BDD8F7BE3FCA9649BD3E297FD83A80AD814C8904C9D7A2DC0DCAA641CFFF502D78AFF1832D34C263C1938C1ADF01238F" }
{ "low" : 192, "hi" : 255, "bytes" : "1E8CB540F19EC7AFCB366A25F74C0004B682E06129030617527BECD16E3E3E0027D818F035EDCDF56D8D4752AEF28BDBFA0D3B008235173475F5FA105B91BEED" }
{ "low" : 256, "hi" : 319, "bytes" : "637C3B4566BBEBBE703E4BF1C978CCD277AE3B8768DB97DF01983CDF3529B3EC6B1137CA6F231047C13EA38649D0058EBE5EF7B7BBA140F22338E382F1D6AB3F" }
{ "low" : 448, "hi" : 511, "bytes" : "D407259B6355C343D64A5130DA55C057E4AF722B70AC8A074262233677A457AFEAA34E7FD6F15959A4C781C4C978F7B3BC571BF66674F015A1EA5DB262E25BDC" } ]
xor_digest = "1F64F78101768FF5067B9A918444EF703FF06561E23B31C61BD43BCF86CFAD249942F73DC8F40AE49B14874B08F2A527A53DF496F37D067F1168268D4A134740"
f()
desc = "Set 2, vector# 54"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "7FED83B9283449AD8EBFC935F5F364075C9008ADE8626D350770E2DBD058F053F7E5300B088B1341EC54C2BEE72A520C35C673E79CC4ED0A6D8F4C15FBDD090B" }
{ "low" : 192, "hi" : 255, "bytes" : "D780206A2537106610D1C95BF7E9121BEDE1F0B8DFBE83CBC49C2C653DD187F7D84A2F4607BF99A96B3B84FB792340D4E67202FB74EC24F38955F345F21CF3DB" }
{ "low" : 256, "hi" : 319, "bytes" : "6CA21C5DC289674C13CFD4FCBDEA83560A90F53BB54F16DBF274F5CC56D7857CD3E3B06C81C70C828DC30DADEBD92F38BB8C24136F37797A647584BCEE68DF91" }
{ "low" : 448, "hi" : 511, "bytes" : "471936CE9C84E131C4C5792B769654B89644BFAFB1149130E580FD805A325B628CDE5FAE0F5C7CFFEF0D931F8F517A929E892D3789B74217A81BAEFE441E47ED" } ]
xor_digest = "0073DA29855E96EA5C414B9BD2E1C0F4987D3F1EB1CA73C4AA10180B99A437744857EB36586593B81088AADE5D89BBC68FBD8B0D268080746D6BE38DBC9396CD"
f()
desc = "Set 2, vector# 63"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "C224F33B124D6692263733DFD5BF52717D1FB45EC1CEDCA6BF92BA44C1EADA85F7B031BCC581A890FD275085C7AD1C3D652BCA5F4D7597DECDB2232318EABC32" }
{ "low" : 192, "hi" : 255, "bytes" : "090325F54C0350AD446C19ABDCAEFF52EC57F5A13FB55FEDE4606CEC44EC658BBB13163481D2C84BF9409313F6470A0DA9803936094CC29A8DE7613CBFA77DD5" }
{ "low" : 256, "hi" : 319, "bytes" : "1F66F5B70B9D12BC7092C1846498A2A0730AA8FA8DD97A757BBB878320CE6633E5BCC3A5090F3F75BE6E72DD1E8D95B0DE7DBFDD764E484E1FB854B68A7111C6" }
{ "low" : 448, "hi" : 511, "bytes" : "F8AE560041414BE888C7B5EB3082CC7C4DFBBA5FD103F522FBD95A7166B91DE6C78FB47413576EC83F0EDE6338C9EDDB81757B58C45CBD3A3E29E491DB1F04E2" } ]
xor_digest = "542B2672401C5D1225CC704365753E33D0827A863C4897FFCE1B724CD10B2A0E8A4E4CDAB7357424FC6DC78440037240B8FD5299907A946CE77DAFA5322AB73D"
f()
desc = "Set 2, vector# 72"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "11BF31E22D7458C189092A1DE3A4905BA2FA36858907E3511FB63FDFF2C5C2A15B651B2C2F1A3A43A7186421528069672B6BB0AEC10452F1DAA9FC73FF5A396A" }
{ "low" : 192, "hi" : 255, "bytes" : "D1E1619E4BD327D2A124FC52BC15B1940B05394ECE5926E1E1ADE7D3FC8C6E91E43889F6F9C1FD5C094F6CA25025AE4CCC4FDC1824936373DBEE16D62B81112D" }
{ "low" : 256, "hi" : 319, "bytes" : "F900E9B0665F84C939D5FE4946FA7B41E34F06058522A2DB49E210E3E5385E5897C24F6350C6CCA578285325CC16F5586DC662FFBEA41BAC68996BAAB9F32D1F" }
{ "low" : 448, "hi" : 511, "bytes" : "40587ECAD15841F1BD1D236A61051574A974E15292F777ABDED64D2B761892BEF3DD69E479DE0D02CC73AF76E81E8A77F3CEE74180CB5685ACD4F0039DFFC3B0" } ]
xor_digest = "C3E5CC5C7CEA1B3885EB9CEF2D1FAF18E7DE1CFD7237F2D6D344F3DF7168A88EC88C1314CB6F5A3EAE1BC468B4FAD75E8A42BE8607705C9A7950302461AD9B3F"
f()
desc = "Set 2, vector# 81"
key = "PI:KEY:<KEY>END_PI"
IV = "PI:KEY:<KEY>END_PI0000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "EBC464423EADEF13E845C595A9795A585064F478A1C8582F07A4BA68E81329CB26A13C2EA0EFE9094B0A749FDB1CC6F9C2D293F0B395E14EB63075A39A2EDB4C" }
{ "low" : 192, "hi" : 255, "bytes" : "F4BBBBCE9C5869DE6BAF5FD4AE835DBE5B7F1752B2972086F3383E9D180C2FE55618846B10EB68AC0EB0865E0B167C6D3A843B29336BC1100A4AB7E8A3369959" }
{ "low" : 256, "hi" : 319, "bytes" : "3CEB39E3D740771BD49002EA8CD998518A8C70772679ECAF2030583AED43F77F565FECDBEF333265A2E1CC42CB606980AEF3B24C436A12C85CBDC5EBD97A9177" }
{ "low" : 448, "hi" : 511, "bytes" : "EF651A98A98C4C2B61EA8E7A673F5D4FD832D1F9FD19EE4537B6FEC7D11C6B2F3EF5D764EEAD396A7A2E32662647BFC07F02A557BA6EF046C8DE3781D74332B0" } ]
xor_digest = "88A96FF895BF2A827FC26DB2BB75DC698E8E1B7E231997AB2942E981EF1633EA061F6B323B99519828FB41A6F5CCC79C57PI:KEY:<KEY>END_PI6DDDD34DEAB38PI:KEY:<KEY>END_PI14A54C4886626E5"
f()
desc = "Set 2, vector# 90"
key = "PI:KEY:<KEY>END_PI"
IV = "0PI:KEY:<KEY>END_PI0000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "F40253BAA835152E1582646FD5BD3FED638EB3498C80BFB941644A7750BBA5653130CC97A937A2B27AFBB3E679BC42BE87F83723DC6F0D61DCE9DE8608AC62AA" }
{ "low" : 192, "hi" : 255, "bytes" : "A5A1CD35A230ED57ADB8FE16CD2D2EA6055C32D3E621A0FD6EB6717AA916D47857CD987C16E6112EDE60CCB0F70146422788017A6812202362691FDA257E5856" }
{ "low" : 256, "hi" : 319, "bytes" : "81F0D04A929DB4676F6A3E6C15049779C4EC9A12ACF80168D7E9AA1D6FA9C13EF2956CEE750A89103B48F22C06439C5CE9129996455FAE2D7775A1D8D39B00CE" }
{ "low" : 448, "hi" : 511, "bytes" : "3F6D60A0951F0747B94E4DDE3CA4ED4C96694B7534CD9ED97B96FAAD3CF00D4AEF12919D410CD9777CD5F2F3F2BF160EBBA3561CC24345D9A09978C3253F6DCB" } ]
xor_digest = "554F89BF1AD5602655B800DB9B3CCFFA1B267D57654DCF3FDDA81A59DF68B022555E63DE51E7A83668E7F1AE09EEB5B8748DEF8580B304199C4D117CF9A94E78"
f()
desc = "Set 2, vector# 99"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "ED5FF13649F7D8EDFC783EFDF2F843B368776B19390AF110BEF12EAC8EC58A2E8CDAB6EC9049FBDA23A615C536C3A313799E21668C248EC864D5D5D99DED80B3" }
{ "low" : 192, "hi" : 255, "bytes" : "845ACE9B870CF9D77597201988552DE53FD40D2C8AC51ABE1335F6A2D0035DF8B10CACAD851E000BAC6EA8831B2FBCFEB7C94787E41CC541BAC3D9D26DB4F19D" }
{ "low" : 256, "hi" : 319, "bytes" : "981580764B81A4E12CA1F36634B591365E4BDB6C12DE13F2F337E72E018029C5A0BECDA7B6723DD609D81A314CE396190E82848893E5A44478B08340F90A73F3" }
{ "low" : 448, "hi" : 511, "bytes" : "4CD3B072D5720E6C64C9476552D1CFF4D4EF68DCBD11E8D516F0C248F9250B571990DD3AFC0AE8452896CCCC0BD0EFDF17B616691AB3DF9AF6A42EDCA54BF9CD" } ]
xor_digest = "52D590BB5E396FCC2E00D9C51B3C0BF073E123C7EE69B528B0F0F87B57DC6907F4B57FD5F5B10D602B1F723E9FDD5510AEC60CD0DD50ED4B60FA355859638C2C"
f()
desc = "Set 2, vector#108"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "78ED06021C5C7867D176DA2A96C4BBAA494F451F21875446393E9688205ED63DEA8ADEB1A2381201F576C5A541BC88874078608CA8F2C2A6BDCDC1081DD254CC" }
{ "low" : 192, "hi" : 255, "bytes" : "C1747F85DB1E4FB3E29621015314E3CB261808FA6485E59057B60BE82851CFC948966763AF97CB9869567B763C7454575022249DFE729BD5DEF41E6DBCC68128" }
{ "low" : 256, "hi" : 319, "bytes" : "1EE4C7F63AF666D8EDB2564268ECD127B4D015CB59487FEAF87D0941D42D0F8A24BD353D4EF765FCCF07A3C3ACF71B90E03E8AEA9C3F467FE2DD36CEC00E5271" }
{ "low" : 448, "hi" : 511, "bytes" : "7AFF4F3A284CC39E5EAF07BA6341F065671147CA0F073CEF2B992A7E21690C8271639ED678D6A675EBDAD4833658421315A2BA74754467CCCE128CCC62668D0D" } ]
xor_digest = "FB3FE601D4E58B0766F02FA15C3323913CD745E905AD74EA5DABA77BC25D282DD66D98204E101F06D60BA446A21331AF6DDEB70679DEF46B886EB8PI:KEY:<KEY>END_PI"
f()
desc = "Set 2, vector#117"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "D935C93A8EBB90DB53A27BF9B41B334523E1DFDE3BFFC09EA97EFB9376D38C7D6DC67AAB21EA3A5C07B6503F986F7E8D9E11B3150BF0D38F36C284ADB31FACF8" }
{ "low" : 192, "hi" : 255, "bytes" : "DA88C48115010D3CD5DC0640DED2E6520399AAFED73E573CBAF552C6FE06B1B3F3ADE3ADC19DA311B675A6D83FD48E3846825BD36EB88001AE1BD69439A0141C" }
{ "low" : 256, "hi" : 319, "bytes" : "14EA210224DAF4FC5D647C78B6BFEF7D724DC56DCDF832B496DEAD31DD948DB1944E17AB2966973FD7CCB1BC9EC0335F35326D5834EE3B08833358C4C28F70DE" }
{ "low" : 448, "hi" : 511, "bytes" : "D5346E161C083E00E247414F44E0E7375B435F426B58D482A37694331D7C5DC97D8953E6A852625282973ECCFD012D664C0AFA5D481A59D7688FDB54C55CD04F" } ]
xor_digest = "BB5EAC1AB84C70857245294309C023C4B1A4199D16877BC847BCBB1B0A8D1B544289D6C8BF27212AAFFD42021669BB2477A4F815FA01B3F7E88299240155265B"
f()
desc = "Set 2, vector#126"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "45A43A587C45607441CE3AE20046797788879C5B77FDB90B76F7D2DF27EE8D9428A5B5AF35E2AAE242E6577BEC92DA0929A6AFB3CB8F8496375C98085460AB95" }
{ "low" : 192, "hi" : 255, "bytes" : "14AE0BA973AE19E6FD674413C276AB9D99AA0048822AFB6F0B68A2741FB5CE2F64F3D862106EF2BDE19B39209F75B92BDBE9015D63FDFD7B9E8A776291F4E831" }
{ "low" : 256, "hi" : 319, "bytes" : "C26FA1812FFC32EFF2954592A0E1E5B126D5A2196624156E3DFD0481205B24D5613B0A75AF3CBC8BBE5911BE93125BD3D3C50C92910DBA05D80666632E5DF9EF" }
{ "low" : 448, "hi" : 511, "bytes" : "AD0DABE5AF74AB4F62B4699E0D667BBF01B4DCF0A45514554CAC4DFDE453EFF1E51BE5B74B37512C40E3608FB0E65A3FD4EAFA27A3BB0D6E1300C594CB0D1254" } ]
xor_digest = "0F1A4B0994EE03B6C381FE4BB8E33C0EE47C395BB59922C5537EEBFD125494220F743B93D867085E027E56623F79505608179A39FF52D4C00A45A5FB8F618C49"
f()
desc = "Set 2, vector#135"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "09E15E82DFA9D821B8F68789978D094048892C624167BA88AD767CAEFDE80E25F57467156B8054C8E88F3478A2897A20344C4B05665E7438AD1836BE86A07B83" }
{ "low" : 192, "hi" : 255, "bytes" : "2D752E53C3FCA8D3CC4E760595D588A6B321F910B8F96459DBD42C663506324660A527C66A53B406709262B0E42F11CB0AD2450A1FB2F48EA85C1B39D4408DB9" }
{ "low" : 256, "hi" : 319, "bytes" : "1EC94A21BD2C0408D3E15104FA25D15D6E3E0D3F8070D84184D35B6302BF62AEA282E3640820CC09E1528B684B7400180598D6960EC92E4EC4C9E533E1BA06F1" }
{ "low" : 448, "hi" : 511, "bytes" : "D0AC302C5CC256351E24CFFD11F0BD8A0BE1277EDDCB3EE4D530E051712A710DF4513FD6438B7A355CCF4FEDA9A60F2AC375508F998C642E6C51724FE9462F7F" } ]
xor_digest = "B7F32B6FADB48BB8DA231BDBDC4697232BAE5F8F8345F9F14A991FF851CC3C641DF4913A5C550FC898F95AC299ED89155A434DC4B1E37D82EA137BB763F68BC7"
f()
desc = "Set 2, vector#144"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "EA869D49E7C75E07B551C24EBE351B4E7FD9CB26413E55A8A977B766650F81EFCA06E30107F76DC97EA9147FFA7CA66AFD4D4DA538CDA1C27E8D948CC406FB89" }
{ "low" : 192, "hi" : 255, "bytes" : "436A8EC10421116CD03BF95A4DAAE6301BB8C724B3D481099C70B26109971CCEACBCE35C8EE98BBB0CD553B5C418112500262C7EA10FAAC8BA9A30A04222D8E2" }
{ "low" : 256, "hi" : 319, "bytes" : "47487A34DE325E79838475B1757D5D293C931F9E57579FCA5E04A40E4A0A38CFD1614F9CEF75F024FFF5D972BD671DC9FB2A80F64E8A2D82C3BAA5DDFD1E6821" }
{ "low" : 448, "hi" : 511, "bytes" : "3FDCAD4E7B069391FAB74C836D58DE2395B27FFAE47D633912AE97E7E3E60264CA0DC540D33122320311C5CFC9E26D632753AC45B6A8E81AC816F5CA3BBDB1D6" } ]
xor_digest = "E30E770C75C94EE022BEA6B95241E5D7163D7C55AAF20FE7150768CEE6E1103742902FA4F928CDCF31335944DCDEBADDE36FE089D2EB93677E9DF75234E1B3C8"
f()
desc = "Set 2, vector#153"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "7B3AA4599561C9059739C7D18D342CF2E73B3B9E1E85D38EDB41AEFADD81BF241580885078CA10D338598D18B3E4B693155D12D362D533494BA48142AB068F68" }
{ "low" : 192, "hi" : 255, "bytes" : "D27864FC30D5FD278A9FB83FADADFD2FE72CE78A2563C031791D55FF31CF59464BE7422C81968A70E040164603DC0B0AEEE93AC497CC0B770779CE6058BE80CF" }
{ "low" : 256, "hi" : 319, "bytes" : "4C5A87029660B65782FD616F48CFD6006DFB158682DC80E085E52163BE2947E270A0FD74DC8DC2F5920E59F28E225280FAC96BA78B8007E3D0DF6EF7BF835993" }
{ "low" : 448, "hi" : 511, "bytes" : "F5A2ECD04452358970E4F8914FC08E82926ECFF33D9FC0977F10241E7A50E528996A7FB71F79FC30BF881AF6BA19016DDC077ED22C58DC57E2BDBDA1020B30B2" } ]
xor_digest = "8C9995B52F4AC9CA25E5C956850FFE90D396530617298D89659C2F863995FB060B65ADFED6AA977EDBB4FC2F6774335E9DEBC61E05E92718A340F79368E74273"
f()
desc = "Set 2, vector#162"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "9776A232A31A22E2F10D203A2A1B60B9D28D64D6D0BF32C8CCA1BBF6B57B1482BCC9FCF7BBE0F8B61C4BF64C540474BCF1F9C1C808CCBE6693668632A4E8653B" }
{ "low" : 192, "hi" : 255, "bytes" : "5C746D64A3195079079028D74CE029A87F72B30B34B6C7459998847C42F2E44D843CF196229EED471B6BBDBA63BE3B529B8AF4B5846EB0AB008261E161707B76" }
{ "low" : 256, "hi" : 319, "bytes" : "F780FE5204AC188A680F41068A9F50182D9154D6D5F1886034C270A8C3AF61DF945381B7ADCA546E153DBF0E6EA2DDDA4EDA3E7F7CF4E2043C5E20AF659282B4" }
{ "low" : 448, "hi" : 511, "bytes" : "71D24CD8B4A70554906A32A5EFDFA8B834C324E6F35240257A0A27485103616DD41C8F4108D1FC76AB72AF166100AB17212492A72099ACF6F9EB53AC50BD8B8B" } ]
xor_digest = "B2217FF55077D373B735C1A7D8B784F5187AF2F028FE906F85B938277CAC918CE87BEA508AFF86B9071F2B7E4F88A3B1F3323151C9DF441FE6F266CF8F01A0B9"
f()
desc = "Set 2, vector#171"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "62DF49A919AF1367D2AAF1EB608DE1FDF8B93C2026389CEBE93FA389C6F2845848EBBE70B3A3C8E79061D78E9ED24ED9AA7BB6C1D726AA060AEFC4FFE70F0169" }
{ "low" : 192, "hi" : 255, "bytes" : "E7A4DF0D61453F612FB558D1FAE198AAB1979F91E1792C99423E0C573345936570915B60210F1F9CA8845120E6372659B02A179A4D679E8EDDDDF8843ABAB7A4" }
{ "low" : 256, "hi" : 319, "bytes" : "C9501A02DD6AFB536BD2045917B016B83C5150A7232E945A53B4A61F90C5D0FB6E6AC45182CBF428772049B32C825D1C33290DBEEC9EF3FE69F5EF4FAC95E9B1" }
{ "low" : 448, "hi" : 511, "bytes" : "B8D487CDD057282A0DDF21CE3F421E2AC9696CD36416FA900D12A20199FE001886C904AB629194AECCC28E59A54A135747B7537D4E017B66538E5B1E83F88367" } ]
xor_digest = "4EB0E761F6BD6A738DC295C0B1B737FCFDB2A68FF50EB198D699CC71141EC6EB54434D40B592A65F2F5C50B6027D4F529307969E1D74028FF4BD6A44CEAA121C"
f()
desc = "Set 2, vector#180"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "6F703F3FF0A49665AC70CD9675902EE78C60FF8BEB931011FC89B0F28D6E176A9AD4D494693187CB5DB08FF727477AE64B2EF7383E76F19731B9E23186212720" }
{ "low" : 192, "hi" : 255, "bytes" : "AD26886ABF6AD6E0CA4E305E468DA1B369F0ADD3E14364C8A95BD78C5F2762B72915264A022AD11B3C6D312B5F6526E0183D581B57973AFB824945BFB78CEB8F" }
{ "low" : 256, "hi" : 319, "bytes" : "FE29F08A5C157B87C600CE4458F274C986451983FE5AE561DF56139FF33755D71100286068A32559B169D8C2161E215DBC32FAEA11B652284795C144CF3E693E" }
{ "low" : 448, "hi" : 511, "bytes" : "7974578366C3E999028FA8318D82AAAA8ED3FD4DFB111CBF0F529C251BA91DC6ACFA9795C90C954CEA287D23AD979028E974393B4C3ABA251BCB6CECCD09210E" } ]
xor_digest = "88BE85838404EA4F0FFDD192C43E3B93329C4A4919234D116E4393EA26110022BED2B427EC719178E6F1A9B9B08BEF5BF2FE4A9CC869CB6BD2D989F750EDA78F"
f()
desc = "Set 2, vector#189"
key = "PI:KEY:<KEY>END_PIDBDBDBD"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "61900F2EF2BEA2F59971C82CDFB52F279D81B444833FF02DD0178A53A8BFB9E1FF3B8D7EC799A7FBB60EADE8B1630C121059AA3E756702FEF9EEE7F233AFC79F" }
{ "low" : 192, "hi" : 255, "bytes" : "D27E0784038D1B13833ACD396413FF10D35F3C5C04A710FC58313EEBC1113B2CFA20CBD1AEA4433C6650F16E7C3B68302E5F6B58D8E4F26D91F19FE981DEF939" }
{ "low" : 256, "hi" : 319, "bytes" : "B658FB693E80CE50E3F64B910B660BEB142B4C4B61466424A9884D22EB80B8B40C26BEA869118ED068DCC83F9E4C68F17A3597D0FE0E36700D01B4252EE0010E" }
{ "low" : 448, "hi" : 511, "bytes" : "9FC658A20D3107A34680CC75EB3F76D6A2150490E9F6A3428C9AD57F2A252385C956B01C31C978E219BE351A534DB23B99908DACC6726196742D0B7E1D88472C" } ]
xor_digest = "DA74A6EC8D54723B1797751F786CB1B517995EBF297A034AF744EEF86833CC5BA3DCBDB4D3FAB47F5BA37463CEC80F45DAE1A48FBB80148A39CA789BAE09D39F"
f()
desc = "Set 2, vector#198"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "42D1C40F11588014006445E81C8219C4370E55E06731E09514956834B2047EE28A9DAECC7EB25F34A311CC8EA28EDCD24A539160A0D8FDAA1A26E9F0CDFE0BE3" }
{ "low" : 192, "hi" : 255, "bytes" : "976201744266DEABBA3BFE206295F40E8D9D169475C11659ADA3F6F25F11CEF8CD6PI:KEY:<KEY>END_PI851B1F72CD3E7D6F0ABAF8FB929DDB7CF0C7B128B4E4C2C977297B2C5FC9" }
{ "low" : 256, "hi" : 319, "bytes" : "D3601C4CD44BBEEFD5DAD1BDFF12C190A5F0B0CE95C019972863F4309CE566DE62BECB0C5F43360A9A09EB5BAB87CF13E7AB42D71D5E1229AF88667D95E8C96F" }
{ "low" : 448, "hi" : 511, "bytes" : "69EAA4BAAAA795BCF3B96E79C931A1F2D2DD16A242714358B106F38C1234A5BBD269E68A03539EFAFA79455ADBE1B984E9766B0720947E1365FDF076F73639CD" } ]
xor_digest = "54E422EB1EB2DBDB338798E0D352A87AD5F5A28BC5F77E1B42913E6500723A936D4019D703DC93A1DF7C65AB74F1FC1A4D38C519A8338B73A435FC7491DFC769"
f()
desc = "Set 2, vector#207"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "9C09F353BF5ED33EDEF88D73985A14DBC1390F08236461F08FDCAF9A7699FD7C4C602BE458B3437CEB1464F451ED021A0E1C906BA59C73A8BA745979AF213E35" }
{ "low" : 192, "hi" : 255, "bytes" : "437E3C1DE32B0DB2F0A57E41A7282670AC223D9FD958D111A8B45A70A1F863E2989A97386758D44060F6BFFF5434C90888B4BB4EDAE6528AAADC7B81B8C7BEA3" }
{ "low" : 256, "hi" : 319, "bytes" : "94007100350C946B6D12B7C6A2FD1215682C867257C12C74E343B79E3DE79A782D74663347D8E633D8BE9D288A2A64A855C71B4496587ADECCB4F30706BB4BD9" }
{ "low" : 448, "hi" : 511, "bytes" : "585D0C2DB901F4004846ADBAA754BCA82B66A94C9AF06C914E3751243B87581AFAE281312A492DBEE8D6BB64DD748F445EF88F82AB44CBA33D767678914BDE77" } ]
xor_digest = "BB97F09B9FCEC06B6124310BBDD1E9CE8D3793F62FF1337F520DE2A90FE2592AF2636DFA20466FDAA9329443ACC0E9A50492621AF5790CAE5642E6F7D9AF400D"
f()
desc = "Set 2, vector#216"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "4965F30797EE95156A0C141D2ACA523204DD7C0F89C6B3F5A2AC1C59B8CF0DA401B3906A6A3C94DA1F1E0046BD895052CB9E95F667407B4EE9E579D7A2C91861" }
{ "low" : 192, "hi" : 255, "bytes" : "8EDF23D6C8B062593C6F32360BF271B7ACEC1A4F7B66BF964DFB6C0BD93217PI:KEY:<KEY>END_PIC5FACC720B286E93D3E9PI:KEY:<KEY>END_PI31FA8C4C762DF1F8A3836A8FD8ACBA384B8093E0817" }
{ "low" : 256, "hi" : 319, "bytes" : "44FA82E9E469170BA6E5E8833117DAE9E65401105C5F9FEA0AF682E53A627B4A4A621B63F7CE5265D3DFADFBFD4A2B6C2B40D2249EB0385D959F9FE73B37D67D" }
{ "low" : 448, "hi" : 511, "bytes" : "828BA57593BC4C2ACB0E8E4B8266C1CC095CE9A761FB68FC57D7A2FCFF768EFB39629D3378549FEE08CCF48A4A4DC2DD17E72A1454B7FA82E2ACF90B4B8370A7" } ]
xor_digest = "8A365EE7E7BC9198EC88A39F5047431D1632CBB0D1E812957595E7A0763DFA46953070863838812A9504F7A376078FEA9444B27E15FC043AE2D375D37DB1C6C3"
f()
desc = "Set 2, vector#225"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "5C7BA38DF4789D45C75FCC71EC9E5751B3A60AD62367952C6A87C0657D6DB3E71053AC73E75FF4B66177B3325B1BBE69AEE30AD5867D68B660603FE4F0BF8AA6" }
{ "low" : 192, "hi" : 255, "bytes" : "B9C7460E3B6C313BA17F7AE115FC6A8A499943C70BE40B8EF9842C8A934061E1E9CB9B4ED3503165C528CA6E0CF2622BB1F16D24657BDAEDB9BA8F9E193B65EB" }
{ "low" : 256, "hi" : 319, "bytes" : "406CD92883E991057DFD80BC8201067F35700264A4DFC28CF23EE32573DCB42091FEF27548613999E5C5463E840FE95760CF80CC5A05A74DE49E7724273C9EA6" }
{ "low" : 448, "hi" : 511, "bytes" : "F13D615B49786D74B6591BA6887A7669136F34B69D31412D4A9CB90234DAFCC41551743113701EF6191A577C7DB72E2CB723C738317848F7CC917E1510F02791" } ]
xor_digest = "B31C13C287692760C2710CC4812A4CD3535248839E0B5220185BE58BBCE6A70D629E0749D40D9E79F698FFAFF7B9C53006419AAAD9AC1FAC2286F66DEC96AEB3"
f()
desc = "Set 2, vector#234"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "5B06F5B01529B8C57B73A410A61DD757FE5810970AA0CBFAD3404F17E7C7B6459DD7F615913A0EF2DCC91AFC57FA660D6C7352B537C65CD090F1DE51C1036AB5" }
{ "low" : 192, "hi" : 255, "bytes" : "0F613F9E9F03199DF0D0A5C5BE253CDF138903876DE7F7B0F40B2F840F322F270C0618D05ABB1F013D8744B231555A8ECB14A9E9C9AF39EDA91D36700F1C25B3" }
{ "low" : 256, "hi" : 319, "bytes" : "4D9FAB87C56867A687A03BF3EDCC224AC54D04450AB6F78A642715AF62CF519215PI:KEY:<KEY>END_PI5338PI:KEY:<KEY>END_PI8PI:KEY:<KEY>END_PI599PI:KEY:<KEY>END_PI9FA679962F038976CDA2DEFA" }
{ "low" : 448, "hi" : 511, "bytes" : "E0F80A9BF168EB523FD9D48F19CA96A18F89C1CF11A3ED6EC8AEAB99082DE99BE46DE2FB23BE4A305F185CF3A8EA377CCA1EF46FD3192D03DCAE13B79960FEF4" } ]
xor_digest = "AB020EA09B2573D7106EAA1D177F2E4A1F8E2237AD1481F9923DDF973A79CFC21A0B8CDDD22D3D78C488D0CC9BE8FAA8C74F0F2CFE619B7D7EA5B2E697E23372"
f()
desc = "Set 2, vector#243"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "E7BC9C13F83F51E8855E83B81AF1FFB9676300ABAB85986B0B44441DDEFAB83B8569C4732D8D991696BD7B6694C6CB20872A2D4542192BE81AA7FF8C1634FC61" }
{ "low" : 192, "hi" : 255, "bytes" : "0B429A2957CBD422E94012B49C443CBC2E13EFDE3B867C6018BABFDE9ED3B8036A913C770D77C60DCD91F23E03B3A57666847B1CACFCBCFF57D9F2A2BAD6131D" }
{ "low" : 256, "hi" : 319, "bytes" : "EA2CBD32269BB804DD2D641452DC09F964CB2BCD714180E94609C1209A8C26D1256067F1B86AA4F886BB3602CF96B4DD7039F0326CD24D7C2D69DE22D9E24624" }
{ "low" : 448, "hi" : 511, "bytes" : "CA0DD398EA7E543F1F680BF83E2B773BBB5B0A931DEADDEC0884F7B823FC686E71D7E4C033C65B03B292426CE4E1A7A8A9D037303E6D1F0F45FDFB0FFE322F93" } ]
xor_digest = "0D67BC1CFE545A6AE2F51A7FB2F32FC62E08707F9CBF2E08245E4594E9DB2A7ECBB6AB7190831C3D7D8F9D606231668E447C4EA29D69B4344952A97A77CC71CB"
f()
desc = "Set 2, vector#252"
key = "PI:KEY:<KEY>END_PI"
IV = "00000000000PI:KEY:<KEY>END_PI0"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "C93DA97CB6851BCB95ABFAF547C20DF8A54836178971F748CF6D49AEF3C9CE8CE7D284571D871EFD51B6A897AF698CD8F2B050B6EB21A1A58A9FC77200B1A032" }
{ "low" : 192, "hi" : 255, "bytes" : "5B4144FD0C46CEE4348B598EEF76D16B1A71CBF85F4D9926402133846136C59FBE577B8B7EB8D6A67A48358573C068766AC76A308A14154E2FA9BD9DCA8842E6" }
{ "low" : 256, "hi" : 319, "bytes" : "3BF67A79DF6FE3C32DA7A53CD0D3723716A99BF7D168A25C93C29DF2945D9BCBF78B669195411BD86D3F890A462734AB10F488E9952334D7242E51AC6D886D60" }
{ "low" : 448, "hi" : 511, "bytes" : "65629AA9654930681578EEC971A48D8390FBF82469A385B8BCF28B2C1E9F13CEFC06F54335B4D5DE011F3DCE2B94D38F1A04871E273FCD2A8FA32C0E08710E69" } ]
xor_digest = "E308FAEC064EC30CA1BEA7C2A02E95F4ABCBF7D7762557BE9872726F9020162F9B4EA11F621426EED6297C947BB3FAC269A8D0F38672EFBD72FDCCBEB8475221"
f()
desc = "Set 3, vector# 0"
key = "PI:KEY:<KEY>END_PI"
IV = "0PI:KEY:<KEY>END_PI00PI:KEY:<KEY>END_PI00000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "2DD5C3F7BA2B20F76802410C688688895AD8C1BD4EA6C9B140FB9B90E21049BF583F527970EBC1A4C4C5AF117A5940D92B98895B1902F02BF6E9BEF8D6B4CCBE" }
{ "low" : 192, "hi" : 255, "bytes" : "AB56CC2C5BFFEF174BBE28C48A17039ECB795F4C2541E2F4AE5C69CA7FC2DED4D39B2C7B936ACD5C2ECD4719FD6A3188323A14490281CBE8DAC48E4664FF3D3B" }
{ "low" : 256, "hi" : 319, "bytes" : "9A18E827C33633E932FC431D697F0775B4C5B0AD26D1ACD5A643E3A01A06582142A43F48E5D3D9A91858887310D39969D65E7DB788AFE27D03CD985641967357" }
{ "low" : 448, "hi" : 511, "bytes" : "752357191E8041ABB8B5761FAF9CB9D73072E10B4A3ED8C6ADA2B05CBBAC298F2ED6448360F63A51E073DE02338DBAF2A8384157329BC31A1036BBB4CBFEE660" } ]
xor_digest = "F3BCF4D6381742839C5627050D4B227FEB1ECCC527BF605C4CB9D6FB0618F419B51846707550BBEEE381E44A50A406D020C8433D08B19C98EFC867ED9897EDBB"
f()
desc = "Set 3, vector# 9"
key = "PI:KEY:<KEY>END_PI"
IV = "0PI:KEY:<KEY>END_PI000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "0F8DB5661F92FB1E7C760741430E15BB36CD93850A901F88C40AB5D03C3C5FCE71E8F16E239795862BEC37F63490335BB13CD83F86225C8257AB682341C2D357" }
{ "low" : 192, "hi" : 255, "bytes" : "002734084DF7F9D6613508E587A4DD421D317B45A6918B48E007F53BEB3685A9235E5F2A7FACC41461B1C22DC55BF82B54468C8523508167AAF83ABBFC39C67B" }
{ "low" : 256, "hi" : 319, "bytes" : "3C9F43ED10724681186AC02ACFEC1A3A090E6C9AC1D1BC92A5DBF407664EBCF4563676257518554C90656AC1D4F167B8B0D3839EB8C9E9B127665DCE0B1FD78C" }
{ "low" : 448, "hi" : 511, "bytes" : "46B7C56E7ED713AAB757B24056AF58C6AD3C86270CFEAE4AADB35F0DB2D969321A38388D00ED9C2AD3A3F6D8BE0DE7F7ADA068F67525A0996DE5E4DF490DF700" } ]
xor_digest = "FDAEDE318DDD9EE44670318D51E812A2F9B6EAEB18B9EBDC0FB76D95CD0AE8C95792F6EA71332404798505D947B89B041D56FAD3B0D92BEC06428EC5A841EB82"
f()
desc = "Set 3, vector# 18"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "4B135E9A5C9D54E6E019B5A2B48B9E6E17F6E6667B9D43BC3F892AD6ED64C5844FE52F75BD67F5C01523EE026A3851083FBA5AC0B6080CE3E6A2F5A65808B0AC" }
{ "low" : 192, "hi" : 255, "bytes" : "E45A7A605BCFBBE77E781BBE78C270C5AC7DAD21F015E90517672F1553724DDA12692D23EC7E0B420A93D249C438356622D45809034A1A92B3DE34AEB4421168" }
{ "low" : 256, "hi" : 319, "bytes" : "14DEA7F82A4D3C1796C3911ABC2EFE9DC9EB79C42F72691F8CB8C353ECBCC0DC6159EC13DFC08442F99F0F68355D704E5649D8B34836B5D2C46F8999CD570B17" }
{ "low" : 448, "hi" : 511, "bytes" : "CA6A357766527EA439B56C970E2E089C30C94E62CB07D7FE1B1403540C2DA9A6362732811EF811C9D04ED4880DC0038D5FDCE22BDE2668CD75107D7926EC98B5" } ]
xor_digest = "DE518E6B67BAEC2A516CCAB0475341C4BCC652ABE49ECCAA64E87248441A8F727BE173CACEBF8895B07DE8DDD28F1EE8AA739855F1E6DB70765AB1B55BC3B1ED"
f()
desc = "Set 3, vector# 27"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "E04A423EF2E928DCA81E10541980CDE5C8054CC3CF437025B629C13677D4116721123EE13F889A991C03A2E5ADC0B12B9BBC63CB60A23543445919AF49EBC829" }
{ "low" : 192, "hi" : 255, "bytes" : "F6E1D7DBD22E05430EBFBEA15E751C8376B4743681DE6AC3E257A3C3C1F9EC6A63D0A04BF3A07F64E6B167A49CD3FDAAB89A05E438B1847E0DC6E9108A8D4C71" }
{ "low" : 256, "hi" : 319, "bytes" : "FC2B2A1A96CF2C73A8901D334462ED56D57ABD985E4F2210D7366456D2D1CDF3F99DFDB271348D00C7E3F51E6738218D9CD0DDEFF12341F295E762C50A50D228" }
{ "low" : 448, "hi" : 511, "bytes" : "1F324485CC29D2EAEC7B31AE7664E8D2C97517A378A9B8184F50801524867D376652416A0CA96EE64DDF26138DB5C58A3B22EF9037E74A9685162EE3DB174A0E" } ]
xor_digest = "697048C59621DBC7D47B6BE93A5060C4B2DFBDB1E7E444F1FC292C06C12974D126EA9C8FD09C63945E4D9107CD0A1AC57161CA8C7CFEF55CB60E52666C705EC6"
f()
desc = "Set 3, vector# 36"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "361A977EEB47543EC9400647C0C169784C852F268B34C5B163BCA81CFC5E746F10CDB464A4B1365F3F44364331568DB2C4707BF81AA0E0B3AB585B9CE6621E64" }
{ "low" : 192, "hi" : 255, "bytes" : "E0F8B9826B20AEEC540EABA9D12AB8EB636C979B38DE75B87102C9B441876C39C2A5FD54E3B7AB28BE342E377A3288956C1A2645B6B76E8B1E21F871699F627E" }
{ "low" : 256, "hi" : 319, "bytes" : "850464EEED2251D2B5E2FE6AE2C11663E63A02E30F59186172D625CFF2A646FACB85DC275C7CA2AF1B61B95F22A5554FBAD63C0DCC4B5B333A29D270B6366AEF" }
{ "low" : 448, "hi" : 511, "bytes" : "4387292615C564C860AE78460BBEC30DECDFBCD60AD2430280E3927353CEBC21DF53F7FD16858EF7542946442A26A1C3DA4CEFF5C4B781AD6210388B7905D2C7" } ]
xor_digest = "2FADEF81A5C4051CAC55E16C68CC6EEFCEE2D4966BAE782E3D885CAA2271EFBBE33F9313FD00632DC73441823713A48794C21E812E30A1DD4B2AE858A27E7C88"
f()
desc = "Set 3, vector# 45"
key = "PI:KEY:<KEY>END_PI"
IV = "0PI:KEY:<KEY>END_PI0000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "9F25D8BD7FBC7102A61CB590CC69D1C72B31425F11A685B80EAC771178030AF052802311ED605FF07E81AD7AAC79B6A81B24113DB5B4F927E6481E3F2D750AB2" }
{ "low" : 192, "hi" : 255, "bytes" : "DAEF37444CB2B068124E074BAD1881953D61D5BA3BFBF37B21BC47935D74820E9187086CEF67EB86C88DDD62C48B9089A9381750DC55EA4736232AE3EDB9BFFE" }
{ "low" : 256, "hi" : 319, "bytes" : "B6C621F00A573B60571990A95A4FEC4AC2CA889C70D662BB4FF54C8FAAE0B7C45B8EC5414AE0F080B68E2943ABF76EA2ABB83F9F93EF94CB3CFE9A4CEED337CD" }
{ "low" : 448, "hi" : 511, "bytes" : "6F17EAE9346878BB98C97F6C81DD2E415FDEB54305FE2DF74AFC65627C376359FB2E7841FF75744A715DF952851C1CBCDD241BADF37B3618E0097B3A084E1B54" } ]
xor_digest = "8D1890B66A56552BE334B3472344F53DD2782D4ABB4514D0F5B761436C99740202A4B1244A1A7F485EFDB52C0065263FEE5A7D7DFC2BB754304CE9B2724119EB"
f()
desc = "Set 3, vector# 54"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "3466360F26B76484D0C4FD63965E55618BDBFDB2213D8CA5A72F2FE6E0A13548D06E87C8A6EEA392FE52D3F5E0F6559D331828E96A07D99C6C0A42EFC24BA96D" }
{ "low" : 192, "hi" : 255, "bytes" : "AB7184066D8E0AB537BB24D777088BC441E00481834B5DD5F6297D6F221532BC56F638A8C84D42F322767D3D1E11A3C65085A8CA239A4FDD1CDF2AC72C1E354F" }
{ "low" : 256, "hi" : 319, "bytes" : "55F29F112B07544EDA3EBB5892DBB91E46F8CBC905D0681D8E7109DF816ABFB8AE6A0F9833CDF34A29F25D67A60D36338A10346FEBE72CCF238D8670C9F2B59C" }
{ "low" : 448, "hi" : 511, "bytes" : "0657453B7806D9EA777FFFBE05028C76DCFF718BC9B6402A3CAEC3BCCB7231E6D3DDB00D5A9637E1E714F47221FFCC11B1425D9653F7D777292B146556A89787" } ]
xor_digest = "C2A8D317E3B1CB884A2C3B07F11FD38833282A9FBD1F6AF5C33CBE1E18D99B6499A241EA83A56605BC6B99259FBAAED4BDDA788B08CAAA93D2E00C6B5392ECF0"
f()
desc = "Set 3, vector# 63"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "40AD59C99464D95702727406E4C82C857FA48911319A3FCC231DC91C990E19D4D9D5972B6A6F21BD12C118365ECAABC89F9C3B63FFF77D8EA3C55B2322B57D0E" }
{ "low" : 192, "hi" : 255, "bytes" : "DBF23042C787DDF6FFCE32A792E39DF9E0332B0A2A2F2A5F96A14F51FAAB7C2714E07C3ADCA32D0DE5F8968870C7F0E81FE263352C1283965F8C210FC25DE713" }
{ "low" : 256, "hi" : 319, "bytes" : "455E3D1F5F44697DA562CC6BF77B93099C4AFAB9F7F300B44AD9783A9622BD543EFDB027D8E71236B52BEE57DD2FB3EE1F5B9022AB96A59AE7DF50E6933B3209" }
{ "low" : 448, "hi" : 511, "bytes" : "F11D47D8C57BBF862E0D6238BC0BF6A52500A62BB037B3A33E87525259B8E54735F664FCEDF11BA2C0F3AEB9C944BCE77FFD26D604674DF8905A73CB7E230A4F" } ]
xor_digest = "F021DE2B24C80A48DE6F7F807F1EF2F813D72A77E7BFC12515F9F5755CEFF64CB5829CA780627A7920F3963E28005677B85A56017A6F5A403DA49F8F8B71581D"
f()
desc = "Set 3, vector# 72"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "D8B1A4CB2A5A8DE1F798254A41F61DD4FB1226A1B4C62FD70E87B6ED7D57902A69642E7E21A71C6DC6D5430DCE89F16FCCC9AAD48743974473753A6FF7663FD9" }
{ "low" : 192, "hi" : 255, "bytes" : "D4BA9BC857F74A28CACC734844849C3EDCB9FB952023C97E80F5BFA445178CAB92B4D9AA8A6D4E79B81993B831C7376510E74E30E7E68AD3188F8817DA8243F2" }
{ "low" : 256, "hi" : 319, "bytes" : "B7039E6F6C4D5D7F750ED014E650118817994F0D3C31B071CC16932A412E627D2486CCB9E43FCA79039D3E0F63577406F5B6420F5587CF9DAC40118AA6F170A8" }
{ "low" : 448, "hi" : 511, "bytes" : "1ABA14E7E9E6BA4821774CBC2B63F410381E4D661F82BAB1B182005B6D42900DC658C6224F959E05095BC8081920C8AD11148D4F8BD746B3F0059E15C47B9414" } ]
xor_digest = "AD0620EB4E71605CDEA447A02E638F0C2A0096EA666010761DB03CFC8562968044D213B15EC69E1E5811EEBE7C96B6166BE36E42B16F9F4BE0CC71B456C1FCA1"
f()
desc = "Set 3, vector# 81"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "235E55E2759C6781BBB947133EDD4D91C9746E7E4B2E5EF833A92BE6086C57C6729655D4C4253EC17ACF359012E801757E7A6EB0F713DEC40491266604B83311" }
{ "low" : 192, "hi" : 255, "bytes" : "247BEAAC4A785EF1A55B469A1AEE853027B2D37C74B8DA58A8B92F1360968513C0296585E6745E727C34FFCE80F5C72F850B999721E3BF1B6C3A019DBEE464C1" }
{ "low" : 256, "hi" : 319, "bytes" : "E7DDB25678BF6EECA2DA2390C9F333EB61CD899DD823E7C19474643A4DA313352556E44A9C0006C8D54B1FD0313D574A08B86138394BA1194E140A62A96D7F01" }
{ "low" : 448, "hi" : 511, "bytes" : "DB417F9C1D9FD49FC96DB5E981F0C3F8484E3BDC559473963D12D982FEA287A39A36D69DDBBCF1CA2C9FB7F4B2B37F3DA755838A67C48822F4C1E82E65A07151" } ]
xor_digest = "119D1DDC7C95982B6B035FD4A4D8C5C9FD2518FFBC69C3C6A7F600174A3916146287F19BDDDAB385D2C6A39C593935F288B2F3E8895B9519EC71BA453319CC1F"
f()
desc = "Set 3, vector# 90"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "F27A0A59FA3D1274D934EACCFA0038AFC3B866D2BFA4A8BA81D698DBCA5B65D52F3A1AC9855BEEEB3B41C510F7489E35AB22CB4444816208C282C461FF16A7BC" }
{ "low" : 192, "hi" : 255, "bytes" : "522594154A2E4843083ABCA886102DA814500C5AADAAB0C8FB40381B1D750F9DA9A1831D8000B30BD1EFA854DC903D63D53CD80A10D642E332DFFC9523792150" }
{ "low" : 256, "hi" : 319, "bytes" : "5D092D8E8DDA6C878A3CFBC1EC8DD13F2A1B073916097AEC4C3E56A229D8E282DDB656DAD60DBC7DF44DF124B19920FCC27FCADB1782F1B73E0A78C161270700" }
{ "low" : 448, "hi" : 511, "bytes" : "8F75BF72995AD23E9ADFEA351F26E42BE2BE8D67FB810ABCBD5FAE552DC10D1E281D94D5239A4EA311784D7AC7A764FA88C7FD7789E803D11E65DD6AC0F9E563" } ]
xor_digest = "55AC113CC018689601F39AA80FA4FA26EE655D40F315C6B694FFAE74A09D382B62A4E7C60F75167361871A82561FFAC453BFED061D6B01672008308C92D241FF"
f()
desc = "Set 3, vector# 99"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "654037B9120AEB60BD08CC07FFEC5985C914DAD04CD1277312B4264582A4D85A4CB7B6CC0EB8AD16475AD8AE99888BC3FDE6A5B744851C5FC77EAB50CFAD021D" }
{ "low" : 192, "hi" : 255, "bytes" : "E52D332CD0DE31F44CDCAB6C71BD38C94417870829D3E2CFDAC40137D066EA482786F146137491B8B9BC05675C4F88A8B58686E18D63BE71B6FEFEF8E46D0273" }
{ "low" : 256, "hi" : 319, "bytes" : "28959548CE505007768B1AA6867D2C009F969675D6E6D54496F0CC1DC8DD1AFBA739E8565323749EAA7B03387922C50B982CB8BC7D602B9B19C05CD2B87324F9" }
{ "low" : 448, "hi" : 511, "bytes" : "D420AEC936801FEE65E7D6542B37C9190E7DB10A5934D3617066BEA8CC80B8EAAAFC82F2860FA760776418B4FF148DFD58F21D322909E7BF0EC19010A168FAF7" } ]
xor_digest = "5BAFB9BEA29B3658A5BBF649E09455B70FB262AB938B65FE71652A0662FF0FB514C35AF438A72A6122AC1AA8591477AEAEB78214C63E41255E87230481D1A793"
f()
desc = "Set 3, vector#108"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "0DB7EA55A79C045818C29E99D8A4B66433E4C77DF532D71BA720BD5D82629F1276EF0BF93E636A6F71F91B947DFA7CAAA1B0512AA531603197B86ABA2B0829D1" }
{ "low" : 192, "hi" : 255, "bytes" : "A62EAFD63CED0D5CE9763609697E78A759A797868B94869EC54B44887D907F01542028DEDDF420496DE84B5DA9C6A4012C3D39DF6D46CE90DD45AF10FA0F8AAF" }
{ "low" : 256, "hi" : 319, "bytes" : "7C2AD3F01023BC8E49C5B36AFE7E67DCA26CCD504C222BD6AF467D4C6B07B79261E9714FDD1E35C31DA4B44DB8D4FC0569F885F880E63B5ABB6BA0BFEE2CE80C" }
{ "low" : 448, "hi" : 511, "bytes" : "066D3C8D46F45891430A85852FF537448EBDD6CE8A799CCF7EAF88425FBD60D32A1741B39CC3C73371C2C9A36544D3C3B0F02D2596ACC61C60A6671F112F185E" } ]
xor_digest = "6EE5BF7E194B03A7DDC92FC74A398FF822471FEF6DD399426F7372E445E1EE365ED7164CD09120A79CCF03D0A2A309DC5932441B64DDC6FDC9E183DA9F825106"
f()
desc = "Set 3, vector#117"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "3FE4BD60364BAB4F323DB8097EC189E2A43ACD0F5FFA5D65D8BDB0D79588AA9D86669E143FD5915C31F7283F1180FCABCDCB64B680F2B63BFBA2AF3FC9836307" }
{ "low" : 192, "hi" : 255, "bytes" : "F1788B6CA473D314F6310675FC7162528285A538B4C1BE58D45C97349C8A36057774A4F0E057311EEA0D41DFDF131D4732E2EAACA1AB09233F8124668881E580" }
{ "low" : 256, "hi" : 319, "bytes" : "FEF434B35F024801A77400B31BD0E73522BEC7D10D8BF8743F991322C660B4FD2CEE5A9FDE0D614DE8919487CBD5C6D13FEB55C254F96094378C72D8316A8936" }
{ "low" : 448, "hi" : 511, "bytes" : "338FD71531C8D07732FD7F9145BBC368932E3F3E4C72D2200A4F780AF7B2C3AA91C1ED44DBEAA9A2F1B3C64DCE8DCD27B307A4104D5C755693D848BEA2C2D23B" } ]
xor_digest = "7ABF3C4E6E8CCAC05AA336DF2156E1957DFDAD45995FF6268B9708DAED9C2097F8F0F2A0EE5FBF4A7B511ED2E8E5617993E915E9BAABA30D758A9691E9D8578A"
f()
desc = "Set 3, vector#126"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "062187DAA84742580D76E1D55EE4DE2E3B0C454F383CFDDE567A008E4E8DAA3CE645D5BEDA64A23F0522D8C15E6DA0AD88421577A78F2A4466BD0BFA243DA160" }
{ "low" : 192, "hi" : 255, "bytes" : "4CC379C5CF66AA9FB0850E50ED8CC58B72E8441361904449DAABF04D3C464DE4D56B22210B4336113DAA1A19E1E15339F047DA5A55379C0E1FE448A20BC10266" }
{ "low" : 256, "hi" : 319, "bytes" : "BD2C0F58DBD757240AEB55E06D5526FE7088123CE2F7386699C3E2780F5C3F86374B7CB9505299D639B89D7C717BA8A2AEED0C529F22F8C5006913D1BE647275" }
{ "low" : 448, "hi" : 511, "bytes" : "54D61231409D85E46023ED5EFF8FDC1F7A83CACDDB82DD8D1FA7CDEA0E088A61D02BCE7FA7EC3B73B66953DA467BE4B912EBE2A46B56A8BF0D925A919B7B22E3" } ]
xor_digest = "9F569A8133067D1D4651BAE70DB3FE201649A1DA469C7D7C0B0DF16968285BF4ED0F36ED1CF9F213B2EC4BFF83D455FFC8B19E82DAE61408141F221C255DDFAB"
f()
desc = "Set 3, vector#135"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "1A74C21E0C929282548AD36F5D6AD360E3A9100933D871388F34DAFB286471AED6ACC48B470476DC5C2BB593F59DC17EF772F56922391BF23A0B2E80D65FA193" }
{ "low" : 192, "hi" : 255, "bytes" : "B9C8DAC399EF111DE678A9BD8EC24F340F6F785B19984328B13F78072666955AB837C4E51AC95C36ECBEFFC07D9B37F2EE9981E8CF49FD5BA0EADDE2CA37CC8D" }
{ "low" : 256, "hi" : 319, "bytes" : "3B0283B5A95280B58CEC0A8D65328A7A8F3655A4B39ECBE88C6322E93011E13CFF0A370844851F4C5605504E8266B301DD9B915CA8DCD72E169AEA2033296D7F" }
{ "low" : 448, "hi" : 511, "bytes" : "4F9CA1676901DDC313D4EE17B815F6B5AC11AF03BF02517FB3B10E9302FCBF67C284B5C7612BBE7249365BCAC07FD4C2C7AE78F3FDA1880B2DAA20E4EC70F93B" } ]
xor_digest = "9B9EA936FD4385D3516304BEFC44BC6D5B60C97925B52CE269F2843496DEBD335A07ADA2EC87BA27E306CFFB884935D774EE317C7307740B884095278D1DB0C2"
f()
desc = "Set 3, vector#144"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "0281FB6B767A90231AB6A19EB1E4FB76A041063FE23AC835797DFA178CC2D7C28DFAD591D2EAF26A985332F8DC74537DF7E0A5F26946BCF7D70B6C3D9DD859D2" }
{ "low" : 192, "hi" : 255, "bytes" : "088ED6D7AB26EEC97518EBF387B0644FD22266E578F141A7218F94AE2EE5885A67A9FA304F6880A781EE05C1251A7EAD4C3025D833B59739C68D3D7F3A844148" }
{ "low" : 256, "hi" : 319, "bytes" : "6B48D13EC0EB1CD0CDAC5D5E09DC7BE4AE02BE4283DDC7FA68E802A31508E6EA7197E5AC10805FDEB6824AEEF8178BAA45D7E419CF9237155D379B38F994EF98" }
{ "low" : 448, "hi" : 511, "bytes" : "7E71823935822D048B67103FF56A709A25517DCE5CFBB807B496EEF79EFFBCD10D23BAD02758814F593B2CD4AC062699AEC02B25A7E0D1BAE598AFDBE4333FE7" } ]
xor_digest = "0D4802AF0B0F92FFF2F80FE65FE5D1FBDFEF122231028FE36CC164D1D39185A1869AD43D08C6E1C9F8A9113CE2CEF0A022629C6FAC1C27E6DDF2A46C52293681"
f()
desc = "Set 3, vector#153"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "D4ACE9BF4A76822D685E93E7F77F2A7946A76E3BF0910854C960331A41835D40902BC1CF3F8A30D4C8391087EC3A03D881E4734A5B830EFD55DA84159879D97F" }
{ "low" : 192, "hi" : 255, "bytes" : "5BD8BB7ED009652150E62CF6A17503BAE55A9F4ECD45B5E2C60DB74E9AE6C8BF44C71000912442E24ED2816243A7794D5B1203A246E40BE02F285294399388B1" }
{ "low" : 256, "hi" : 319, "bytes" : "55433BDEA349E8849D7DF899193F029A9F09405D7AFE842CB2C79F0E55C88913B0776825D8D036A69DDDCD6AFCA6588F69F0946A86D32C3585F3813B8CCB56AF" }
{ "low" : 448, "hi" : 511, "bytes" : "0B67F00FA0BB7D1ED5E4B46A687948645239422656F77EF2AFEA34FFF98DA7A890970F09137AF0FABD754C296DD3C6F27539BC3AE78FFA6CDCCC75E944660BB4" } ]
xor_digest = "9D6D8BAB5F6EDB5450EA2D5751741351199ED720B0572410FD698C99F2E0DB92C0E62E68AEE0CC6CDB6EA8898BFD29E8E106470DE4E5C66F94FE0258A2D24CA3"
f()
desc = "Set 3, vector#162"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "92A067C3724F662120C25FAF4B9EC419C392D98E5CB8C5EE5842C1D5C704DE878C8C68C55BA83D63C5DEEC24CFF7230D3F6FBF6E49520C20CFE422798C676A47" }
{ "low" : 192, "hi" : 255, "bytes" : "133C9A30B917C583D84FB0AAC2C63B5F6758AC8C2951196E9460ADBE3417D91490F0A195DC5682F984069506CA75DC1D79A7AE1DCDF9E0219D4E6A005BA72EDD" }
{ "low" : 256, "hi" : 319, "bytes" : "091D38749503B63238B1E3260855B76C5CFE9D012265FB7F58EB8CAA76B456459C54F051274DDAE06BEC6D7EB8B9FF595302D9D68F2AF1057581D5EE97CCEEDD" }
{ "low" : 448, "hi" : 511, "bytes" : "3FCCB960792B7136768BBA4C3D69C59788F04602C10848A7BCBED112F860998D9E9A788998D1DC760F7ECF40597446D8F39CD4D4013F472BB125DE6A43E9799D" } ]
xor_digest = "12464226235C1DDDAFA37DF12F3A044442C0EEE521DBB7B3239C86ADB61AD6A0A418D3804252DC3658A3AE82473023A8D190E1EDB1DAFA3CF566573511CF8F19"
f()
desc = "Set 3, vector#171"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "AC3DE1B9F6DF6D6117B671A639BF076124A0A6D293B107554E9D662A8BFC3F3417C59437C981A0FDF9853EDF5B9C38FE74072C8B78FE5EBA6B8B970FE0CE8F1F" }
{ "low" : 192, "hi" : 255, "bytes" : "23112BD4E7F978D15F8B16F6EDB130D72F377233C463D710F302B9D7844C8A47FB2DFDD60235572859B7AF100149C87F6ED6CE2344CDF917D3E94700B05E2EEF" }
{ "low" : 256, "hi" : 319, "bytes" : "E8DDFE8916B97519B6FCC881AEDDB42F39EC77F64CAB75210B15FBE104B02FC802A775C681E79086D0802A49CE6212F177BF925D10425F7AD199AB06BD4D9802" }
{ "low" : 448, "hi" : 511, "bytes" : "F9D681342E65348868500712C2CA8481D08B7176A751EF880014391A546809926597B10E85761664558F34DA486D3D4454829C2D337BBA3483E62F2D72A0A521" } ]
xor_digest = "75BEFA10DACA457FFE4753A13543F9964CF17E6941318C931575A0865B1C86C12EE5E031EFD125A3D56C4B7846C19484507CC551C5CB558533E288BA0D2C14F1"
f()
desc = "Set 3, vector#180"
key = "PI:KEY:<KEY>END_PI"
IV = "PI:KEY:<KEY>END_PI000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "21BD228837BFB3ACB2DFC2B6556002B6A0D63A8A0637533947615E61FE567471B26506B3D3B23F3FDB90DFAC6515961D0F07FD3D9E25B5F31B07E29657E000BF" }
{ "low" : 192, "hi" : 255, "bytes" : "2CF15E4DC1192CA86AA3B3F64841D8C5CD7067696674B6D6AB36533284DA3ABFD96DD87830AE8FA723457BE53CB3404B7A0DCBB4AF48A40FC946C5DEB7BD3A59" }
{ "low" : 256, "hi" : 319, "bytes" : "E3B15D2A87F61C2CE8F37DCEB896B5CA28D1DA6A3A71704309C0175BB61169119D5CBE34FC8F052961FF15F2C8F06CD6F8E889694E2C69E918DD29C33F125D31" }
{ "low" : 448, "hi" : 511, "bytes" : "CCD1C951D6339694972E902166A13033A1B0C07313DC5927FE9FB3910625332C4F0C96A8896E3FC26EFF2AF9484D28B8CB36FF4883634B40C2891FA53B6620B1" } ]
xor_digest = "1E6FA2DF675C21D1AA9819BA05D3C96D3463D6F0758286BBB41A63F8748B94C8B652C60C5D4655E8436F2379CA7088B49625667F386BC5A2F25FD0BFB0088FAA"
f()
desc = "Set 3, vector#189"
key = "PI:KEY:<KEY>END_PI"
IV = "0PI:KEY:<KEY>END_PI00000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "7943AD4AA5F62E08E1AE450E84CFF27DE3B204A2BCA315B981906D5A13F68AB034D3396EA8A41001AF49834368805B37D5380FB14821E3F7F4B44231784306F3" }
{ "low" : 192, "hi" : 255, "bytes" : "415F5381C9A58A29045E77A1E91E6726DFCEBC71E4F52B36DBD7432D158F2ADB31CF5F52D8456952C09B45A16B289B7A32687716B8EDFF0B1E5D0FC16DCCFA88" }
{ "low" : 256, "hi" : 319, "bytes" : "CE317CB853E2AFA22392D4B8AE345A910807F8DE3A14A820CDA771C2F2F3629A65A1CC7A54DDEC182E29B4DACEA5FBFA4FAC8F54338C7B854CD58ABA74A2ACFF" }
{ "low" : 448, "hi" : 511, "bytes" : "5804F61C5C07EC3C2D37DF746E4C96A1AD5E004C2585F3F401CB3AF62CB975F864375BE3A7117079810418B07DABCCEE61B6EC98EA4F28B0D88941CB6BE2B9D2" } ]
xor_digest = "9DBDBD0C3B340F294B1EB42CAD3111F0A5CF6A0B6206976022C6A2D6303A235B717542C25397879A27480D67AC5A245D0C58PI:KEY:<KEY>END_PICD801764A948060CA6F99E2D6"
f()
desc = "Set 3, vector#198"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "A4FB9A02500A1F86145956E16D04975E2A1F9D2283D8AD55C17A9BD6E0C8B5616658132B8928F908FEC7C6D08DBFBC5573449F28AA0EF2884E3A7637233E45CD" }
{ "low" : 192, "hi" : 255, "bytes" : "74D169573560C14692BBE2498FDA0ED7866A11EE4F26BB5B2E9E2559F089B35EC9972634C5A969DD16EB4341782C6C29FBBF4D11ECB4133D1F9CA576963973EB" }
{ "low" : 256, "hi" : 319, "bytes" : "D28966E675759B82EDE324ABA1121B82EAB964AB3E10F0FE9DF3FCC04AFC83863A43FD6B7FC0AD592C93B80BE99207CBA8A55DDEA56DD811AAD3560B9A26DE82" }
{ "low" : 448, "hi" : 511, "bytes" : "E362A817CCD304126E214D7A0C8E9EB93B33EB15DE324DDDFB5C870EA22279C78E28EFF95974C2B935FC9F1BF531D372EF7244D2CC620CEBDE5D8096AD7926B3" } ]
xor_digest = "3DD73F824FD1D9CB55B7E37C9C8A55C7EBB0866564AEA680BBBD431554D89E81FF280B563D5991438CEA5C183C607ADC23CC72CDE3A4D2CEB27B81ED8E5C9215"
f()
desc = "Set 3, vector#207"
key = "PI:KEY:<KEY>END_PI"
IV = "0PI:KEY:<KEY>END_PI00000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "FF879F406EAF43FABC6BE563ADA47C27872647F244C7FAE428E4130F17B471380E1E1CD06C50309760FDEE0BC91C31D0CA797E07B173C6202D2916EEBA9B6D1C" }
{ "low" : 192, "hi" : 255, "bytes" : "61E724B288AECF393483371C1BE653F37BBA313D220173A43459F0BCE195E45C49B3B5FB1B0539DE43B5B4F2960D8E6E5BC81DAF07E9EFBB760881441FA8823B" }
{ "low" : 256, "hi" : 319, "bytes" : "F77AC22945ECD60EBCAF4BA19A59B078B3C3BC36D1DDA6B9969B458C2019D68EFD04D75DDC6041BBCD69747651D2DA7FBED721081F8147367585CABB1C50CF0C" }
{ "low" : 448, "hi" : 511, "bytes" : "7475DCD3545B810445AFCA0C0AFA93A911EA99991A5D639AB32DDF69AA21C45A53DCB998FDAE5F9A82EC8501123EAE3D99351C43311F8430DB3D230E12DA77D2" } ]
xor_digest = "A61CDBCF6F79213D2A789543B0EA3D8A22BA4FB8118C1D40AE56EC823886156620CED8AA76FFE917C1E52060F91EE73BC75E913D072C50B3D939PI:KEY:<KEY>END_PI04F69493553"
f()
desc = "Set 3, vector#216"
key = "PI:KEY:<KEY>END_PI"
IV = "0PI:KEY:<KEY>END_PI000000PI:KEY:<KEY>END_PI"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "2B4C4185E2FDFAE75DABFF32632FB5D9823359F15E2D17FF74FAC844E5016A4A64C2C47498A15029FBEB6E4893381E656D2A2B9712524827B151C6E67D990388" }
{ "low" : 192, "hi" : 255, "bytes" : "D870A94C4856EF818C5D93B2187F09C732E4491103B8A49B14CDC118F1607E2D8443740F20220DF076B981D90436E9C309282C1CEAAE6375002AD1CA9CCF720C" }
{ "low" : 256, "hi" : 319, "bytes" : "5091AE53E13948DAE57F6B0BE95B8F46A1F53553767B98F9799A0F0AC468AEB340C20E23FA1A8CAE7387CEA127A7A0F3635667BF028DE15179093B706306B99C" }
{ "low" : 448, "hi" : 511, "bytes" : "02323B1FA2C863D3B4A89CFC143013A6EEA8265BBD1B8FE243DEA2F4B19A5726593564E7E7021FD042F58077A5821C2F415BC38D6DD2BE29A5400E4B1D65B2A2" } ]
xor_digest = "9B29085D13B4992B077E3A878A5918B592C98C8A83956EC20EFE673A24C48C915D8DB1A4A66F62F1A3E7D6ADF6DC8845DD7A6D43F9DBF6C1EA21639060469AD6"
f()
desc = "Set 3, vector#225"
key = "PI:KEY:<KEY>END_PI"
IV = "0PI:KEY:<KEY>END_PI000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "9A5509AB6D2AB05C7DBA61B0CC9DD844B352A293E7D96B5C0066ACDB548DB8570459E989B83AF10A2C48E9C00E02671F436B39C174494787D1ECEB3417C3A533" }
{ "low" : 192, "hi" : 255, "bytes" : "8A913EBA25B4D5B485E67F97E83E10E0B858780D482A6840C88E7981F59DC51F2A86109E9CD526FCFA5DBF30D4AB575351027E5A1C923A00007260CE7948C53D" }
{ "low" : 256, "hi" : 319, "bytes" : "0A901AB3EBC2B0E4CBC154821FB7A0E72682EC9876144C4DC9E05098B6EFCCCB90E2F03837553C579CDD0A647D6A696350000CA57628B1E48E96242226A92ECC" }
{ "low" : 448, "hi" : 511, "bytes" : "9CDB39B79A464F2CCA3637F04EBAEA357A229FC6A9BA5B83171A0A8945B6F11756EBC9F4201D0BA09C39F9776721304632AA6A68ADE5B90268AEE335E13B1D39" } ]
xor_digest = "695757EDF4992CE9E1C088D62CAB18A38F56EE71F1F4866E88D1A02E07CB89B9133F0B02A23BA39622E84E19DACDF32397F29PI:KEY:<KEY>END_PI0PI:KEY:<KEY>END_PI785PI:KEY:<KEY>END_PI4PI:KEY:<KEY>END_PI717093131A10B1"
f()
desc = "Set 3, vector#234"
key = "PI:KEY:<KEY>END_PI"
IV = "PI:KEY:<KEY>END_PI"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "37EDAFA4F5EDC64EBF5F74E543493A5393353DE345A70467A9EC9F61EEFE0ED4532914B3EA6C2D889DA9E22D45A7DD321EA5F1F6978A7B2E2A15D705DE700CE4" }
{ "low" : 192, "hi" : 255, "bytes" : "C415739777C22430DAB2037F6287E516B1CE142111456D8919E8CD19C2B2D30D8A1B662C26137F20F87C2802A2F3E66D8CEB9D3C1B4368195856249A379BD880" }
{ "low" : 256, "hi" : 319, "bytes" : "0381733EC9B2073F9E4E9954471184112D99B23FA4A87B4025C6AF955E93E0D57DD37011E1624175F970BDA7D625224BAB0F021E6453DBA894A5074C447D24BC" }
{ "low" : 448, "hi" : 511, "bytes" : "F9D45C7E0E7A26F2E7E2C07F68AF1191CC699964C01654522924A98D6790A946A04CD9586455D5A537CBA4D10B3C2718745C24875156483FE662B11E0634EAEA" } ]
xor_digest = "E0FE8129B73BCADA14FB385E6D3DB22D84C9755D63E93141202576FB5B2D3647D47B2F6378BC8567E4416976443FAE763C2B5FA46F2670C301A5B22802513D2D"
f()
desc = "Set 3, vector#243"
key = "PI:KEY:<KEY>END_PI"
IV = "PI:KEY:<KEY>END_PI00000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "B935A7B6D798932D879795A182E7C194BECEFF32522C2F3FFF55A5C6D32A91D2BA9F144DB280ABA7BA8A7921AFA3BD82CA742DDBEAF8AF72299936E9C2FEA59E" }
{ "low" : 192, "hi" : 255, "bytes" : "6F32248B6EF4CDAE06864B6477893440F0E0217421D7081D1F0DA197B52636740E9BDD59068BEDE48BF52C43446C12CD4F10ED22BFDDFA915FA0FB1A73F9139C" }
{ "low" : 256, "hi" : 319, "bytes" : "BF01A4ED868EF9080DF80689E589897C021DCA18073F9291E1D158DC26266556728DD130629D3760F541439147F4C1CA279FB98040E9FCE50998E42D6259DE1F" }
{ "low" : 448, "hi" : 511, "bytes" : "0F2B116CD687C91FBA1EDEAD586411E966D9EA1076863EC3FDFC254DD5C93ED6AE1B01982F63A8EB13D839B2510AD02CDE24210D97A7FA9623CAC00F4C5A1107" } ]
xor_digest = "C6970385CA89CDFCACA9E90DA2A2FE9958EF83B9BF04DBE7A3B343750368883105FF6665D9F91D4DBBBCAF31B555ED3DD07C3AC8242817PI:KEY:<KEY>END_PI0BF834693C596AD54"
f()
desc = "Set 3, vector#252"
key = "PI:KEY:<KEY>END_PI"
IV = "0PI:KEY:<KEY>END_PI0000PI:KEY:<KEY>END_PI"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "09D36BFFDDCD3ADC8EB0ABEEB3794CE1FFBDED9CFC315D21A53C221B27722FE3F10E20D47DDCFD3CCDE9C1BAAF01F5511D3F14F88BF741A7F6578C3BC9024B2B" }
{ "low" : 192, "hi" : 255, "bytes" : "552502A1B2D0F29806DE512F3314FC8E19518E35D9DB1EBC9034EA46E5815AB9DF0F403E997E676BF47C0116D5E9B81726B99D65AA4315F1E5906F6E39B1297E" }
{ "low" : 256, "hi" : 319, "bytes" : "6BF351A501E8D1B4BAF4BFD04726DC4F50200463DCC13FF3BE93E6C4D4304CE09E6A1CEA41BFB93D6DBAD713298F79CFF6F5BB81F456E33A3396D02F2E33BDC5" }
{ "low" : 448, "hi" : 511, "bytes" : "715F8FFB2BC25CD89E46B706EF871207EFE736AA3CB961B06E7B439E8E4F76E2944AF7BD49EEC47B4A2FD716D191E85859C74FD0B4A505ACE9F80EEB39403A1F" } ]
xor_digest = "D51B519D78CDBC8DF5CB1CEA5EBBA6E46530535D84CBF1696EBF238D3F7AA4A1D2F1EF5FF092DB57943E28501C64CFF04619197ED4A3D82EEPI:KEY:<KEY>END_PI"
f()
desc = "Set 4, vector# 0"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "BE4EF3D2FAC6C4C3D822CE67436A407CC237981D31A65190B51053D13A19C89FC90ACB45C8684058733EDD259869C58EEF760862BEFBBCA0F6E675FD1FA25C27" }
{ "low" : 65472, "hi" : 65535, "bytes" : "F5666B7BD1F4BC8134E0E45CDB69876D1D0ADAE6E3C17BFBFE4BCE02461169C54B787C6EF602AF92BEBBD66321E0CAF044E1ADA8CCB9F9FACFC4C1031948352E" }
{ "low" : 65536, "hi" : 65599, "bytes" : "292EEB202F1E3A353D9DC6188C5DB43414C9EF3F479DF988125EC39B30C014A809683084FBCDD5271165B1B1BF54DAB440577D864CD186867876F7FDA5C79653" }
{ "low" : 131008, "hi" : 131071, "bytes" : "C012E8E03878A6E7D236FEC001A9F895B4F58B2AF2F3D237A944D93273F5F3B545B1220A6A2C732FC85E7632921F2D366B3290C7B0A73FB61D49BC7616FC02B8" } ]
xor_digest = "196D1A0977F0585B23367497D449E11DE328ECD944BC133F786348C9591B35B7189CDDD934757ED8F18FBC984DA377A807147F1A6A9A8759FD2A062FD76D275E"
f()
desc = "Set 4, vector# 1"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "BA1A48247B8C44AAF12F5645D65FF7F4E4D7C404EE0CBB691355FAEB82D03B99AD0FDFC20A1E593973E5B8F0264F7FB0538292A4C8FE8218A1DA3EB7B71EEA64" }
{ "low" : 65472, "hi" : 65535, "bytes" : "03A24E89D69D5E1DA98B0367CF626F33D558B1208AB120B6B1778BFF640F56DA715FE1B681D8CC0F305D6645B439BA81D3C446A428B31BB18E9DA1E2A900B0FD" }
{ "low" : 65536, "hi" : 65599, "bytes" : "6A28ADD4F926759CEBB0AFC5D5DA52431F2E7ECBBD1E9DEAF368137E35F1AFBD65852214FA06310C3175FCF364810F627E3703E9AC5458A8B681EB03CEECD872" }
{ "low" : 131008, "hi" : 131071, "bytes" : "E8D8AB5E245B9A83A77B30F19E3706F037272E42F9C6CD7E8156C923535EF119B633E896E97C404C6D87565EEA08EB7FF6319FF3E631B6CDD18C53EE92CCEEA0" } ]
xor_digest = "2BD4F834BC7B3C128E291B2BCE7DA0A5BA1A17E2785093B7F32B7D605AE63276F8256998EC1E0B5A7FD2D66EE9B0B705E49435EDF8BACE1BE770738A403PI:KEY:<KEY>END_PI8F14"
f()
desc = "Set 4, vector# 2"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "8313F4A86F697AAC985182862E4FC6233511C46B6DAEEDB94B63461111CB476872F1BC3B4E8EE80A4ADE7D1A8CD49C171D3A550D3F39B7775734225579B8B60A" }
{ "low" : 65472, "hi" : 65535, "bytes" : "6AFA6F539C0F3B0B9DEB0235E7EB2E14B111615D4FBC5BF7FFE75E160DEDA3D9932125469AEC00539ECE8FCF8067CB0FB542C2064267BEA7D9AD6365314D5C2C" }
{ "low" : 65536, "hi" : 65599, "bytes" : "296F2B5D22F5C96DA78304F5800E0C87C56BC1BACD7A85D35CFECE17427393E1611975CC040D27DF6A5FABC89ADDE328AE8E9CB4F64CFA0CB38FE525E39BDFE4" }
{ "low" : 131008, "hi" : 131071, "bytes" : "86C8139FD7CED7B5432E16911469C7A56BDD8567E8A8993BA9FA1394348C2283F2DF5F56E207D52A1DA070ABF7B516CF2A03C6CD42D6EA2C217EC02DF8DDCA9C" } ]
xor_digest = "DEEBF1FCF222519E26EC6556EA44908092923B357CB88D1A1C1B03341F5C6A984C70E9DB735377615C0476D46DA9897B48127A0D224241PI:KEY:<KEY>END_PI8CF51B005EF93"
f()
desc = "Set 4, vector# 3"
key = "PI:KEY:<KEY>END_PI"
IV = "0PI:KEY:<KEY>END_PI0000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "62765613D127804ECD0F82D208D701563B1685EEF67945DAE2900307CDB14EA62474A439D8BAE8005493455471E7BCB9DB75F0596F3FB47E65B94DC909FDE140" }
{ "low" : 65472, "hi" : 65535, "bytes" : "00A0D5B2CE7B95E142D21B57B187C29C19B101CD063196D9B32A3075FB5D54A20D3CE57CBEC6CA684CB0E5306D5E21E5657F35B8FB419A0251EA5CD94113E23B" }
{ "low" : 65536, "hi" : 65599, "bytes" : "AAC2D29404A015047DEFB4F11460958DA989141026FE9325F15954363FC78898D4A20F6870F4D2B124590973F6956096940E2324F7C63384A85BACF53F7755E3" }
{ "low" : 131008, "hi" : 131071, "bytes" : "0A543607FE352336ACFEDFE6B74359E0B26B19FD45A8938C6C0A6DB68A1377495B65211558D0CB9ECA9DA2C0E50702B688B2DEC53AAA2FBF11BD149F4F445696" } ]
xor_digest = "D124AA942DC1D54D5B9B4BC6804F9990543EAF31FF441F0CD16B961C817EA4A76AF71F678BBB482052B2BA767B4F9265B65C3D839D182D093B560AEB09184C0C"
f()
desc = "Set 5, vector# 0"
key = "PI:KEY:<KEY>END_PI"
IV = "8000000000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "B66C1E4446DD9557E578E223B0B768017B23B267BB0234AE4626BF443F219776436FB19FD0E8866FCD0DE9A9538F4A09CA9AC0732E30BCF98E4F13E4B9E201D9" }
{ "low" : 192, "hi" : 255, "bytes" : "462920041C5543954D6230C531042B999A289542FEB3C129C5286E1A4B4CF1187447959785434BEF0D05C6EC8950E469BBA6647571DDD049C72D81AC8B75D027" }
{ "low" : 256, "hi" : 319, "bytes" : "DD84E3F631ADDC4450B9813729BD8E7CC8909A1E023EE539F12646CFEC03239A68F3008F171CDAE514D20BCD584DFD44CBF25C05D028E51870729E4087AA025B" }
{ "low" : 448, "hi" : 511, "bytes" : "5AC8474899B9E28211CC7137BD0DF290D3E926EB32D8F9C92D0FB1DE4DBE452DE3800E554B348E8A3D1B9C59B9C77B090B8E3A0BDAC520E97650195846198E9D" } ]
xor_digest = "104639D9F65C879F7DFF8A82A94C130CD6C727B3BC8127943ACDF0AB7AD6D28BF2ADF50D81F50C53D0FDFE15803854C7D67F6C9B4752275696E370A467A4C1F8"
f()
desc = "Set 5, vector# 9"
key = "PI:KEY:<KEY>END_PI"
IV = "004PI:KEY:<KEY>END_PI00000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "1A643637B9A9D868F66237163E2C7D976CEDC2ED0E18C98916614C6C0D435B448105B355AE1937A3F718733CE15262316FA3243A27C9E93D29745C1B4DE6C17B" }
{ "low" : 192, "hi" : 255, "bytes" : "CDDB6BD210D7E92FBFDD18B22A03D66CC695A93F34FB033DC14605536EEEA06FFC4F1E4BACFCD6EB9DA65E36C46B26A93F60EAA9EC43307E2EA5C7A68558C01A" }
{ "low" : 256, "hi" : 319, "bytes" : "5FC02B90B39F3E90B8AEC15776F2A94FD8C26B140F798C93E1759957F99C613B8B4177A7B877D80A9B9C76C2B84E21A6DF803F0DB651E1D0C88FB3743A79938F" }
{ "low" : 448, "hi" : 511, "bytes" : "B4BC18F7279AC64BB6140A586F45AC96E549C0CA497F59B875C614DE605A8BFF63AB3F1E00DAEAE7A5CC7A7796E9BACCDD469E9100EABCD6E69301EA59C4B76A" } ]
xor_digest = "4EF8F9A7D50D7ABEC1A104565E9E20BF35FACFDD5600B0360E3ECBDE626CC6934A52173415C05BA5EE681D649CB60D186970CF18BC028AF829054903FDEB37BA"
f()
desc = "Set 5, vector# 18"
key = "PI:KEY:<KEY>END_PI"
IV = "0000200000000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "94B7B07E184BC24A0904290B2601FC3AC70BEAD7B1FC3294360ED4EF168134530B4D1F3F28A3C3B248B2E914A8DCBD5326A240C9BB361A8A93D023725BDCD4E3" }
{ "low" : 192, "hi" : 255, "bytes" : "27C7A2C4EAA1E2E8798CA71EA50B7E5ACD9FC82263D11781EFC16142CFD21A634DB2B860B54A9979AFA187CE0667D17623FC91EC1E5E6C31A8089628AC76F9F0" }
{ "low" : 256, "hi" : 319, "bytes" : "C2CD243516E5919D6C5C478469260813ABE8E6F54BE8E11D48FEC043CDADA19BEFE9CB0C22A9BB30B98E4CFCF1A55EF1263B209CE15FEAEF8237CFAF7E5286D6" }
{ "low" : 448, "hi" : 511, "bytes" : "84489BD680FB11E5CAA0F5535ABA86DCFF30AC031CEFED9897F252803597772670E1E164FA06A28DD9BAF625B576166A4C4BF4CADD003D5DF2B0E6D9142DD8B3" } ]
xor_digest = "783AD910F37369EFB54DD9A00D54CDB72EEAF2693C121B13344025E08DF874AC4BBC08B8FA916B423B0F4667A6D1BAEC3016B999FF9PI:KEY:<KEY>END_PI6PI:KEY:<KEY>END_PI22PI:KEY:<KEY>END_PIFF925AB"
f()
desc = "Set 5, vector# 27"
key = "PI:KEY:<KEY>END_PI"
IV = "0PI:KEY:<KEY>END_PI1PI:KEY:<KEY>END_PI0000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "2E6C8BE7DD335292EE9152641B0E4EFB43D27434E4BE70EAC4CAFAE5C38B2E5B06E70B9966F4EDD9B4C4589E18E61F05B78E7849B6496F33E2FCA3FC8360824C" }
{ "low" : 192, "hi" : 255, "bytes" : "1006D6A04165A951C7EE31EEB0F6C32BD0B089683C001942886FCEF9E700D15ADB117652735C546D30177DC14FA68708D591C3254C05B84BF0DCBC3105F06A6F" }
{ "low" : 256, "hi" : 319, "bytes" : "2196ADA05BED2BD097A43E4C5BE6C9404A353689939DCB9C4F82278BDB0EB505F70FFD9921B46645EDDFCF47405FD3E67CAE732B367A0B0F2B57A503161FA5DE" }
{ "low" : 448, "hi" : 511, "bytes" : "4A3504DAC25F59489C769090D822E89E1338AC73F22DB2614B43D640525EF9969D6B7E3900ADCBE056AB818E0FF708E3B0A8E63531F252C384DD3DE7318EA866" } ]
xor_digest = "33533F81725EA5444E0642A07A334AE5AC3DD16214F6FE196A60A4343AFA5026E1602E84D3E672EEDB9FB5BB6F44C02366C28BD8E3PI:KEY:<KEY>END_PI673PI:KEY:<KEY>END_PI438PI:KEY:<KEY>END_PI82561PI:KEY:<KEY>END_PI"
f()
desc = "Set 5, vector# 36"
key = "PI:KEY:<KEY>END_PI"
IV = "00PI:KEY:<KEY>END_PI0000008000000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "1D3FD8BAF2A13BCD2A49B50F8DFB05228E366B4FD2ECD6973DFF116289D7E0AF55EFB875345204B5FCE27A1C6DF79531B3175647526BF5C028C454BADEFBECD6" }
{ "low" : 192, "hi" : 255, "bytes" : "F639D0D23CC5817501517216ADA14241D08495F17CDEAFB883CE619A3255EC3FEAADFA224CF354C425A74D3DDAAA0C86E44016238C142B36944EF53A1EC7DF92" }
{ "low" : 256, "hi" : 319, "bytes" : "9CAE4D4639696A188E08BC1B017746085D18418F82DC90742BB6D172414ACC13A4721B018B2CC002CB6E6FFE4A4E252CC4BF5DE975684C8805036F4C76660DC8" }
{ "low" : 448, "hi" : 511, "bytes" : "CB2A2CB3136F5CC71FD95A4A242B15E51C8E3BAE52FEC9C1B591B86DFDDC2442353DF500B2B9868A6C609655FC1A3E03347608D12D3923457EEEB34960F4DB31" } ]
xor_digest = "D623CA4753D2197E68B87B1ACBD84CC9A056EC02F83D7E399CE2C4ACCF7934A5A0CAE68FC0EB88098AA39DA88881C7B24C137195F32DA5CA86631CB84A6BC3B2"
f()
desc = "Set 5, vector# 45"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000040000"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "2DCAD75F5621A673A471FDE8728FACF6D3146C10A0903DE12FBDCE134CC0F11B2D2ABBDBADFA19303E264011A1B9EFECAB4DFBC37E3D0F090D6B069505525D3A" }
{ "low" : 192, "hi" : 255, "bytes" : "02C401ACF6D160CC1D80E11CB4F3038A4C5B61C995CD94E15D7F95A0A18C49D5DA265F6D88D68A39B55DB3505039D13EAB9DEBD408CE7A79C375FD3FEBEF86C8" }
{ "low" : 256, "hi" : 319, "bytes" : "83D92AF769F5BF1FA894613D3DF447EBD461CFFC0CA3A9843E8441EC91DEBC67BE9162EABC5607A6D3FCAD4426EF4F9F3B42CEC8C287C194B2211DEA4549D5D5" }
{ "low" : 448, "hi" : 511, "bytes" : "D3F86930112EAFC7AA430444693BAE773F014D0798CAF3652A3432460F326DA88E82BE1E08C220B5FCBCE238B982E37D1E60DCBF1747D437D42DB21ADF5EECF2" } ]
xor_digest = "0BF26BADEFCB5BB32C43410920FF5E0F2720E8BB1C94DD5D04F0853F298C3ABA8FF670AF163C5D24BCAF13AD0A04196A2B89E82CF88846C77C77A097E234010F"
f()
desc = "Set 5, vector# 54"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000200"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "D8E137C510CDBB1C788677F44F3D3F2E4C19FCEB51E7C2ECBDB175E933F44625C7B0168E446CCCA900B9DB12D53E89E1B917A69BDB888935B3B795D743D0D0E6" }
{ "low" : 192, "hi" : 255, "bytes" : "E168F81B5BFB769F3380690D423E251E0F4BEEBE0B02F19AFFADBD94212B8063D77A665FD53F8F1A1CC682599C74F4153642EC7DADA034403A90E1E5DA40C896" }
{ "low" : 256, "hi" : 319, "bytes" : "574774CFB8452E82777371616E0AC224E29939E725B99EA8CFB4A9BF459A70D6AB1991E85E06905ACCDA8D1911F828359C4FD7614A55C1E30171934412D46B3E" }
{ "low" : 448, "hi" : 511, "bytes" : "21FE9B1F82E865CC305F04FA2C69EA976D90A41590A3BD242337D87D28E3041D3D0F74CA24A74453CB679FDFFEE45AA63B2DDE513D3F9E28E86346D9A4114CD7" } ]
xor_digest = "3E25D50331D9840FBD4F8B0FD10A9D646A5E8E0ADE57CCDECF346B2973631740382139165B0E0E78A53E4B6CAABE6517BF02B7B2905F9A64A60F412CA78E6929"
f()
desc = "Set 5, vector# 63"
key = "PI:KEY:<KEY>END_PI"
IV = "0000000000000001"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "42DCF10EA1BCBA82C88DDCDF905C9C7842A78AE57117F09CE51517C0C70063CF1F6BC955EF8806300972BD5FC715B0ED38A111610A81EBA855BB5CD1AEA0D74E" }
{ "low" : 192, "hi" : 255, "bytes" : "261E70245994E208CDF3E868A19E26D3B74DBFCB6416DE95E202228F18E56622521759F43A9A71EB5F8F705932B0448B42987CEC39A4DF03E62D2C24501B4BDE" }
{ "low" : 256, "hi" : 319, "bytes" : "9E433A4BF223AA0126807E8041179CC4760516D3537109F72124E3534A24EA7DB225C60063190FD57FF8595D60B2A8B4AE37384BB4FCD5B65234EE4FB0A1EBEA" }
{ "low" : 448, "hi" : 511, "bytes" : "3F9803DD763449758F008D77C8940F8AFB755833ED080A10513D800BA3A83B1C028A53AED0A65177C58B116E574745D0F28506A9DACD6F8A3D81613E00B12FDB" } ]
xor_digest = "C0CA35A30730FCE3A6B08FD9707EBD1C8154F54266696A99430BCA8B9F94FDD1A78CCB43CB67C58EFF3B171A38597F12AA6A424088C062B97613691B7D12CDE6"
f()
desc = "Set 6, vector# 0"
key = "PI:KEY:<KEY>END_PI"
IV = "0D74DB42A91077DE"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "05E1E7BEB697D999656BF37C1B978806735D0B903A6007BD329927EFBE1B0E2A8137C1AE291493AA83A821755BEE0B06CD14855A67E46703EBF8F3114B584CBA" }
{ "low" : 65472, "hi" : 65535, "bytes" : "1A70A37B1C9CA11CD3BF988D3EE4612D15F1A08D683FCCC6558ECF2089388B8E555E7619BF82EE71348F4F8D0D2AE464339D66BFC3A003BF229C0FC0AB6AE1C6" }
{ "low" : 65536, "hi" : 65599, "bytes" : "4ED220425F7DDB0C843232FB03A7B1C7616A50076FB056D3580DB13D2C295973D289CC335C8BC75DD87F121E85BB998166C2EF415F3F7A297E9E1BEE767F84E2" }
{ "low" : 131008, "hi" : 131071, "bytes" : "E121F8377E5146BFAE5AEC9F422F474FD3E9C685D32744A76D8B307A682FCA1B6BF790B5B51073E114732D3786B985FD4F45162488FEEB04C8F26E27E0F6B5CD" } ]
xor_digest = "620BB4C2ED20F4152F0F86053D3F55958E1FBA48F5D86B25C8F31559F31580726E7ED8525D0B9EA5264BF977507134761EF65FE195274AFPI:KEY:<KEY>END_PI000938C03BA59A7"
f()
desc = "Set 6, vector# 1"
key = "PI:KEY:<KEY>END_PI"
IV = "167DE44BB21980E7"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "EF5236C33EEEC2E337296AB237F99F56A48639744788E128BC05275D4873B9F0FAFDA8FAF24F0A61C2903373F3DE3E459928CD6F2172EA6CDBE7B0FBF45D3DAD" }
{ "low" : 65472, "hi" : 65535, "bytes" : "29412152F2750DC2F951EC969B4E9587DCD2A23DAADCBC20677DDFE89096C883E65721FC8F7BFC2D0D1FD6143D8504CB7340E06FE324CE3445081D3B7B72F3B3" }
{ "low" : 65536, "hi" : 65599, "bytes" : "49BFE800381794D264028A2E32D318E7F6FD9B377ED3A12274CE21D40CCEF04D55791AF99849989C21D00E7D4E7B9FF4D46AABC44AED676B5C69CF32BE386205" }
{ "low" : 131008, "hi" : 131071, "bytes" : "C3E16260DD666D8D8FBF1529D0E8151A931663D75FA0046132E4AD78D8BE7F8D7F41AAEFDE58BA80B962B8B68762CDF3E4B06E05D73D22CC33F1E1592D5116F4" } ]
xor_digest = "10879B33D24115E4774C71711B563B67CCD891E3825EDB58E182EC92648AE51CDDC29A6A776C0AB3182DDDA1E180D55DFAB024A3121BE45ECA59FF1A3715434C"
f()
desc = "Set 6, vector# 2"
key = "PI:KEY:<KEY>END_PI"
IV = "1F86ED54BB2289F0"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "8B354C8F8384D5591EA0FF23E7960472B494D04B2F787FC87B6569CB9021562FF5B1287A4D89FB316B69971E9B861A109CF9204572E3DE7EAB4991F4C7975427" }
{ "low" : 65472, "hi" : 65535, "bytes" : "B8B26382B081B45E135DF7F8C468ACEA56EB33EC38F292E3246F5A90233DDDC1CD977E0996641C3FA4BB42E7438EE04D8C275C57A69EEA872A440FC6EE39DB21" }
{ "low" : 65536, "hi" : 65599, "bytes" : "C0BA18C9F84D6A2E10D2CCCC041D736A943592BB626D2832A9A6CCC1005DDB9EA1694370FF15BD486B77629BB363C3B121811BCCFB18537502712A63061157D8" }
{ "low" : 131008, "hi" : 131071, "bytes" : "870355A6A03D4BC9038EA0CB2F4B8006B42D70914FBFF76A80D2567BE8404B03C1124BCE2FD863CE7438A5680D23C5E1F8ED3C8A6DB656BFF7B060B8A8966E09" } ]
xor_digest = "888FA87DB4EC690A180EF022AF6615F0677DB73B6A9E0CFACEBBB5B2A8816B2AD0338A812E03F4DFB26AF9D66160348CB9EEPI:KEY:<KEY>END_PI2B6PI:KEY:<KEY>END_PI8PI:KEY:<KEY>END_PI81A2DB79PI:KEY:<KEY>END_PIA3A68E"
f()
desc = "Set 6, vector# 3"
key = "PI:KEY:<KEY>END_PI"
IV = "288FF6PI:KEY:<KEY>END_PI9"
stream = [
{ "low" : 0, "hi" : 63, "bytes" : "71DAEE5142D0728B41B6597933EBF467E43279E30978677078941602629CBF68B73D6BD2C95F118D2B3E6EC955DABB6DC61C4143BC9A9B32B99DBE6866166DC0" }
{ "low" : 65472, "hi" : 65535, "bytes" : "906258725DDD0323D8E3098CBDAD6B7F941682A4745E4A42B3DC6EDEE565E6D9C65630610CDB14B5F110425F5A6DBF1870856183FA5B91FC177DFA721C5D6BF0" }
{ "low" : 65536, "hi" : 65599, "bytes" : "09033D9EBB07648F92858913E220FC528A10125919C891CCF8051153229B958BA9236CADF56A0F328707F7E9D5F76CCBCAF5E46A7BB9675655A426ED377D660E" }
{ "low" : 131008, "hi" : 131071, "bytes" : "F9876CA5B5136805445520CDA425508AE0E36DE975DE381F80E77D951D885801CEB354E4F45A2ED5F51DD61CE09942277F493452E0768B2624FACA4D9E0F7BE4" } ]
xor_digest = "0F4039E538DAB20139A4FEDCF07C00C45D81FD259D0C64A29799A6EE2FF2FA8B480A8A3CC7C7027A6CE0A197C44322955E4D4B00C94BF5B751E61B891F3FD906"
f()
console.log "exports.data = #{JSON.stringify out, null, 4};"
|
[
{
"context": "app.use cookieParser()\napp.use session { secret: '934b7dec-705d-4f5d-b0ee-e2d68782b67d', cookie: { maxAge: 3600000 } }\napp.use bodyParse",
"end": 1513,
"score": 0.9996007084846497,
"start": 1477,
"tag": "KEY",
"value": "934b7dec-705d-4f5d-b0ee-e2d68782b67d"
}
] | src/server/server.coffee | bipio-server/pod-server | 1 | ###
Copyright (c) 2017 InterDigital, Inc. All Rights Reserved
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
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.
###
express = require("express")
path = require("path")
moment = require('moment')
colors = require('colors')
bodyParser = require 'body-parser'
cookieParser = require 'cookie-parser'
session = require 'express-session'
request = require 'request'
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
routes = {
get: require('./routes/get')
post: require('./routes/post')
}
middleware = require('./middleware')
# Set the app
app = express()
app.config = require '../../config'
# Set the server port
app.set 'port', 3000
app.set 'version', require('../../package').version
app.set 'name', require('../../package').name
# Configure jade templates
app.set 'views', path.join __dirname, "../../views"
app.set "view engine", "jade"
# Configure client-side
app.use express.static path.join __dirname, "../../public"
app.use cookieParser()
app.use session { secret: '934b7dec-705d-4f5d-b0ee-e2d68782b67d', cookie: { maxAge: 3600000 } }
app.use bodyParser.json()
app.use bodyParser.urlencoded { extended: true }
# Create the server with timestamp
server = require('http').createServer(app)
server.listen app.get("port"), ->
timestamp = moment().format('D MMM H:mm:ss')
console.log "%s - %s v%s ("+"%s".blue+") port "+"%d".red, timestamp, app.get('name'), app.get('version'), app.get('env'), app.get('port')
# Configure middleware
app.use route, method for route, method of middleware app
# Configure normal http routes
app.get route, method for route, method of routes.get app
app.post route, method for route, method of routes.post app
# Handle crashes
process.on 'SIGINT', ->
setTimeout ->
console.error "Forcefully shutting down".red
process.exit(1)
, 1000
module.exports = app
| 76136 | ###
Copyright (c) 2017 InterDigital, Inc. All Rights Reserved
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
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.
###
express = require("express")
path = require("path")
moment = require('moment')
colors = require('colors')
bodyParser = require 'body-parser'
cookieParser = require 'cookie-parser'
session = require 'express-session'
request = require 'request'
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
routes = {
get: require('./routes/get')
post: require('./routes/post')
}
middleware = require('./middleware')
# Set the app
app = express()
app.config = require '../../config'
# Set the server port
app.set 'port', 3000
app.set 'version', require('../../package').version
app.set 'name', require('../../package').name
# Configure jade templates
app.set 'views', path.join __dirname, "../../views"
app.set "view engine", "jade"
# Configure client-side
app.use express.static path.join __dirname, "../../public"
app.use cookieParser()
app.use session { secret: '<KEY>', cookie: { maxAge: 3600000 } }
app.use bodyParser.json()
app.use bodyParser.urlencoded { extended: true }
# Create the server with timestamp
server = require('http').createServer(app)
server.listen app.get("port"), ->
timestamp = moment().format('D MMM H:mm:ss')
console.log "%s - %s v%s ("+"%s".blue+") port "+"%d".red, timestamp, app.get('name'), app.get('version'), app.get('env'), app.get('port')
# Configure middleware
app.use route, method for route, method of middleware app
# Configure normal http routes
app.get route, method for route, method of routes.get app
app.post route, method for route, method of routes.post app
# Handle crashes
process.on 'SIGINT', ->
setTimeout ->
console.error "Forcefully shutting down".red
process.exit(1)
, 1000
module.exports = app
| true | ###
Copyright (c) 2017 InterDigital, Inc. All Rights Reserved
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
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.
###
express = require("express")
path = require("path")
moment = require('moment')
colors = require('colors')
bodyParser = require 'body-parser'
cookieParser = require 'cookie-parser'
session = require 'express-session'
request = require 'request'
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
routes = {
get: require('./routes/get')
post: require('./routes/post')
}
middleware = require('./middleware')
# Set the app
app = express()
app.config = require '../../config'
# Set the server port
app.set 'port', 3000
app.set 'version', require('../../package').version
app.set 'name', require('../../package').name
# Configure jade templates
app.set 'views', path.join __dirname, "../../views"
app.set "view engine", "jade"
# Configure client-side
app.use express.static path.join __dirname, "../../public"
app.use cookieParser()
app.use session { secret: 'PI:KEY:<KEY>END_PI', cookie: { maxAge: 3600000 } }
app.use bodyParser.json()
app.use bodyParser.urlencoded { extended: true }
# Create the server with timestamp
server = require('http').createServer(app)
server.listen app.get("port"), ->
timestamp = moment().format('D MMM H:mm:ss')
console.log "%s - %s v%s ("+"%s".blue+") port "+"%d".red, timestamp, app.get('name'), app.get('version'), app.get('env'), app.get('port')
# Configure middleware
app.use route, method for route, method of middleware app
# Configure normal http routes
app.get route, method for route, method of routes.get app
app.post route, method for route, method of routes.post app
# Handle crashes
process.on 'SIGINT', ->
setTimeout ->
console.error "Forcefully shutting down".red
process.exit(1)
, 1000
module.exports = app
|
[
{
"context": "ntact'}\n {id: '512ef4805a67a8c507000001', name: 'Nick'}\n {id: '5162fab9c92b4c751e000274', name: 'Scott",
"end": 860,
"score": 0.9998176693916321,
"start": 856,
"tag": "NAME",
"value": "Nick"
},
{
"context": "'Nick'}\n {id: '5162fab9c92b4c751e000274', name: 'Scott'}... | app/views/user/JobProfileView.coffee | rishiloyola/codecombat | 1 | UserView = require 'views/common/UserView'
template = require 'templates/account/job-profile-view'
User = require 'models/User'
LevelSession = require 'models/LevelSession'
CocoCollection = require 'collections/CocoCollection'
{me} = require 'core/auth'
JobProfileContactModal = require 'views/modal/JobProfileContactModal'
JobProfileTreemaView = require 'views/account/JobProfileTreemaView'
UserRemark = require 'models/UserRemark'
forms = require 'core/forms'
ModelModal = require 'views/modal/ModelModal'
JobProfileCodeModal = require './JobProfileCodeModal'
require 'vendor/treema'
class LevelSessionsCollection extends CocoCollection
url: -> "/db/user/#{@userID}/level.sessions/employer"
model: LevelSession
constructor: (@userID) ->
super()
adminContacts = [
{id: '', name: 'Assign a Contact'}
{id: '512ef4805a67a8c507000001', name: 'Nick'}
{id: '5162fab9c92b4c751e000274', name: 'Scott'}
{id: '51eb2714fa058cb20d0006ef', name: 'Michael'}
{id: '51538fdb812dd9af02000001', name: 'George'}
{id: '52a57252a89409700d0000d9', name: 'Ignore'}
]
module.exports = class JobProfileView extends UserView
id: 'profile-view'
template: template
showBackground: false
usesSocialMedia: true
subscriptions: {}
events:
'click #toggle-editing': 'toggleEditing'
'click #toggle-job-profile-active': 'toggleJobProfileActive'
'click #toggle-job-profile-approved': 'toggleJobProfileApproved'
'click #save-notes-button': 'onJobProfileNotesChanged'
'click #contact-candidate': 'onContactCandidate'
'click #enter-espionage-mode': 'enterEspionageMode'
'click #open-model-modal': 'openModelModal'
'click .editable-profile .profile-photo': 'onEditProfilePhoto'
'click .editable-profile .project-image': 'onEditProjectImage'
'click .editable-profile .editable-display': 'onEditSection'
'click .editable-profile .save-section': 'onSaveSection'
'click .editable-profile .glyphicon-remove': 'onCancelSectionEdit'
'change .editable-profile .editable-array input': 'onEditArray'
'keyup .editable-profile .editable-array input': 'onEditArray'
'click .editable-profile a': 'onClickLinkWhileEditing'
'change #admin-contact': 'onAdminContactChanged'
'click .session-link': 'onSessionLinkPressed'
constructor: (options, userID) ->
@onJobProfileNotesChanged = _.debounce @onJobProfileNotesChanged, 1000
@onRemarkChanged = _.debounce @onRemarkChanged, 1000
require('core/services/filepicker')() # Initialize if needed
super userID, options
onLoaded: ->
@finishInit() unless @destroyed
super()
finishInit: ->
return unless @userID
@uploadFilePath = "db/user/#{@userID}"
if @user?.get('firstName')
jobProfile = @user.get('jobProfile')
jobProfile ?= {}
if not jobProfile.name
jobProfile.name = (@user.get('firstName') + ' ' + @user.get('lastName')).trim()
@user.set('jobProfile', jobProfile)
@highlightedContainers = []
if me.isAdmin() or 'employer' in me.get('permissions', true)
$.post "/db/user/#{me.id}/track/view_candidate"
$.post "/db/user/#{@userID}/track/viewed_by_employer" unless me.isAdmin()
@sessions = @supermodel.loadCollection(new LevelSessionsCollection(@user.id), 'candidate_sessions').model
@listenToOnce @sessions, 'sync', => @render?()
if me.isAdmin()
# Mimicking how the VictoryModal fetches LevelFeedback
@remark = new UserRemark()
@remark.setURL "/db/user/#{@userID}/remark"
@remark.fetch()
@listenToOnce @remark, 'sync', @onRemarkLoaded
@listenToOnce @remark, 'error', @onRemarkNotFound
onRemarkLoaded: ->
@remark.setURL "/db/user.remark/#{@remark.id}"
@render()
onRemarkNotFound: ->
@remark = new UserRemark() # hmm, why do we create a new one here?
@remark.set 'user', @userID
@remark.set 'userName', name if name = @user.get('name')
jobProfileSchema: -> @user.schema().properties.jobProfile.properties
getRenderData: ->
context = super()
context.userID = @userID
context.profile = @user.get('jobProfile', true)
context.rawProfile = @user.get('jobProfile') or {}
context.user = @user
context.myProfile = @isMe()
context.allowedToViewJobProfile = @user and (me.isAdmin() or 'employer' in me.get('permissions', true) or (context.myProfile && !me.get('anonymous')))
context.allowedToEditJobProfile = @user and (me.isAdmin() or (context.myProfile && !me.get('anonymous')))
context.profileApproved = @user?.get 'jobProfileApproved'
context.progress = @progress ? @updateProgress()
@editing ?= context.myProfile and context.progress < 0.8
context.editing = @editing
context.marked = marked
context.moment = moment
context.iconForLink = @iconForLink
if links = context.profile.links
links = ($.extend(true, {}, link) for link in links)
link.icon = @iconForLink link for link in links
context.profileLinks = _.sortBy links, (link) -> not link.icon # icons first
if @sessions
context.sessions = (s.attributes for s in @sessions.models when (s.get('submitted') or (s.get('levelID') is 'gridmancer') and s.get('code')?.thoktar?.plan?.length isnt 942)) # no default code
context.sessions.sort (a, b) -> (b.playtime ? 0) - (a.playtime ? 0)
else
context.sessions = []
context.adminContacts = adminContacts
context.remark = @remark
context
afterRender: ->
super()
if me.get('employerAt')
@$el.addClass 'viewed-by-employer'
return unless @user
unless @user.get('jobProfile')?.projects?.length or @editing
@$el.find('.right-column').hide()
@$el.find('.middle-column').addClass('double-column')
unless @editing
@$el.find('.editable-display').attr('title', '')
@initializeAutocomplete()
highlightNext = @highlightNext ? true
justSavedSection = @$el.find('#' + @justSavedSectionID).addClass 'just-saved'
_.defer =>
@progress = @updateProgress highlightNext
_.delay ->
justSavedSection.removeClass 'just-saved', duration: 1500, easing: 'easeOutQuad'
, 500
if me.isAdmin() and @user and @remark
visibleSettings = ['history', 'tasks']
data = _.pick (@remark.attributes), (value, key) -> key in visibleSettings
data.history ?= []
data.tasks ?= []
schema = _.cloneDeep @remark.schema()
schema.properties = _.pick schema.properties, (value, key) => key in visibleSettings
schema.required = _.intersection (schema.required ? []), visibleSettings
treemaOptions =
filePath: "db/user/#{@userID}"
schema: schema
data: data
aceUseWrapMode: true
callbacks: {change: @onRemarkChanged}
@remarkTreema = @$el.find('#remark-treema').treema treemaOptions
@remarkTreema?.build()
@remarkTreema?.open(3)
onRemarkChanged: (e) =>
return unless @remarkTreema.isValid()
for key in ['history', 'tasks']
val = _.filter(@remarkTreema.get(key), (entry) -> entry?.content or entry?.action)
entry.date ?= (new Date()).toISOString() for entry in val if key is 'history'
@remark.set key, val
@saveRemark()
initializeAutocomplete: (container) ->
(container ? @$el).find('input[data-autocomplete]').each ->
$(@).autocomplete(source: JobProfileTreemaView[$(@).data('autocomplete')], minLength: parseInt($(@).data('autocomplete-min-length')), delay: 0, autoFocus: true)
toggleEditing: ->
@editing = not @editing
@render()
@saveEdits()
toggleJobProfileApproved: ->
return unless me.isAdmin()
approved = not @user.get 'jobProfileApproved'
@user.set 'jobProfileApproved', approved
res = @user.patch()
res.success (model, response, options) => @render()
toggleJobProfileActive: ->
active = not @user.get('jobProfile').active
@user.get('jobProfile').active = active
@saveEdits()
if active and not (me.isAdmin() or @stackLed)
$.post '/stacklead'
@stackLed = true
enterEspionageMode: ->
postData = emailLower: @user.get('email').toLowerCase(), usernameLower: @user.get('name').toLowerCase()
$.ajax
type: 'POST',
url: '/auth/spy'
data: postData
success: @espionageSuccess
espionageSuccess: (model) ->
window.location.reload()
openModelModal: (e) ->
@openModalView new ModelModal models: [@user]
onJobProfileNotesChanged: (e) =>
notes = @$el.find('#job-profile-notes').val()
@user.set 'jobProfileNotes', notes
@user.save {jobProfileNotes: notes}, {patch: true, type: 'PUT'}
iconForLink: (link) ->
icons = [
{icon: 'facebook', name: 'Facebook', domain: /facebook\.com/, match: /facebook/i}
{icon: 'twitter', name: 'Twitter', domain: /twitter\.com/, match: /twitter/i}
{icon: 'github', name: 'GitHub', domain: /github\.(com|io)/, match: /github/i}
{icon: 'gplus', name: 'Google Plus', domain: /plus\.google\.com/, match: /(google|^g).?(\+|plus)/i}
{icon: 'linkedin', name: 'LinkedIn', domain: /linkedin\.com/, match: /(google|^g).?(\+|plus)/i}
]
for icon in icons
if (link.name.search(icon.match) isnt -1) or (link.link.search(icon.domain) isnt -1)
icon.url = "/images/pages/account/profile/icon_#{icon.icon}.png"
return icon
null
onContactCandidate: (e) ->
@openModalView new JobProfileContactModal recipientID: @user.id, recipientUserName: @user.get('name')
showErrors: (errors) ->
section = @$el.find '.saving'
console.error 'Couldn\'t save because of validation errors:', errors
section.removeClass 'saving'
forms.clearFormAlerts section
# This is pretty lame, since we don't easily match which field had the error like forms.applyErrorsToForm can.
section.find('form').addClass('has-error').find('.save-section').before($("<span class='help-block error-help-block'>#{errors[0].message}</span>"))
saveEdits: (highlightNext) ->
errors = @user.validate()
return @showErrors errors if errors
jobProfile = @user.get('jobProfile')
jobProfile.updated = (new Date()).toISOString() if @user is me
@user.set 'jobProfile', jobProfile
return unless res = @user.save()
res.error =>
return if @destroyed
@showErrors [message: res.responseText]
res.success (model, response, options) =>
return if @destroyed
@justSavedSectionID = @$el.find('.editable-section.saving').removeClass('saving').attr('id')
@highlightNext = highlightNext
@render()
@highlightNext = false
@justSavedSectionID = null
onEditProfilePhoto: (e) ->
onSaving = =>
@$el.find('.profile-photo').addClass('saving')
onSaved = (uploadingPath) =>
@user.get('jobProfile').photoURL = uploadingPath
@saveEdits()
filepicker.pick {mimetypes: 'image/*'}, @onImageChosen(onSaving, onSaved)
onEditProjectImage: (e) ->
img = $(e.target)
onSaving = =>
img.addClass('saving')
onSaved = (uploadingPath) =>
img.parent().find('input').val(uploadingPath)
img.css('background-image', "url('/file/#{uploadingPath}')")
img.removeClass('saving')
filepicker.pick {mimetypes: 'image/*'}, @onImageChosen(onSaving, onSaved)
formatImagePostData: (inkBlob) ->
url: inkBlob.url, filename: inkBlob.filename, mimetype: inkBlob.mimetype, path: @uploadFilePath, force: true
onImageChosen: (onSaving, onSaved) ->
(inkBlob) =>
onSaving()
uploadingPath = [@uploadFilePath, inkBlob.filename].join('/')
$.ajax '/file', type: 'POST', data: @formatImagePostData(inkBlob), success: @onImageUploaded(onSaved, uploadingPath)
onImageUploaded: (onSaved, uploadingPath) ->
(e) =>
onSaved uploadingPath
onEditSection: (e) ->
@$el.find('.emphasized').removeClass('emphasized')
section = $(e.target).closest('.editable-section').removeClass 'deemphasized'
section.find('.editable-form').show().find('select, input, textarea').first().focus()
section.find('.editable-display').hide()
@$el.find('.editable-section').not(section).addClass 'deemphasized'
column = section.closest('.full-height-column')
@$el.find('.full-height-column').not(column).addClass 'deemphasized'
onCancelSectionEdit: (e) ->
@render()
onSaveSection: (e) ->
e.preventDefault()
section = $(e.target).closest('.editable-section')
form = $(e.target).closest('form')
isEmpty = @arrayItemIsEmpty
section.find('.array-item').each ->
$(@).remove() if isEmpty @
resetOnce = false # We have to clear out arrays if we're going to redo them
serialized = form.serializeArray()
jobProfile = @user.get('jobProfile') or {}
jobProfile[prop] ?= [] for prop in ['links', 'skills', 'work', 'education', 'projects']
rootPropertiesSeen = {}
for field in serialized
keyChain = @extractFieldKeyChain field.name
value = @extractFieldValue keyChain[0], field.value
parent = jobProfile
for key, i in keyChain
rootPropertiesSeen[key] = true unless i
break if i is keyChain.length - 1
parent[key] ?= {}
child = parent[key]
if _.isArray(child) and not resetOnce
child = parent[key] = []
resetOnce = true
else unless child?
child = parent[key] = {}
parent = child
if key is 'link' and keyChain[0] is 'projects' and not value
delete parent[key]
else
parent[key] = value
form.find('.editable-array').each ->
key = $(@).data('property')
unless rootPropertiesSeen[key]
jobProfile[key] = []
if section.hasClass('projects-container') and not section.find('.array-item').length
jobProfile.projects = []
section.addClass 'saving'
@user.set('jobProfile', jobProfile)
@saveEdits true
extractFieldKeyChain: (key) ->
# 'root[projects][0][name]' -> ['projects', '0', 'name']
key.replace(/^root/, '').replace(/\[(.*?)\]/g, '.$1').replace(/^\./, '').split(/\./)
extractFieldValue: (key, value) ->
switch key
when 'active' then Boolean value
when 'experience' then parseInt value or '0'
else value
arrayItemIsEmpty: (arrayItem) ->
for input in $(arrayItem).find('input[type!=hidden], textarea')
return false if $(input).val().trim()
true
onEditArray: (e) ->
# We make sure there's always an empty array item at the end for the user to add to, deleting interstitial empties.
array = $(e.target).closest('.editable-array')
arrayItems = array.find('.array-item')
toRemove = []
for arrayItem, index in arrayItems
empty = @arrayItemIsEmpty arrayItem
if index is arrayItems.length - 1
lastEmpty = empty
else if empty and not $(arrayItem).find('input:focus, textarea:focus').length
toRemove.unshift index
$(arrayItems[emptyIndex]).remove() for emptyIndex in toRemove
unless lastEmpty
clone = $(arrayItem).clone(false)
clone.find('input').each -> $(@).val('')
clone.find('textarea').each -> $(@).text('')
array.append clone
@initializeAutocomplete clone
for arrayItem, index in array.find('.array-item')
for input in $(arrayItem).find('input, textarea')
$(input).attr('name', $(input).attr('name').replace(/\[\d+\]/, "[#{index}]"))
onClickLinkWhileEditing: (e) ->
e.preventDefault()
onAdminContactChanged: (e) ->
newContact = @$el.find('#admin-contact').val()
newContactName = if newContact then _.find(adminContacts, id: newContact).name else ''
@remark.set 'contact', newContact
@remark.set 'contactName', newContactName
@saveRemark()
saveRemark: ->
@remark.set 'user', @user.id
@remark.set 'userName', @user.get('name')
if errors = @remark.validate()
return console.error 'UserRemark', @remark, 'failed validation with errors:', errors
res = @remark.save()
res.error =>
return if @destroyed
console.error 'UserRemark', @remark, 'failed to save with error:', res.responseText
res.success (model, response, options) =>
return if @destroyed
console.log 'Saved UserRemark', @remark, 'with response', response
updateProgress: (highlightNext) ->
return unless @user?.loaded and @sessions?.loaded
completed = 0
totalWeight = 0
next = null
for metric in metrics = @getProgressMetrics()
done = metric.fn()
completed += metric.weight if done
totalWeight += metric.weight
next = metric unless next or done
progress = Math.round 100 * completed / totalWeight
bar = @$el.find('.profile-completion-progress .progress-bar')
bar.css 'width', "#{progress}%"
if next
text = ''
t = $.i18n.t
text = "#{progress}% #{t 'account_profile.complete'}. #{t 'account_profile.next'}: #{next.name}"
bar.parent().show().find('.progress-text').text text
if highlightNext and next?.container and not (next.container in @highlightedContainers)
@highlightedContainers.push next.container
@$el.find(next.container).addClass 'emphasized'
#@onEditSection target: next.container
#$('#page-container').scrollTop 0
else
bar.parent().hide()
completed / totalWeight
getProgressMetrics: ->
schema = me.schema().properties.jobProfile
jobProfile = @user.get('jobProfile') ? {}
exists = (field) -> -> jobProfile[field]
modified = (field) -> -> jobProfile[field] and jobProfile[field] isnt schema.properties[field].default
listStarted = (field, subfields) -> -> jobProfile[field]?.length and _.every subfields, (subfield) -> jobProfile[field][0][subfield]
t = $.i18n.t
@progressMetrics = [
{name: t('account_profile.next_name'), weight: 1, container: '#name-container', fn: modified 'name'}
{name: t('account_profile.next_short_description'), weight: 2, container: '#short-description-container', fn: modified 'shortDescription'}
{name: t('account_profile.next_skills'), weight: 2, container: '#skills-container', fn: -> jobProfile.skills?.length >= 5}
{name: t('account_profile.next_long_description'), weight: 3, container: '#long-description-container', fn: modified 'longDescription'}
{name: t('account_profile.next_work'), weight: 3, container: '#work-container', fn: listStarted 'work', ['role', 'employer']}
{name: t('account_profile.next_education'), weight: 3, container: '#education-container', fn: listStarted 'education', ['degree', 'school']}
{name: t('account_profile.next_projects'), weight: 3, container: '#projects-container', fn: listStarted 'projects', ['name']}
{name: t('account_profile.next_city'), weight: 1, container: '#basic-info-container', fn: modified 'city'}
{name: t('account_profile.next_country'), weight: 0, container: '#basic-info-container', fn: exists 'country'}
{name: t('account_profile.next_links'), weight: 2, container: '#links-container', fn: listStarted 'links', ['link', 'name']}
{name: t('account_profile.next_photo'), weight: 2, container: '#profile-photo-container', fn: modified 'photoURL'}
{name: t('account_profile.next_active'), weight: 1, fn: modified 'active'}
]
onSessionLinkPressed: (e) ->
sessionID = $(e.target).closest('.session-link').data('session-id')
session = _.find @sessions.models, (session) -> session.id is sessionID
modal = new JobProfileCodeModal({session:session})
@openModalView modal
destroy: ->
@remarkTreema?.destroy()
super()
| 138826 | UserView = require 'views/common/UserView'
template = require 'templates/account/job-profile-view'
User = require 'models/User'
LevelSession = require 'models/LevelSession'
CocoCollection = require 'collections/CocoCollection'
{me} = require 'core/auth'
JobProfileContactModal = require 'views/modal/JobProfileContactModal'
JobProfileTreemaView = require 'views/account/JobProfileTreemaView'
UserRemark = require 'models/UserRemark'
forms = require 'core/forms'
ModelModal = require 'views/modal/ModelModal'
JobProfileCodeModal = require './JobProfileCodeModal'
require 'vendor/treema'
class LevelSessionsCollection extends CocoCollection
url: -> "/db/user/#{@userID}/level.sessions/employer"
model: LevelSession
constructor: (@userID) ->
super()
adminContacts = [
{id: '', name: 'Assign a Contact'}
{id: '512ef4805a67a8c507000001', name: '<NAME>'}
{id: '5162fab9c92b4c751e000274', name: '<NAME>'}
{id: '51eb2714fa058cb20d0006ef', name: '<NAME>'}
{id: '51538fdb812dd9af02000001', name: '<NAME>'}
{id: '52a57252a89409700d0000d9', name: 'Ignore'}
]
module.exports = class JobProfileView extends UserView
id: 'profile-view'
template: template
showBackground: false
usesSocialMedia: true
subscriptions: {}
events:
'click #toggle-editing': 'toggleEditing'
'click #toggle-job-profile-active': 'toggleJobProfileActive'
'click #toggle-job-profile-approved': 'toggleJobProfileApproved'
'click #save-notes-button': 'onJobProfileNotesChanged'
'click #contact-candidate': 'onContactCandidate'
'click #enter-espionage-mode': 'enterEspionageMode'
'click #open-model-modal': 'openModelModal'
'click .editable-profile .profile-photo': 'onEditProfilePhoto'
'click .editable-profile .project-image': 'onEditProjectImage'
'click .editable-profile .editable-display': 'onEditSection'
'click .editable-profile .save-section': 'onSaveSection'
'click .editable-profile .glyphicon-remove': 'onCancelSectionEdit'
'change .editable-profile .editable-array input': 'onEditArray'
'keyup .editable-profile .editable-array input': 'onEditArray'
'click .editable-profile a': 'onClickLinkWhileEditing'
'change #admin-contact': 'onAdminContactChanged'
'click .session-link': 'onSessionLinkPressed'
constructor: (options, userID) ->
@onJobProfileNotesChanged = _.debounce @onJobProfileNotesChanged, 1000
@onRemarkChanged = _.debounce @onRemarkChanged, 1000
require('core/services/filepicker')() # Initialize if needed
super userID, options
onLoaded: ->
@finishInit() unless @destroyed
super()
finishInit: ->
return unless @userID
@uploadFilePath = "db/user/#{@userID}"
if @user?.get('firstName')
jobProfile = @user.get('jobProfile')
jobProfile ?= {}
if not jobProfile.name
jobProfile.name = (@user.get('firstName') + ' ' + @user.get('lastName')).trim()
@user.set('jobProfile', jobProfile)
@highlightedContainers = []
if me.isAdmin() or 'employer' in me.get('permissions', true)
$.post "/db/user/#{me.id}/track/view_candidate"
$.post "/db/user/#{@userID}/track/viewed_by_employer" unless me.isAdmin()
@sessions = @supermodel.loadCollection(new LevelSessionsCollection(@user.id), 'candidate_sessions').model
@listenToOnce @sessions, 'sync', => @render?()
if me.isAdmin()
# Mimicking how the VictoryModal fetches LevelFeedback
@remark = new UserRemark()
@remark.setURL "/db/user/#{@userID}/remark"
@remark.fetch()
@listenToOnce @remark, 'sync', @onRemarkLoaded
@listenToOnce @remark, 'error', @onRemarkNotFound
onRemarkLoaded: ->
@remark.setURL "/db/user.remark/#{@remark.id}"
@render()
onRemarkNotFound: ->
@remark = new UserRemark() # hmm, why do we create a new one here?
@remark.set 'user', @userID
@remark.set 'userName', name if name = @user.get('name')
jobProfileSchema: -> @user.schema().properties.jobProfile.properties
getRenderData: ->
context = super()
context.userID = @userID
context.profile = @user.get('jobProfile', true)
context.rawProfile = @user.get('jobProfile') or {}
context.user = @user
context.myProfile = @isMe()
context.allowedToViewJobProfile = @user and (me.isAdmin() or 'employer' in me.get('permissions', true) or (context.myProfile && !me.get('anonymous')))
context.allowedToEditJobProfile = @user and (me.isAdmin() or (context.myProfile && !me.get('anonymous')))
context.profileApproved = @user?.get 'jobProfileApproved'
context.progress = @progress ? @updateProgress()
@editing ?= context.myProfile and context.progress < 0.8
context.editing = @editing
context.marked = marked
context.moment = moment
context.iconForLink = @iconForLink
if links = context.profile.links
links = ($.extend(true, {}, link) for link in links)
link.icon = @iconForLink link for link in links
context.profileLinks = _.sortBy links, (link) -> not link.icon # icons first
if @sessions
context.sessions = (s.attributes for s in @sessions.models when (s.get('submitted') or (s.get('levelID') is 'gridmancer') and s.get('code')?.thoktar?.plan?.length isnt 942)) # no default code
context.sessions.sort (a, b) -> (b.playtime ? 0) - (a.playtime ? 0)
else
context.sessions = []
context.adminContacts = adminContacts
context.remark = @remark
context
afterRender: ->
super()
if me.get('employerAt')
@$el.addClass 'viewed-by-employer'
return unless @user
unless @user.get('jobProfile')?.projects?.length or @editing
@$el.find('.right-column').hide()
@$el.find('.middle-column').addClass('double-column')
unless @editing
@$el.find('.editable-display').attr('title', '')
@initializeAutocomplete()
highlightNext = @highlightNext ? true
justSavedSection = @$el.find('#' + @justSavedSectionID).addClass 'just-saved'
_.defer =>
@progress = @updateProgress highlightNext
_.delay ->
justSavedSection.removeClass 'just-saved', duration: 1500, easing: 'easeOutQuad'
, 500
if me.isAdmin() and @user and @remark
visibleSettings = ['history', 'tasks']
data = _.pick (@remark.attributes), (value, key) -> key in visibleSettings
data.history ?= []
data.tasks ?= []
schema = _.cloneDeep @remark.schema()
schema.properties = _.pick schema.properties, (value, key) => key in visibleSettings
schema.required = _.intersection (schema.required ? []), visibleSettings
treemaOptions =
filePath: "db/user/#{@userID}"
schema: schema
data: data
aceUseWrapMode: true
callbacks: {change: @onRemarkChanged}
@remarkTreema = @$el.find('#remark-treema').treema treemaOptions
@remarkTreema?.build()
@remarkTreema?.open(3)
onRemarkChanged: (e) =>
return unless @remarkTreema.isValid()
for key in ['history', 'tasks']
val = _.filter(@remarkTreema.get(key), (entry) -> entry?.content or entry?.action)
entry.date ?= (new Date()).toISOString() for entry in val if key is 'history'
@remark.set key, val
@saveRemark()
initializeAutocomplete: (container) ->
(container ? @$el).find('input[data-autocomplete]').each ->
$(@).autocomplete(source: JobProfileTreemaView[$(@).data('autocomplete')], minLength: parseInt($(@).data('autocomplete-min-length')), delay: 0, autoFocus: true)
toggleEditing: ->
@editing = not @editing
@render()
@saveEdits()
toggleJobProfileApproved: ->
return unless me.isAdmin()
approved = not @user.get 'jobProfileApproved'
@user.set 'jobProfileApproved', approved
res = @user.patch()
res.success (model, response, options) => @render()
toggleJobProfileActive: ->
active = not @user.get('jobProfile').active
@user.get('jobProfile').active = active
@saveEdits()
if active and not (me.isAdmin() or @stackLed)
$.post '/stacklead'
@stackLed = true
enterEspionageMode: ->
postData = emailLower: @user.get('email').toLowerCase(), usernameLower: @user.get('name').toLowerCase()
$.ajax
type: 'POST',
url: '/auth/spy'
data: postData
success: @espionageSuccess
espionageSuccess: (model) ->
window.location.reload()
openModelModal: (e) ->
@openModalView new ModelModal models: [@user]
onJobProfileNotesChanged: (e) =>
notes = @$el.find('#job-profile-notes').val()
@user.set 'jobProfileNotes', notes
@user.save {jobProfileNotes: notes}, {patch: true, type: 'PUT'}
iconForLink: (link) ->
icons = [
{icon: 'facebook', name: 'Facebook', domain: /facebook\.com/, match: /facebook/i}
{icon: 'twitter', name: 'Twitter', domain: /twitter\.com/, match: /twitter/i}
{icon: 'github', name: 'GitHub', domain: /github\.(com|io)/, match: /github/i}
{icon: 'gplus', name: 'Google Plus', domain: /plus\.google\.com/, match: /(google|^g).?(\+|plus)/i}
{icon: 'linkedin', name: 'LinkedIn', domain: /linkedin\.com/, match: /(google|^g).?(\+|plus)/i}
]
for icon in icons
if (link.name.search(icon.match) isnt -1) or (link.link.search(icon.domain) isnt -1)
icon.url = "/images/pages/account/profile/icon_#{icon.icon}.png"
return icon
null
onContactCandidate: (e) ->
@openModalView new JobProfileContactModal recipientID: @user.id, recipientUserName: @user.get('name')
showErrors: (errors) ->
section = @$el.find '.saving'
console.error 'Couldn\'t save because of validation errors:', errors
section.removeClass 'saving'
forms.clearFormAlerts section
# This is pretty lame, since we don't easily match which field had the error like forms.applyErrorsToForm can.
section.find('form').addClass('has-error').find('.save-section').before($("<span class='help-block error-help-block'>#{errors[0].message}</span>"))
saveEdits: (highlightNext) ->
errors = @user.validate()
return @showErrors errors if errors
jobProfile = @user.get('jobProfile')
jobProfile.updated = (new Date()).toISOString() if @user is me
@user.set 'jobProfile', jobProfile
return unless res = @user.save()
res.error =>
return if @destroyed
@showErrors [message: res.responseText]
res.success (model, response, options) =>
return if @destroyed
@justSavedSectionID = @$el.find('.editable-section.saving').removeClass('saving').attr('id')
@highlightNext = highlightNext
@render()
@highlightNext = false
@justSavedSectionID = null
onEditProfilePhoto: (e) ->
onSaving = =>
@$el.find('.profile-photo').addClass('saving')
onSaved = (uploadingPath) =>
@user.get('jobProfile').photoURL = uploadingPath
@saveEdits()
filepicker.pick {mimetypes: 'image/*'}, @onImageChosen(onSaving, onSaved)
onEditProjectImage: (e) ->
img = $(e.target)
onSaving = =>
img.addClass('saving')
onSaved = (uploadingPath) =>
img.parent().find('input').val(uploadingPath)
img.css('background-image', "url('/file/#{uploadingPath}')")
img.removeClass('saving')
filepicker.pick {mimetypes: 'image/*'}, @onImageChosen(onSaving, onSaved)
formatImagePostData: (inkBlob) ->
url: inkBlob.url, filename: inkBlob.filename, mimetype: inkBlob.mimetype, path: @uploadFilePath, force: true
onImageChosen: (onSaving, onSaved) ->
(inkBlob) =>
onSaving()
uploadingPath = [@uploadFilePath, inkBlob.filename].join('/')
$.ajax '/file', type: 'POST', data: @formatImagePostData(inkBlob), success: @onImageUploaded(onSaved, uploadingPath)
onImageUploaded: (onSaved, uploadingPath) ->
(e) =>
onSaved uploadingPath
onEditSection: (e) ->
@$el.find('.emphasized').removeClass('emphasized')
section = $(e.target).closest('.editable-section').removeClass 'deemphasized'
section.find('.editable-form').show().find('select, input, textarea').first().focus()
section.find('.editable-display').hide()
@$el.find('.editable-section').not(section).addClass 'deemphasized'
column = section.closest('.full-height-column')
@$el.find('.full-height-column').not(column).addClass 'deemphasized'
onCancelSectionEdit: (e) ->
@render()
onSaveSection: (e) ->
e.preventDefault()
section = $(e.target).closest('.editable-section')
form = $(e.target).closest('form')
isEmpty = @arrayItemIsEmpty
section.find('.array-item').each ->
$(@).remove() if isEmpty @
resetOnce = false # We have to clear out arrays if we're going to redo them
serialized = form.serializeArray()
jobProfile = @user.get('jobProfile') or {}
jobProfile[prop] ?= [] for prop in ['links', 'skills', 'work', 'education', 'projects']
rootPropertiesSeen = {}
for field in serialized
keyChain = @extractFieldKeyChain field.name
value = @extractFieldValue keyChain[0], field.value
parent = jobProfile
for key, i in keyChain
rootPropertiesSeen[key] = true unless i
break if i is keyChain.length - 1
parent[key] ?= {}
child = parent[key]
if _.isArray(child) and not resetOnce
child = parent[key] = []
resetOnce = true
else unless child?
child = parent[key] = {}
parent = child
if key is '<KEY>' and keyChain[0] is '<KEY>' and not value
delete parent[key]
else
parent[key] = value
form.find('.editable-array').each ->
key = $(@).data('property')
unless rootPropertiesSeen[key]
jobProfile[key] = []
if section.hasClass('projects-container') and not section.find('.array-item').length
jobProfile.projects = []
section.addClass 'saving'
@user.set('jobProfile', jobProfile)
@saveEdits true
extractFieldKeyChain: (key) ->
# 'root[projects][0][name]' -> ['projects', '0', 'name']
key.replace(/^root/, '').replace(/\[(.*?)\]/g, '.$1').replace(/^\./, '').split(/\./)
extractFieldValue: (key, value) ->
switch key
when 'active' then Boolean value
when 'experience' then parseInt value or '0'
else value
arrayItemIsEmpty: (arrayItem) ->
for input in $(arrayItem).find('input[type!=hidden], textarea')
return false if $(input).val().trim()
true
onEditArray: (e) ->
# We make sure there's always an empty array item at the end for the user to add to, deleting interstitial empties.
array = $(e.target).closest('.editable-array')
arrayItems = array.find('.array-item')
toRemove = []
for arrayItem, index in arrayItems
empty = @arrayItemIsEmpty arrayItem
if index is arrayItems.length - 1
lastEmpty = empty
else if empty and not $(arrayItem).find('input:focus, textarea:focus').length
toRemove.unshift index
$(arrayItems[emptyIndex]).remove() for emptyIndex in toRemove
unless lastEmpty
clone = $(arrayItem).clone(false)
clone.find('input').each -> $(@).val('')
clone.find('textarea').each -> $(@).text('')
array.append clone
@initializeAutocomplete clone
for arrayItem, index in array.find('.array-item')
for input in $(arrayItem).find('input, textarea')
$(input).attr('name', $(input).attr('name').replace(/\[\d+\]/, "[#{index}]"))
onClickLinkWhileEditing: (e) ->
e.preventDefault()
onAdminContactChanged: (e) ->
newContact = @$el.find('#admin-contact').val()
newContactName = if newContact then _.find(adminContacts, id: newContact).name else ''
@remark.set 'contact', newContact
@remark.set 'contactName', newContactName
@saveRemark()
saveRemark: ->
@remark.set 'user', @user.id
@remark.set 'userName', @user.get('name')
if errors = @remark.validate()
return console.error 'UserRemark', @remark, 'failed validation with errors:', errors
res = @remark.save()
res.error =>
return if @destroyed
console.error 'UserRemark', @remark, 'failed to save with error:', res.responseText
res.success (model, response, options) =>
return if @destroyed
console.log 'Saved UserRemark', @remark, 'with response', response
updateProgress: (highlightNext) ->
return unless @user?.loaded and @sessions?.loaded
completed = 0
totalWeight = 0
next = null
for metric in metrics = @getProgressMetrics()
done = metric.fn()
completed += metric.weight if done
totalWeight += metric.weight
next = metric unless next or done
progress = Math.round 100 * completed / totalWeight
bar = @$el.find('.profile-completion-progress .progress-bar')
bar.css 'width', "#{progress}%"
if next
text = ''
t = $.i18n.t
text = "#{progress}% #{t 'account_profile.complete'}. #{t 'account_profile.next'}: #{next.name}"
bar.parent().show().find('.progress-text').text text
if highlightNext and next?.container and not (next.container in @highlightedContainers)
@highlightedContainers.push next.container
@$el.find(next.container).addClass 'emphasized'
#@onEditSection target: next.container
#$('#page-container').scrollTop 0
else
bar.parent().hide()
completed / totalWeight
getProgressMetrics: ->
schema = me.schema().properties.jobProfile
jobProfile = @user.get('jobProfile') ? {}
exists = (field) -> -> jobProfile[field]
modified = (field) -> -> jobProfile[field] and jobProfile[field] isnt schema.properties[field].default
listStarted = (field, subfields) -> -> jobProfile[field]?.length and _.every subfields, (subfield) -> jobProfile[field][0][subfield]
t = $.i18n.t
@progressMetrics = [
{name: t('account_profile.next_name'), weight: 1, container: '#name-container', fn: modified 'name'}
{name: t('account_profile.next_short_description'), weight: 2, container: '#short-description-container', fn: modified 'shortDescription'}
{name: t('account_profile.next_skills'), weight: 2, container: '#skills-container', fn: -> jobProfile.skills?.length >= 5}
{name: t('account_profile.next_long_description'), weight: 3, container: '#long-description-container', fn: modified 'longDescription'}
{name: t('account_profile.next_work'), weight: 3, container: '#work-container', fn: listStarted 'work', ['role', 'employer']}
{name: t('account_profile.next_education'), weight: 3, container: '#education-container', fn: listStarted 'education', ['degree', 'school']}
{name: t('account_profile.next_projects'), weight: 3, container: '#projects-container', fn: listStarted 'projects', ['name']}
{name: t('account_profile.next_city'), weight: 1, container: '#basic-info-container', fn: modified 'city'}
{name: t('account_profile.next_country'), weight: 0, container: '#basic-info-container', fn: exists 'country'}
{name: t('account_profile.next_links'), weight: 2, container: '#links-container', fn: listStarted 'links', ['link', 'name']}
{name: t('account_profile.next_photo'), weight: 2, container: '#profile-photo-container', fn: modified 'photoURL'}
{name: t('account_profile.next_active'), weight: 1, fn: modified 'active'}
]
onSessionLinkPressed: (e) ->
sessionID = $(e.target).closest('.session-link').data('session-id')
session = _.find @sessions.models, (session) -> session.id is sessionID
modal = new JobProfileCodeModal({session:session})
@openModalView modal
destroy: ->
@remarkTreema?.destroy()
super()
| true | UserView = require 'views/common/UserView'
template = require 'templates/account/job-profile-view'
User = require 'models/User'
LevelSession = require 'models/LevelSession'
CocoCollection = require 'collections/CocoCollection'
{me} = require 'core/auth'
JobProfileContactModal = require 'views/modal/JobProfileContactModal'
JobProfileTreemaView = require 'views/account/JobProfileTreemaView'
UserRemark = require 'models/UserRemark'
forms = require 'core/forms'
ModelModal = require 'views/modal/ModelModal'
JobProfileCodeModal = require './JobProfileCodeModal'
require 'vendor/treema'
class LevelSessionsCollection extends CocoCollection
url: -> "/db/user/#{@userID}/level.sessions/employer"
model: LevelSession
constructor: (@userID) ->
super()
adminContacts = [
{id: '', name: 'Assign a Contact'}
{id: '512ef4805a67a8c507000001', name: 'PI:NAME:<NAME>END_PI'}
{id: '5162fab9c92b4c751e000274', name: 'PI:NAME:<NAME>END_PI'}
{id: '51eb2714fa058cb20d0006ef', name: 'PI:NAME:<NAME>END_PI'}
{id: '51538fdb812dd9af02000001', name: 'PI:NAME:<NAME>END_PI'}
{id: '52a57252a89409700d0000d9', name: 'Ignore'}
]
module.exports = class JobProfileView extends UserView
id: 'profile-view'
template: template
showBackground: false
usesSocialMedia: true
subscriptions: {}
events:
'click #toggle-editing': 'toggleEditing'
'click #toggle-job-profile-active': 'toggleJobProfileActive'
'click #toggle-job-profile-approved': 'toggleJobProfileApproved'
'click #save-notes-button': 'onJobProfileNotesChanged'
'click #contact-candidate': 'onContactCandidate'
'click #enter-espionage-mode': 'enterEspionageMode'
'click #open-model-modal': 'openModelModal'
'click .editable-profile .profile-photo': 'onEditProfilePhoto'
'click .editable-profile .project-image': 'onEditProjectImage'
'click .editable-profile .editable-display': 'onEditSection'
'click .editable-profile .save-section': 'onSaveSection'
'click .editable-profile .glyphicon-remove': 'onCancelSectionEdit'
'change .editable-profile .editable-array input': 'onEditArray'
'keyup .editable-profile .editable-array input': 'onEditArray'
'click .editable-profile a': 'onClickLinkWhileEditing'
'change #admin-contact': 'onAdminContactChanged'
'click .session-link': 'onSessionLinkPressed'
constructor: (options, userID) ->
@onJobProfileNotesChanged = _.debounce @onJobProfileNotesChanged, 1000
@onRemarkChanged = _.debounce @onRemarkChanged, 1000
require('core/services/filepicker')() # Initialize if needed
super userID, options
onLoaded: ->
@finishInit() unless @destroyed
super()
finishInit: ->
return unless @userID
@uploadFilePath = "db/user/#{@userID}"
if @user?.get('firstName')
jobProfile = @user.get('jobProfile')
jobProfile ?= {}
if not jobProfile.name
jobProfile.name = (@user.get('firstName') + ' ' + @user.get('lastName')).trim()
@user.set('jobProfile', jobProfile)
@highlightedContainers = []
if me.isAdmin() or 'employer' in me.get('permissions', true)
$.post "/db/user/#{me.id}/track/view_candidate"
$.post "/db/user/#{@userID}/track/viewed_by_employer" unless me.isAdmin()
@sessions = @supermodel.loadCollection(new LevelSessionsCollection(@user.id), 'candidate_sessions').model
@listenToOnce @sessions, 'sync', => @render?()
if me.isAdmin()
# Mimicking how the VictoryModal fetches LevelFeedback
@remark = new UserRemark()
@remark.setURL "/db/user/#{@userID}/remark"
@remark.fetch()
@listenToOnce @remark, 'sync', @onRemarkLoaded
@listenToOnce @remark, 'error', @onRemarkNotFound
onRemarkLoaded: ->
@remark.setURL "/db/user.remark/#{@remark.id}"
@render()
onRemarkNotFound: ->
@remark = new UserRemark() # hmm, why do we create a new one here?
@remark.set 'user', @userID
@remark.set 'userName', name if name = @user.get('name')
jobProfileSchema: -> @user.schema().properties.jobProfile.properties
getRenderData: ->
context = super()
context.userID = @userID
context.profile = @user.get('jobProfile', true)
context.rawProfile = @user.get('jobProfile') or {}
context.user = @user
context.myProfile = @isMe()
context.allowedToViewJobProfile = @user and (me.isAdmin() or 'employer' in me.get('permissions', true) or (context.myProfile && !me.get('anonymous')))
context.allowedToEditJobProfile = @user and (me.isAdmin() or (context.myProfile && !me.get('anonymous')))
context.profileApproved = @user?.get 'jobProfileApproved'
context.progress = @progress ? @updateProgress()
@editing ?= context.myProfile and context.progress < 0.8
context.editing = @editing
context.marked = marked
context.moment = moment
context.iconForLink = @iconForLink
if links = context.profile.links
links = ($.extend(true, {}, link) for link in links)
link.icon = @iconForLink link for link in links
context.profileLinks = _.sortBy links, (link) -> not link.icon # icons first
if @sessions
context.sessions = (s.attributes for s in @sessions.models when (s.get('submitted') or (s.get('levelID') is 'gridmancer') and s.get('code')?.thoktar?.plan?.length isnt 942)) # no default code
context.sessions.sort (a, b) -> (b.playtime ? 0) - (a.playtime ? 0)
else
context.sessions = []
context.adminContacts = adminContacts
context.remark = @remark
context
afterRender: ->
super()
if me.get('employerAt')
@$el.addClass 'viewed-by-employer'
return unless @user
unless @user.get('jobProfile')?.projects?.length or @editing
@$el.find('.right-column').hide()
@$el.find('.middle-column').addClass('double-column')
unless @editing
@$el.find('.editable-display').attr('title', '')
@initializeAutocomplete()
highlightNext = @highlightNext ? true
justSavedSection = @$el.find('#' + @justSavedSectionID).addClass 'just-saved'
_.defer =>
@progress = @updateProgress highlightNext
_.delay ->
justSavedSection.removeClass 'just-saved', duration: 1500, easing: 'easeOutQuad'
, 500
if me.isAdmin() and @user and @remark
visibleSettings = ['history', 'tasks']
data = _.pick (@remark.attributes), (value, key) -> key in visibleSettings
data.history ?= []
data.tasks ?= []
schema = _.cloneDeep @remark.schema()
schema.properties = _.pick schema.properties, (value, key) => key in visibleSettings
schema.required = _.intersection (schema.required ? []), visibleSettings
treemaOptions =
filePath: "db/user/#{@userID}"
schema: schema
data: data
aceUseWrapMode: true
callbacks: {change: @onRemarkChanged}
@remarkTreema = @$el.find('#remark-treema').treema treemaOptions
@remarkTreema?.build()
@remarkTreema?.open(3)
onRemarkChanged: (e) =>
return unless @remarkTreema.isValid()
for key in ['history', 'tasks']
val = _.filter(@remarkTreema.get(key), (entry) -> entry?.content or entry?.action)
entry.date ?= (new Date()).toISOString() for entry in val if key is 'history'
@remark.set key, val
@saveRemark()
initializeAutocomplete: (container) ->
(container ? @$el).find('input[data-autocomplete]').each ->
$(@).autocomplete(source: JobProfileTreemaView[$(@).data('autocomplete')], minLength: parseInt($(@).data('autocomplete-min-length')), delay: 0, autoFocus: true)
toggleEditing: ->
@editing = not @editing
@render()
@saveEdits()
toggleJobProfileApproved: ->
return unless me.isAdmin()
approved = not @user.get 'jobProfileApproved'
@user.set 'jobProfileApproved', approved
res = @user.patch()
res.success (model, response, options) => @render()
toggleJobProfileActive: ->
active = not @user.get('jobProfile').active
@user.get('jobProfile').active = active
@saveEdits()
if active and not (me.isAdmin() or @stackLed)
$.post '/stacklead'
@stackLed = true
enterEspionageMode: ->
postData = emailLower: @user.get('email').toLowerCase(), usernameLower: @user.get('name').toLowerCase()
$.ajax
type: 'POST',
url: '/auth/spy'
data: postData
success: @espionageSuccess
espionageSuccess: (model) ->
window.location.reload()
openModelModal: (e) ->
@openModalView new ModelModal models: [@user]
onJobProfileNotesChanged: (e) =>
notes = @$el.find('#job-profile-notes').val()
@user.set 'jobProfileNotes', notes
@user.save {jobProfileNotes: notes}, {patch: true, type: 'PUT'}
iconForLink: (link) ->
icons = [
{icon: 'facebook', name: 'Facebook', domain: /facebook\.com/, match: /facebook/i}
{icon: 'twitter', name: 'Twitter', domain: /twitter\.com/, match: /twitter/i}
{icon: 'github', name: 'GitHub', domain: /github\.(com|io)/, match: /github/i}
{icon: 'gplus', name: 'Google Plus', domain: /plus\.google\.com/, match: /(google|^g).?(\+|plus)/i}
{icon: 'linkedin', name: 'LinkedIn', domain: /linkedin\.com/, match: /(google|^g).?(\+|plus)/i}
]
for icon in icons
if (link.name.search(icon.match) isnt -1) or (link.link.search(icon.domain) isnt -1)
icon.url = "/images/pages/account/profile/icon_#{icon.icon}.png"
return icon
null
onContactCandidate: (e) ->
@openModalView new JobProfileContactModal recipientID: @user.id, recipientUserName: @user.get('name')
showErrors: (errors) ->
section = @$el.find '.saving'
console.error 'Couldn\'t save because of validation errors:', errors
section.removeClass 'saving'
forms.clearFormAlerts section
# This is pretty lame, since we don't easily match which field had the error like forms.applyErrorsToForm can.
section.find('form').addClass('has-error').find('.save-section').before($("<span class='help-block error-help-block'>#{errors[0].message}</span>"))
saveEdits: (highlightNext) ->
errors = @user.validate()
return @showErrors errors if errors
jobProfile = @user.get('jobProfile')
jobProfile.updated = (new Date()).toISOString() if @user is me
@user.set 'jobProfile', jobProfile
return unless res = @user.save()
res.error =>
return if @destroyed
@showErrors [message: res.responseText]
res.success (model, response, options) =>
return if @destroyed
@justSavedSectionID = @$el.find('.editable-section.saving').removeClass('saving').attr('id')
@highlightNext = highlightNext
@render()
@highlightNext = false
@justSavedSectionID = null
onEditProfilePhoto: (e) ->
onSaving = =>
@$el.find('.profile-photo').addClass('saving')
onSaved = (uploadingPath) =>
@user.get('jobProfile').photoURL = uploadingPath
@saveEdits()
filepicker.pick {mimetypes: 'image/*'}, @onImageChosen(onSaving, onSaved)
onEditProjectImage: (e) ->
img = $(e.target)
onSaving = =>
img.addClass('saving')
onSaved = (uploadingPath) =>
img.parent().find('input').val(uploadingPath)
img.css('background-image', "url('/file/#{uploadingPath}')")
img.removeClass('saving')
filepicker.pick {mimetypes: 'image/*'}, @onImageChosen(onSaving, onSaved)
formatImagePostData: (inkBlob) ->
url: inkBlob.url, filename: inkBlob.filename, mimetype: inkBlob.mimetype, path: @uploadFilePath, force: true
onImageChosen: (onSaving, onSaved) ->
(inkBlob) =>
onSaving()
uploadingPath = [@uploadFilePath, inkBlob.filename].join('/')
$.ajax '/file', type: 'POST', data: @formatImagePostData(inkBlob), success: @onImageUploaded(onSaved, uploadingPath)
onImageUploaded: (onSaved, uploadingPath) ->
(e) =>
onSaved uploadingPath
onEditSection: (e) ->
@$el.find('.emphasized').removeClass('emphasized')
section = $(e.target).closest('.editable-section').removeClass 'deemphasized'
section.find('.editable-form').show().find('select, input, textarea').first().focus()
section.find('.editable-display').hide()
@$el.find('.editable-section').not(section).addClass 'deemphasized'
column = section.closest('.full-height-column')
@$el.find('.full-height-column').not(column).addClass 'deemphasized'
onCancelSectionEdit: (e) ->
@render()
onSaveSection: (e) ->
e.preventDefault()
section = $(e.target).closest('.editable-section')
form = $(e.target).closest('form')
isEmpty = @arrayItemIsEmpty
section.find('.array-item').each ->
$(@).remove() if isEmpty @
resetOnce = false # We have to clear out arrays if we're going to redo them
serialized = form.serializeArray()
jobProfile = @user.get('jobProfile') or {}
jobProfile[prop] ?= [] for prop in ['links', 'skills', 'work', 'education', 'projects']
rootPropertiesSeen = {}
for field in serialized
keyChain = @extractFieldKeyChain field.name
value = @extractFieldValue keyChain[0], field.value
parent = jobProfile
for key, i in keyChain
rootPropertiesSeen[key] = true unless i
break if i is keyChain.length - 1
parent[key] ?= {}
child = parent[key]
if _.isArray(child) and not resetOnce
child = parent[key] = []
resetOnce = true
else unless child?
child = parent[key] = {}
parent = child
if key is 'PI:KEY:<KEY>END_PI' and keyChain[0] is 'PI:KEY:<KEY>END_PI' and not value
delete parent[key]
else
parent[key] = value
form.find('.editable-array').each ->
key = $(@).data('property')
unless rootPropertiesSeen[key]
jobProfile[key] = []
if section.hasClass('projects-container') and not section.find('.array-item').length
jobProfile.projects = []
section.addClass 'saving'
@user.set('jobProfile', jobProfile)
@saveEdits true
extractFieldKeyChain: (key) ->
# 'root[projects][0][name]' -> ['projects', '0', 'name']
key.replace(/^root/, '').replace(/\[(.*?)\]/g, '.$1').replace(/^\./, '').split(/\./)
extractFieldValue: (key, value) ->
switch key
when 'active' then Boolean value
when 'experience' then parseInt value or '0'
else value
arrayItemIsEmpty: (arrayItem) ->
for input in $(arrayItem).find('input[type!=hidden], textarea')
return false if $(input).val().trim()
true
onEditArray: (e) ->
# We make sure there's always an empty array item at the end for the user to add to, deleting interstitial empties.
array = $(e.target).closest('.editable-array')
arrayItems = array.find('.array-item')
toRemove = []
for arrayItem, index in arrayItems
empty = @arrayItemIsEmpty arrayItem
if index is arrayItems.length - 1
lastEmpty = empty
else if empty and not $(arrayItem).find('input:focus, textarea:focus').length
toRemove.unshift index
$(arrayItems[emptyIndex]).remove() for emptyIndex in toRemove
unless lastEmpty
clone = $(arrayItem).clone(false)
clone.find('input').each -> $(@).val('')
clone.find('textarea').each -> $(@).text('')
array.append clone
@initializeAutocomplete clone
for arrayItem, index in array.find('.array-item')
for input in $(arrayItem).find('input, textarea')
$(input).attr('name', $(input).attr('name').replace(/\[\d+\]/, "[#{index}]"))
onClickLinkWhileEditing: (e) ->
e.preventDefault()
onAdminContactChanged: (e) ->
newContact = @$el.find('#admin-contact').val()
newContactName = if newContact then _.find(adminContacts, id: newContact).name else ''
@remark.set 'contact', newContact
@remark.set 'contactName', newContactName
@saveRemark()
saveRemark: ->
@remark.set 'user', @user.id
@remark.set 'userName', @user.get('name')
if errors = @remark.validate()
return console.error 'UserRemark', @remark, 'failed validation with errors:', errors
res = @remark.save()
res.error =>
return if @destroyed
console.error 'UserRemark', @remark, 'failed to save with error:', res.responseText
res.success (model, response, options) =>
return if @destroyed
console.log 'Saved UserRemark', @remark, 'with response', response
updateProgress: (highlightNext) ->
return unless @user?.loaded and @sessions?.loaded
completed = 0
totalWeight = 0
next = null
for metric in metrics = @getProgressMetrics()
done = metric.fn()
completed += metric.weight if done
totalWeight += metric.weight
next = metric unless next or done
progress = Math.round 100 * completed / totalWeight
bar = @$el.find('.profile-completion-progress .progress-bar')
bar.css 'width', "#{progress}%"
if next
text = ''
t = $.i18n.t
text = "#{progress}% #{t 'account_profile.complete'}. #{t 'account_profile.next'}: #{next.name}"
bar.parent().show().find('.progress-text').text text
if highlightNext and next?.container and not (next.container in @highlightedContainers)
@highlightedContainers.push next.container
@$el.find(next.container).addClass 'emphasized'
#@onEditSection target: next.container
#$('#page-container').scrollTop 0
else
bar.parent().hide()
completed / totalWeight
getProgressMetrics: ->
schema = me.schema().properties.jobProfile
jobProfile = @user.get('jobProfile') ? {}
exists = (field) -> -> jobProfile[field]
modified = (field) -> -> jobProfile[field] and jobProfile[field] isnt schema.properties[field].default
listStarted = (field, subfields) -> -> jobProfile[field]?.length and _.every subfields, (subfield) -> jobProfile[field][0][subfield]
t = $.i18n.t
@progressMetrics = [
{name: t('account_profile.next_name'), weight: 1, container: '#name-container', fn: modified 'name'}
{name: t('account_profile.next_short_description'), weight: 2, container: '#short-description-container', fn: modified 'shortDescription'}
{name: t('account_profile.next_skills'), weight: 2, container: '#skills-container', fn: -> jobProfile.skills?.length >= 5}
{name: t('account_profile.next_long_description'), weight: 3, container: '#long-description-container', fn: modified 'longDescription'}
{name: t('account_profile.next_work'), weight: 3, container: '#work-container', fn: listStarted 'work', ['role', 'employer']}
{name: t('account_profile.next_education'), weight: 3, container: '#education-container', fn: listStarted 'education', ['degree', 'school']}
{name: t('account_profile.next_projects'), weight: 3, container: '#projects-container', fn: listStarted 'projects', ['name']}
{name: t('account_profile.next_city'), weight: 1, container: '#basic-info-container', fn: modified 'city'}
{name: t('account_profile.next_country'), weight: 0, container: '#basic-info-container', fn: exists 'country'}
{name: t('account_profile.next_links'), weight: 2, container: '#links-container', fn: listStarted 'links', ['link', 'name']}
{name: t('account_profile.next_photo'), weight: 2, container: '#profile-photo-container', fn: modified 'photoURL'}
{name: t('account_profile.next_active'), weight: 1, fn: modified 'active'}
]
onSessionLinkPressed: (e) ->
sessionID = $(e.target).closest('.session-link').data('session-id')
session = _.find @sessions.models, (session) -> session.id is sessionID
modal = new JobProfileCodeModal({session:session})
@openModalView modal
destroy: ->
@remarkTreema?.destroy()
super()
|
[
{
"context": "###\nAuthor: Ansel Chen\nThanks xiaoshan5733\n###\ncrypto = require(\"crypto\"",
"end": 22,
"score": 0.9997196197509766,
"start": 12,
"tag": "NAME",
"value": "Ansel Chen"
},
{
"context": "###\nAuthor: Ansel Chen\nThanks xiaoshan5733\n###\ncrypto = require(\"crypto\")\n\... | src/libs/roa-signer.coffee | lln7777/aliyun-ros | 1 | ###
Author: Ansel Chen
Thanks xiaoshan5733
###
crypto = require("crypto")
ACCEPT = "Accept"
CONTENT_MD5 = "Content-MD5"
CONTENT_TYPE = "Content-Type"
DATE = "Date"
QUERY_SEPARATOR = "&"
HEADER_SEPARATOR = "\n"
###
Header 排序:
http协议Header
计算签名必须包含参数,Accept、Content-MD5、Content-Type、Date的值(没有key)(Content-Length不计入签名),并按顺序排列;若值不存在则以”\n”补齐
###
exports.replaceOccupiedParameters = (options)->
if not options.uriPattern
return null
result = options.uriPattern
delete options.uriPattern
paths = options
if paths
for key, value of paths
target = '{' + key + '}'
if ~(result.indexOf target)
result = result.replace target, value
delete paths[key]
return result
# change the give headerBegin to the lower() which in the headers
# and change it to key.lower():value
buildCanonicalHeaders = (headers, header_begin)->
result = ""
unsortMap = []
sortMapArr = []
for key, value of headers
if ~(key.toLowerCase().indexOf header_begin)
unsortMap.push [key.toLowerCase(), value]
sortMapArr = unsortMap.sort (a, b)->a[0] > b[0]
for value, i in sortMapArr
result += value[0] + ':' + value[1]
result += HEADER_SEPARATOR
return result
deleteHeadersParameters = (headers, header_begin)->
for key, value of headers
if ~(key.toLowerCase().indexOf header_begin)
delete headers[key]
return headers
buildQueryString = (uri)->
unSortMap = []
sortMap = []
uriArr = uri.split '?'
result = uriArr[0]
params = []
if uriArr[1]?
params = uriArr[1].split '&'
sortMap = params.sort()
result += '?' + sortMap.join QUERY_SEPARATOR
return result
exports.composeSignString = (options = {})->
# 先拼装出uri
signString = ""
signString += options.method
signString += HEADER_SEPARATOR
signString += options[ACCEPT] if options[ACCEPT]
signString += HEADER_SEPARATOR
signString += options[CONTENT_MD5] if options[CONTENT_MD5]
signString += HEADER_SEPARATOR
signString += options[CONTENT_TYPE] if options[CONTENT_TYPE]
signString += HEADER_SEPARATOR
signString += options[DATE] if options[DATE]
signString += HEADER_SEPARATOR
# 至此,标准头已经排好序
# 加入CanonicalizedHeaders
signString += buildCanonicalHeaders(options, "x-acs-")
# deleteHeadersParameters(options, "x-acs-")
signString += buildQueryString options.uri
return signString
handleParams = (params)->
keysSorted = Object.keys(params).sort()
result = []
i = 0
len = keysSorted.length
while i < len
result.push specialEncode(keysSorted[i]) + "=" + specialEncode(params[keysSorted[i]])
i++
result
exports.md5base64 = (text)->
crypto.createHash('md5').update(text).digest('base64')
exports.sign = (secret, signString) ->
hmac = crypto.createHmac("sha1", secret)
hmac.update signString
ret = hmac.digest "base64" | 113129 | ###
Author: <NAME>
Thanks xiaoshan5733
###
crypto = require("crypto")
ACCEPT = "Accept"
CONTENT_MD5 = "Content-MD5"
CONTENT_TYPE = "Content-Type"
DATE = "Date"
QUERY_SEPARATOR = "&"
HEADER_SEPARATOR = "\n"
###
Header 排序:
http协议Header
计算签名必须包含参数,Accept、Content-MD5、Content-Type、Date的值(没有key)(Content-Length不计入签名),并按顺序排列;若值不存在则以”\n”补齐
###
exports.replaceOccupiedParameters = (options)->
if not options.uriPattern
return null
result = options.uriPattern
delete options.uriPattern
paths = options
if paths
for key, value of paths
target = '{' + key + '}'
if ~(result.indexOf target)
result = result.replace target, value
delete paths[key]
return result
# change the give headerBegin to the lower() which in the headers
# and change it to key.lower():value
buildCanonicalHeaders = (headers, header_begin)->
result = ""
unsortMap = []
sortMapArr = []
for key, value of headers
if ~(key.toLowerCase().indexOf header_begin)
unsortMap.push [key.toLowerCase(), value]
sortMapArr = unsortMap.sort (a, b)->a[0] > b[0]
for value, i in sortMapArr
result += value[0] + ':' + value[1]
result += HEADER_SEPARATOR
return result
deleteHeadersParameters = (headers, header_begin)->
for key, value of headers
if ~(key.toLowerCase().indexOf header_begin)
delete headers[key]
return headers
buildQueryString = (uri)->
unSortMap = []
sortMap = []
uriArr = uri.split '?'
result = uriArr[0]
params = []
if uriArr[1]?
params = uriArr[1].split '&'
sortMap = params.sort()
result += '?' + sortMap.join QUERY_SEPARATOR
return result
exports.composeSignString = (options = {})->
# 先拼装出uri
signString = ""
signString += options.method
signString += HEADER_SEPARATOR
signString += options[ACCEPT] if options[ACCEPT]
signString += HEADER_SEPARATOR
signString += options[CONTENT_MD5] if options[CONTENT_MD5]
signString += HEADER_SEPARATOR
signString += options[CONTENT_TYPE] if options[CONTENT_TYPE]
signString += HEADER_SEPARATOR
signString += options[DATE] if options[DATE]
signString += HEADER_SEPARATOR
# 至此,标准头已经排好序
# 加入CanonicalizedHeaders
signString += buildCanonicalHeaders(options, "x-acs-")
# deleteHeadersParameters(options, "x-acs-")
signString += buildQueryString options.uri
return signString
handleParams = (params)->
keysSorted = Object.keys(params).sort()
result = []
i = 0
len = keysSorted.length
while i < len
result.push specialEncode(keysSorted[i]) + "=" + specialEncode(params[keysSorted[i]])
i++
result
exports.md5base64 = (text)->
crypto.createHash('md5').update(text).digest('base64')
exports.sign = (secret, signString) ->
hmac = crypto.createHmac("sha1", secret)
hmac.update signString
ret = hmac.digest "base64" | true | ###
Author: PI:NAME:<NAME>END_PI
Thanks xiaoshan5733
###
crypto = require("crypto")
ACCEPT = "Accept"
CONTENT_MD5 = "Content-MD5"
CONTENT_TYPE = "Content-Type"
DATE = "Date"
QUERY_SEPARATOR = "&"
HEADER_SEPARATOR = "\n"
###
Header 排序:
http协议Header
计算签名必须包含参数,Accept、Content-MD5、Content-Type、Date的值(没有key)(Content-Length不计入签名),并按顺序排列;若值不存在则以”\n”补齐
###
exports.replaceOccupiedParameters = (options)->
if not options.uriPattern
return null
result = options.uriPattern
delete options.uriPattern
paths = options
if paths
for key, value of paths
target = '{' + key + '}'
if ~(result.indexOf target)
result = result.replace target, value
delete paths[key]
return result
# change the give headerBegin to the lower() which in the headers
# and change it to key.lower():value
buildCanonicalHeaders = (headers, header_begin)->
result = ""
unsortMap = []
sortMapArr = []
for key, value of headers
if ~(key.toLowerCase().indexOf header_begin)
unsortMap.push [key.toLowerCase(), value]
sortMapArr = unsortMap.sort (a, b)->a[0] > b[0]
for value, i in sortMapArr
result += value[0] + ':' + value[1]
result += HEADER_SEPARATOR
return result
deleteHeadersParameters = (headers, header_begin)->
for key, value of headers
if ~(key.toLowerCase().indexOf header_begin)
delete headers[key]
return headers
buildQueryString = (uri)->
unSortMap = []
sortMap = []
uriArr = uri.split '?'
result = uriArr[0]
params = []
if uriArr[1]?
params = uriArr[1].split '&'
sortMap = params.sort()
result += '?' + sortMap.join QUERY_SEPARATOR
return result
exports.composeSignString = (options = {})->
# 先拼装出uri
signString = ""
signString += options.method
signString += HEADER_SEPARATOR
signString += options[ACCEPT] if options[ACCEPT]
signString += HEADER_SEPARATOR
signString += options[CONTENT_MD5] if options[CONTENT_MD5]
signString += HEADER_SEPARATOR
signString += options[CONTENT_TYPE] if options[CONTENT_TYPE]
signString += HEADER_SEPARATOR
signString += options[DATE] if options[DATE]
signString += HEADER_SEPARATOR
# 至此,标准头已经排好序
# 加入CanonicalizedHeaders
signString += buildCanonicalHeaders(options, "x-acs-")
# deleteHeadersParameters(options, "x-acs-")
signString += buildQueryString options.uri
return signString
handleParams = (params)->
keysSorted = Object.keys(params).sort()
result = []
i = 0
len = keysSorted.length
while i < len
result.push specialEncode(keysSorted[i]) + "=" + specialEncode(params[keysSorted[i]])
i++
result
exports.md5base64 = (text)->
crypto.createHash('md5').update(text).digest('base64')
exports.sign = (secret, signString) ->
hmac = crypto.createHmac("sha1", secret)
hmac.update signString
ret = hmac.digest "base64" |
[
{
"context": " = require 'odoql'\nql = ql()\n\ndata = [\n { name: 'one' }\n { name: 'two' }\n { name: 'three' }\n { name",
"end": 55,
"score": 0.9977249503135681,
"start": 52,
"tag": "NAME",
"value": "one"
},
{
"context": "\nql = ql()\n\ndata = [\n { name: 'one' }\n { name: 'tw... | examples/fill.coffee | odojs/odoql | 2 | ql = require 'odoql'
ql = ql()
data = [
{ name: 'one' }
{ name: 'two' }
{ name: 'three' }
{ name: 'four' }
]
query = ql 'test'
.concat ql.param 'param1'
.fill
param1: 'name'
.query()
console.log JSON.stringify query, null, 2
exe = require 'odoql-exe'
exe = exe()
exe.build(query) (err, results) ->
console.log results | 171797 | ql = require 'odoql'
ql = ql()
data = [
{ name: '<NAME>' }
{ name: '<NAME>' }
{ name: '<NAME>' }
{ name: '<NAME>' }
]
query = ql 'test'
.concat ql.param 'param1'
.fill
param1: '<NAME>'
.query()
console.log JSON.stringify query, null, 2
exe = require 'odoql-exe'
exe = exe()
exe.build(query) (err, results) ->
console.log results | true | ql = require 'odoql'
ql = ql()
data = [
{ name: 'PI:NAME:<NAME>END_PI' }
{ name: 'PI:NAME:<NAME>END_PI' }
{ name: 'PI:NAME:<NAME>END_PI' }
{ name: 'PI:NAME:<NAME>END_PI' }
]
query = ql 'test'
.concat ql.param 'param1'
.fill
param1: 'PI:NAME:<NAME>END_PI'
.query()
console.log JSON.stringify query, null, 2
exe = require 'odoql-exe'
exe = exe()
exe.build(query) (err, results) ->
console.log results |
[
{
"context": "elf.login = options.login\n self.password = options.password\n self.rooms = options.rooms\n s",
"end": 3070,
"score": 0.8048778176307678,
"start": 3063,
"tag": "PASSWORD",
"value": "options"
}
] | node_modules/hubot-kato/src/kato.coffee | nitroniks/hubot | 0 | HTTP = require('http')
HTTPS = require('https')
EventEmitter = require('events').EventEmitter
WebSocketClient = require('websocket').client
# for inspectiong and loggingig
Util = require("util")
Winston = require('winston')
# for scripts loading
Fs = require('fs')
Path = require('path')
# logger options
winston = new Winston.Logger
transports: [
new Winston.transports.File {
filename: process.env.HUBOT_KATO_LOG_FILE || 'kato-hubot.log',
timestamp: true,
json: false,
level: process.env.HUBOT_KATO_LOG_LEVEL || 'error'
}
new Winston.transports.Console {
level: process.env.HUBOT_KATO_LOG_LEVEL || 'error'
}
]
# simple Winston logger wrapper
logger =
error : (msg) -> winston.log("error", msg)
debug : (msg) -> winston.log("debug", msg)
info : (msg) -> winston.log("info", msg)
inspect : (msg, obj) -> winston.log("debug", msg + "#{Util.inspect(obj)}")
{Robot, Adapter, TextMessage, EnterMessage, LeaveMessage, Response} = require 'hubot'
try
{TextMessage} = require '../../../src/message' # because of bugs with new version of nodejs
# Hubot Adapter
class Kato extends Adapter
constructor: (robot) ->
super robot
# scripts files loader
path = Path.resolve __dirname, '../scripts'
Fs.exists path, (exists) ->
logger.inspect("path ", path)
logger.inspect("exist ", exists)
if exists
for file in Fs.readdirSync(path)
robot.loadFile path, file
robot.parseHelp Path.join(path, file)
else logger.info("Script folder #{path} doesn't exist!")
send: (envelope, strings...) ->
@client.send(envelope.room, str) for str in strings
reply: (envelope, strings...) ->
strings = strings.map (s) -> "@#{envelope.user.name} #{s}"
@send envelope.user, strings...
run: ->
self = @
options =
api_url : process.env.HUBOT_KATO_API || "https://api.kato.im"
login : process.env.HUBOT_KATO_LOGIN
password: process.env.HUBOT_KATO_PASSWORD
logger.debug "Kato adapter options: #{Util.inspect options}"
unless options.login? and options.password?
logger.error \
"Not enough parameters provided. I need a login, password"
process.exit(1)
client = new KatoClient(options, @robot)
client.on "TextMessage", (user, message) ->
self.receive new TextMessage user, message
client.on 'reconnect', () ->
setTimeout ->
client.Login()
, 5000
client.Login()
@client = client
self.emit "connected"
exports.use = (robot) ->
new Kato robot
###################################################################
# The client.
###################################################################
class KatoClient extends EventEmitter
self = @
constructor: (options, @robot) ->
self = @
[schema, host] = options.api_url.split("://")
self.secure = schema == "https"
self.api_host = host
self.login = options.login
self.password = options.password
self.rooms = options.rooms
self.orgs = []
@.on 'login', (err) ->
@WebSocket()
# Get organizations membership which is available for account.
# Set returned orgs collection to self.orgs
# (will be used for ws messages subscription)
GetAccount: () ->
@get "/accounts/"+self.account_id, null, (err, data) ->
{response, body} = data
switch response.statusCode
when 200,201
json = JSON.parse body
self.orgs = []
for m in json.memberships
self.orgs.push({org_id: m.org_id,\
org_name: m.org_name,\
restricted: m.restricted,\
role: m.role})
logger.inspect "account memberships: #{Util.inspect json}"
self.emit 'login'
when 403
logger.error "Invalid account id"
else
self.emit 'reconnect'
Login: () ->
id = @uuid()
data = JSON.stringify
email: self.login
password: self.password
@put "/sessions/"+id, data, (err, data) ->
{response, body} = data
switch response.statusCode
when 200,201
self.sessionKey = response.headers['set-cookie'][0].split(';')[0]
self.sessionId = id
json = JSON.parse body
self.account_id = json.account_id
self.session_id = json.id
self.GetAccount() # getting additional account infformation for ws subscription
when 403
logger.error "Invalid login/password combination"
process.exit(2)
else
logger.error "Can't login. Status: #{response.statusCode}, Id: #{id}, Headers: #{Util.inspect(response.headers)}"
logger.error "Kato error: #{response.statusCode}"
self.emit 'reconnect'
WebSocket: () ->
client = new WebSocketClient()
client.on 'connectFailed', (error) ->
logger.error('_Connect Error: ' + error.toString())
client.on 'connect', (connection) ->
self.connection = connection
connection.on 'close', () ->
logger.info 'echo-protocol Connection Closed'
self.emit 'reconnect'
connection.on 'error', (error) ->
logger.info "error #{error}"
connection.on 'message', (message) ->
logger.debug "incomming message: #{Util.inspect message}"
if (message.type == 'utf8')
data = JSON.parse message.utf8Data
if data.type == "text" # message for hubot
user =
id: data.from.id
name: data.from.name
room: data.room_id
if self.login != data.from.email # ignore own messages
user = self.robot.brain.userForId(user.id, user)
self.emit "TextMessage", user, data.params.text
else if data.type == "read" || data.type == "typing" || data.type == "silence"
# ignore
else if data.type == "check" # server check of status
json = JSON.stringify(
org_id: data.org_id,
type: "presence",
params: {
status: "online",
ts: Date.now(),
tz_offset: new Date().getTimezoneOffset()/60,
device_type: "hubot" # TODO: not sure about it
})
connection.sendUTF json # notifying server for hubot user presence
logger.debug "send presence: #{json}"
else
logger.debug "unused message received: #{Util.inspect(data)}"
# Send message for subscribing to all avalable rooms
Subscribe = () ->
for o in self.orgs
params = {}
params.organization = {}
params.accounts = {}
params.forums = {}
if (o.role == "owner")
params.groups = {}
json = JSON.stringify(
type: "sync"
org_id: o.org_id
group_id: o.org_id
params: params
)
connection.sendUTF json
# Subscribe to organizations messages (aka hello)
json = JSON.stringify(
type: "sync"
params: { account: {} })
logger.debug "send ws hello: #{json}"
connection.sendUTF json, Subscribe()
headers =
'Cookie': self.sessionKey
client.connect((if self.secure then 'wss' else 'ws') + '://'+self.api_host+'/ws/v1', null, null, headers)
uuid: (size) ->
part = (d) ->
if d then part(d - 1) + Math.ceil((0xffffffff * Math.random())).toString(16) else ''
part(size || 8)
send: (room_id, str) ->
json = JSON.stringify
room_id: room_id
type: "text"
params:
text: str
data:
renderer: "markdown"
logger.debug "sended: #{JSON.stringify json}"
@connection.sendUTF json
put: (path, body, callback) ->
@request "PUT", path, body, callback
get: (path, body, callback) ->
@request "GET", path, body, callback
request: (method, path, body, callback) ->
if self.secure
module = HTTPS
port = 443
else
module = HTTP
port = 80
headers =
"Authorization" : @authorization
"Host" : self.api_host
"Content-Type" : "application/json"
"Cookie" : self.sessionKey # it's need for HTTP api requests
options =
"agent" : false
"host" : self.api_host
"port" : port
"path" : path
"method" : method
"headers": {}
if method is "POST" || method is "PUT"
if typeof(body) isnt "string"
body = JSON.stringify body
body = new Buffer(body)
headers["Content-Length"] = body.length
for key, val of headers when val
options.headers[key] = val
request = module.request options, (response) ->
data = ""
response.on "data", (chunk) ->
data += chunk
response.on "end", ->
callback null, {response: response, body: data}
response.on "error", (err) ->
logger.error "Kato response error: #{err}"
callback err, { }
if method is "POST" || method is "PUT"
request.end(body, 'binary')
else
request.end()
request.on "error", (err) ->
logger.error "Kato request error: #{err}"
| 114724 | HTTP = require('http')
HTTPS = require('https')
EventEmitter = require('events').EventEmitter
WebSocketClient = require('websocket').client
# for inspectiong and loggingig
Util = require("util")
Winston = require('winston')
# for scripts loading
Fs = require('fs')
Path = require('path')
# logger options
winston = new Winston.Logger
transports: [
new Winston.transports.File {
filename: process.env.HUBOT_KATO_LOG_FILE || 'kato-hubot.log',
timestamp: true,
json: false,
level: process.env.HUBOT_KATO_LOG_LEVEL || 'error'
}
new Winston.transports.Console {
level: process.env.HUBOT_KATO_LOG_LEVEL || 'error'
}
]
# simple Winston logger wrapper
logger =
error : (msg) -> winston.log("error", msg)
debug : (msg) -> winston.log("debug", msg)
info : (msg) -> winston.log("info", msg)
inspect : (msg, obj) -> winston.log("debug", msg + "#{Util.inspect(obj)}")
{Robot, Adapter, TextMessage, EnterMessage, LeaveMessage, Response} = require 'hubot'
try
{TextMessage} = require '../../../src/message' # because of bugs with new version of nodejs
# Hubot Adapter
class Kato extends Adapter
constructor: (robot) ->
super robot
# scripts files loader
path = Path.resolve __dirname, '../scripts'
Fs.exists path, (exists) ->
logger.inspect("path ", path)
logger.inspect("exist ", exists)
if exists
for file in Fs.readdirSync(path)
robot.loadFile path, file
robot.parseHelp Path.join(path, file)
else logger.info("Script folder #{path} doesn't exist!")
send: (envelope, strings...) ->
@client.send(envelope.room, str) for str in strings
reply: (envelope, strings...) ->
strings = strings.map (s) -> "@#{envelope.user.name} #{s}"
@send envelope.user, strings...
run: ->
self = @
options =
api_url : process.env.HUBOT_KATO_API || "https://api.kato.im"
login : process.env.HUBOT_KATO_LOGIN
password: process.env.HUBOT_KATO_PASSWORD
logger.debug "Kato adapter options: #{Util.inspect options}"
unless options.login? and options.password?
logger.error \
"Not enough parameters provided. I need a login, password"
process.exit(1)
client = new KatoClient(options, @robot)
client.on "TextMessage", (user, message) ->
self.receive new TextMessage user, message
client.on 'reconnect', () ->
setTimeout ->
client.Login()
, 5000
client.Login()
@client = client
self.emit "connected"
exports.use = (robot) ->
new Kato robot
###################################################################
# The client.
###################################################################
class KatoClient extends EventEmitter
self = @
constructor: (options, @robot) ->
self = @
[schema, host] = options.api_url.split("://")
self.secure = schema == "https"
self.api_host = host
self.login = options.login
self.password = <PASSWORD>.password
self.rooms = options.rooms
self.orgs = []
@.on 'login', (err) ->
@WebSocket()
# Get organizations membership which is available for account.
# Set returned orgs collection to self.orgs
# (will be used for ws messages subscription)
GetAccount: () ->
@get "/accounts/"+self.account_id, null, (err, data) ->
{response, body} = data
switch response.statusCode
when 200,201
json = JSON.parse body
self.orgs = []
for m in json.memberships
self.orgs.push({org_id: m.org_id,\
org_name: m.org_name,\
restricted: m.restricted,\
role: m.role})
logger.inspect "account memberships: #{Util.inspect json}"
self.emit 'login'
when 403
logger.error "Invalid account id"
else
self.emit 'reconnect'
Login: () ->
id = @uuid()
data = JSON.stringify
email: self.login
password: self.password
@put "/sessions/"+id, data, (err, data) ->
{response, body} = data
switch response.statusCode
when 200,201
self.sessionKey = response.headers['set-cookie'][0].split(';')[0]
self.sessionId = id
json = JSON.parse body
self.account_id = json.account_id
self.session_id = json.id
self.GetAccount() # getting additional account infformation for ws subscription
when 403
logger.error "Invalid login/password combination"
process.exit(2)
else
logger.error "Can't login. Status: #{response.statusCode}, Id: #{id}, Headers: #{Util.inspect(response.headers)}"
logger.error "Kato error: #{response.statusCode}"
self.emit 'reconnect'
WebSocket: () ->
client = new WebSocketClient()
client.on 'connectFailed', (error) ->
logger.error('_Connect Error: ' + error.toString())
client.on 'connect', (connection) ->
self.connection = connection
connection.on 'close', () ->
logger.info 'echo-protocol Connection Closed'
self.emit 'reconnect'
connection.on 'error', (error) ->
logger.info "error #{error}"
connection.on 'message', (message) ->
logger.debug "incomming message: #{Util.inspect message}"
if (message.type == 'utf8')
data = JSON.parse message.utf8Data
if data.type == "text" # message for hubot
user =
id: data.from.id
name: data.from.name
room: data.room_id
if self.login != data.from.email # ignore own messages
user = self.robot.brain.userForId(user.id, user)
self.emit "TextMessage", user, data.params.text
else if data.type == "read" || data.type == "typing" || data.type == "silence"
# ignore
else if data.type == "check" # server check of status
json = JSON.stringify(
org_id: data.org_id,
type: "presence",
params: {
status: "online",
ts: Date.now(),
tz_offset: new Date().getTimezoneOffset()/60,
device_type: "hubot" # TODO: not sure about it
})
connection.sendUTF json # notifying server for hubot user presence
logger.debug "send presence: #{json}"
else
logger.debug "unused message received: #{Util.inspect(data)}"
# Send message for subscribing to all avalable rooms
Subscribe = () ->
for o in self.orgs
params = {}
params.organization = {}
params.accounts = {}
params.forums = {}
if (o.role == "owner")
params.groups = {}
json = JSON.stringify(
type: "sync"
org_id: o.org_id
group_id: o.org_id
params: params
)
connection.sendUTF json
# Subscribe to organizations messages (aka hello)
json = JSON.stringify(
type: "sync"
params: { account: {} })
logger.debug "send ws hello: #{json}"
connection.sendUTF json, Subscribe()
headers =
'Cookie': self.sessionKey
client.connect((if self.secure then 'wss' else 'ws') + '://'+self.api_host+'/ws/v1', null, null, headers)
uuid: (size) ->
part = (d) ->
if d then part(d - 1) + Math.ceil((0xffffffff * Math.random())).toString(16) else ''
part(size || 8)
send: (room_id, str) ->
json = JSON.stringify
room_id: room_id
type: "text"
params:
text: str
data:
renderer: "markdown"
logger.debug "sended: #{JSON.stringify json}"
@connection.sendUTF json
put: (path, body, callback) ->
@request "PUT", path, body, callback
get: (path, body, callback) ->
@request "GET", path, body, callback
request: (method, path, body, callback) ->
if self.secure
module = HTTPS
port = 443
else
module = HTTP
port = 80
headers =
"Authorization" : @authorization
"Host" : self.api_host
"Content-Type" : "application/json"
"Cookie" : self.sessionKey # it's need for HTTP api requests
options =
"agent" : false
"host" : self.api_host
"port" : port
"path" : path
"method" : method
"headers": {}
if method is "POST" || method is "PUT"
if typeof(body) isnt "string"
body = JSON.stringify body
body = new Buffer(body)
headers["Content-Length"] = body.length
for key, val of headers when val
options.headers[key] = val
request = module.request options, (response) ->
data = ""
response.on "data", (chunk) ->
data += chunk
response.on "end", ->
callback null, {response: response, body: data}
response.on "error", (err) ->
logger.error "Kato response error: #{err}"
callback err, { }
if method is "POST" || method is "PUT"
request.end(body, 'binary')
else
request.end()
request.on "error", (err) ->
logger.error "Kato request error: #{err}"
| true | HTTP = require('http')
HTTPS = require('https')
EventEmitter = require('events').EventEmitter
WebSocketClient = require('websocket').client
# for inspectiong and loggingig
Util = require("util")
Winston = require('winston')
# for scripts loading
Fs = require('fs')
Path = require('path')
# logger options
winston = new Winston.Logger
transports: [
new Winston.transports.File {
filename: process.env.HUBOT_KATO_LOG_FILE || 'kato-hubot.log',
timestamp: true,
json: false,
level: process.env.HUBOT_KATO_LOG_LEVEL || 'error'
}
new Winston.transports.Console {
level: process.env.HUBOT_KATO_LOG_LEVEL || 'error'
}
]
# simple Winston logger wrapper
logger =
error : (msg) -> winston.log("error", msg)
debug : (msg) -> winston.log("debug", msg)
info : (msg) -> winston.log("info", msg)
inspect : (msg, obj) -> winston.log("debug", msg + "#{Util.inspect(obj)}")
{Robot, Adapter, TextMessage, EnterMessage, LeaveMessage, Response} = require 'hubot'
try
{TextMessage} = require '../../../src/message' # because of bugs with new version of nodejs
# Hubot Adapter
class Kato extends Adapter
constructor: (robot) ->
super robot
# scripts files loader
path = Path.resolve __dirname, '../scripts'
Fs.exists path, (exists) ->
logger.inspect("path ", path)
logger.inspect("exist ", exists)
if exists
for file in Fs.readdirSync(path)
robot.loadFile path, file
robot.parseHelp Path.join(path, file)
else logger.info("Script folder #{path} doesn't exist!")
send: (envelope, strings...) ->
@client.send(envelope.room, str) for str in strings
reply: (envelope, strings...) ->
strings = strings.map (s) -> "@#{envelope.user.name} #{s}"
@send envelope.user, strings...
run: ->
self = @
options =
api_url : process.env.HUBOT_KATO_API || "https://api.kato.im"
login : process.env.HUBOT_KATO_LOGIN
password: process.env.HUBOT_KATO_PASSWORD
logger.debug "Kato adapter options: #{Util.inspect options}"
unless options.login? and options.password?
logger.error \
"Not enough parameters provided. I need a login, password"
process.exit(1)
client = new KatoClient(options, @robot)
client.on "TextMessage", (user, message) ->
self.receive new TextMessage user, message
client.on 'reconnect', () ->
setTimeout ->
client.Login()
, 5000
client.Login()
@client = client
self.emit "connected"
exports.use = (robot) ->
new Kato robot
###################################################################
# The client.
###################################################################
class KatoClient extends EventEmitter
self = @
constructor: (options, @robot) ->
self = @
[schema, host] = options.api_url.split("://")
self.secure = schema == "https"
self.api_host = host
self.login = options.login
self.password = PI:PASSWORD:<PASSWORD>END_PI.password
self.rooms = options.rooms
self.orgs = []
@.on 'login', (err) ->
@WebSocket()
# Get organizations membership which is available for account.
# Set returned orgs collection to self.orgs
# (will be used for ws messages subscription)
GetAccount: () ->
@get "/accounts/"+self.account_id, null, (err, data) ->
{response, body} = data
switch response.statusCode
when 200,201
json = JSON.parse body
self.orgs = []
for m in json.memberships
self.orgs.push({org_id: m.org_id,\
org_name: m.org_name,\
restricted: m.restricted,\
role: m.role})
logger.inspect "account memberships: #{Util.inspect json}"
self.emit 'login'
when 403
logger.error "Invalid account id"
else
self.emit 'reconnect'
Login: () ->
id = @uuid()
data = JSON.stringify
email: self.login
password: self.password
@put "/sessions/"+id, data, (err, data) ->
{response, body} = data
switch response.statusCode
when 200,201
self.sessionKey = response.headers['set-cookie'][0].split(';')[0]
self.sessionId = id
json = JSON.parse body
self.account_id = json.account_id
self.session_id = json.id
self.GetAccount() # getting additional account infformation for ws subscription
when 403
logger.error "Invalid login/password combination"
process.exit(2)
else
logger.error "Can't login. Status: #{response.statusCode}, Id: #{id}, Headers: #{Util.inspect(response.headers)}"
logger.error "Kato error: #{response.statusCode}"
self.emit 'reconnect'
WebSocket: () ->
client = new WebSocketClient()
client.on 'connectFailed', (error) ->
logger.error('_Connect Error: ' + error.toString())
client.on 'connect', (connection) ->
self.connection = connection
connection.on 'close', () ->
logger.info 'echo-protocol Connection Closed'
self.emit 'reconnect'
connection.on 'error', (error) ->
logger.info "error #{error}"
connection.on 'message', (message) ->
logger.debug "incomming message: #{Util.inspect message}"
if (message.type == 'utf8')
data = JSON.parse message.utf8Data
if data.type == "text" # message for hubot
user =
id: data.from.id
name: data.from.name
room: data.room_id
if self.login != data.from.email # ignore own messages
user = self.robot.brain.userForId(user.id, user)
self.emit "TextMessage", user, data.params.text
else if data.type == "read" || data.type == "typing" || data.type == "silence"
# ignore
else if data.type == "check" # server check of status
json = JSON.stringify(
org_id: data.org_id,
type: "presence",
params: {
status: "online",
ts: Date.now(),
tz_offset: new Date().getTimezoneOffset()/60,
device_type: "hubot" # TODO: not sure about it
})
connection.sendUTF json # notifying server for hubot user presence
logger.debug "send presence: #{json}"
else
logger.debug "unused message received: #{Util.inspect(data)}"
# Send message for subscribing to all avalable rooms
Subscribe = () ->
for o in self.orgs
params = {}
params.organization = {}
params.accounts = {}
params.forums = {}
if (o.role == "owner")
params.groups = {}
json = JSON.stringify(
type: "sync"
org_id: o.org_id
group_id: o.org_id
params: params
)
connection.sendUTF json
# Subscribe to organizations messages (aka hello)
json = JSON.stringify(
type: "sync"
params: { account: {} })
logger.debug "send ws hello: #{json}"
connection.sendUTF json, Subscribe()
headers =
'Cookie': self.sessionKey
client.connect((if self.secure then 'wss' else 'ws') + '://'+self.api_host+'/ws/v1', null, null, headers)
uuid: (size) ->
part = (d) ->
if d then part(d - 1) + Math.ceil((0xffffffff * Math.random())).toString(16) else ''
part(size || 8)
send: (room_id, str) ->
json = JSON.stringify
room_id: room_id
type: "text"
params:
text: str
data:
renderer: "markdown"
logger.debug "sended: #{JSON.stringify json}"
@connection.sendUTF json
put: (path, body, callback) ->
@request "PUT", path, body, callback
get: (path, body, callback) ->
@request "GET", path, body, callback
request: (method, path, body, callback) ->
if self.secure
module = HTTPS
port = 443
else
module = HTTP
port = 80
headers =
"Authorization" : @authorization
"Host" : self.api_host
"Content-Type" : "application/json"
"Cookie" : self.sessionKey # it's need for HTTP api requests
options =
"agent" : false
"host" : self.api_host
"port" : port
"path" : path
"method" : method
"headers": {}
if method is "POST" || method is "PUT"
if typeof(body) isnt "string"
body = JSON.stringify body
body = new Buffer(body)
headers["Content-Length"] = body.length
for key, val of headers when val
options.headers[key] = val
request = module.request options, (response) ->
data = ""
response.on "data", (chunk) ->
data += chunk
response.on "end", ->
callback null, {response: response, body: data}
response.on "error", (err) ->
logger.error "Kato response error: #{err}"
callback err, { }
if method is "POST" || method is "PUT"
request.end(body, 'binary')
else
request.end()
request.on "error", (err) ->
logger.error "Kato request error: #{err}"
|
[
{
"context": " team: challenge.team,\n ratingKey: alts.uniqueId(challengerId, challenge.altName)\n }\n {\n",
"end": 4735,
"score": 0.7114149332046509,
"start": 4724,
"tag": "KEY",
"value": "ts.uniqueId"
},
{
"context": ".team,\n ratingKey: alts.uniqueId(... | server/server.coffee | sarenji/pokebattle-sim | 5 | {createHmac} = require 'crypto'
{_} = require 'underscore'
Limiter = require 'ratelimiter'
{User} = require('./user')
{BattleQueue} = require './queue'
{UserStore} = require './user_store'
async = require('async')
gen = require './generations'
auth = require('./auth')
learnsets = require '../shared/learnsets'
{Conditions, SelectableConditions, Formats, DEFAULT_FORMAT} = require '../shared/conditions'
pbv = require '../shared/pokebattle_values'
config = require './config'
errors = require '../shared/errors'
redis = require('./redis')
alts = require './alts'
achievements = require './achievements'
FIND_BATTLE_CONDITIONS = [
Conditions.TEAM_PREVIEW
Conditions.RATED_BATTLE
Conditions.TIMED_BATTLE
Conditions.SLEEP_CLAUSE
Conditions.EVASION_CLAUSE
Conditions.SPECIES_CLAUSE
Conditions.PRANKSTER_SWAGGER_CLAUSE
Conditions.OHKO_CLAUSE
Conditions.UNRELEASED_BAN
]
MAX_NICKNAME_LENGTH = 15
class @BattleServer
constructor: ->
@queues = {}
for format of Formats
@queues[format] = new BattleQueue()
@battles = {}
# A hash mapping users to battles.
@userBattles = {}
# same as user battles, but indexed by name and does not include alts
@visibleUserBattles = {}
# A hash mapping user ids to challenges
# challenges[challengeeId][challengerId] = {generation: 'xy', team: []}
@challenges = {}
# A hash mapping ids to users
@users = new UserStore()
@rooms = []
# rate limiters
@limiters = {}
# Battles can start.
@unlockdown()
hasRoom: (roomId) ->
!!@getRoom(roomId)
getRoom: (roomId) ->
_.find(@rooms, (room) -> room.name == roomId)
# Creates a new user or finds an existing one, and adds a spark to it
findOrCreateUser: (json, spark) ->
user = @users.get(json.name)
user = @users.add(json, spark)
user
getUser: (userId) ->
@users.get(userId)
join: (spark) ->
@showTopic(spark)
for battleId of @userBattles[spark.user.name]
battle = @battles[battleId]
battle.add(spark)
battle.sendRequestTo(spark.user.name)
battle.sendUpdates()
@limiters[spark.user.id] ?= {}
return spark
leave: (spark) ->
for room in @rooms
room.remove(spark)
@users.remove(spark)
return if spark.user.hasSparks()
delete @limiters[spark.user.id]
@stopChallenges(spark.user)
showTopic: (player) ->
redis.hget "topic", "main", (err, topic) ->
player.send('topic', topic) if topic
registerChallenge: (player, challengeeId, format, team, conditions, altName) ->
if @isLockedDown()
errorMessage = "The server is locked. No new battles can start at this time."
player.error(errors.PRIVATE_MESSAGE, challengeeId, errorMessage)
return false
else if !@users.contains(challengeeId)
errorMessage = "This user is offline."
player.error(errors.PRIVATE_MESSAGE, challengeeId, errorMessage)
return false
else if player.name == challengeeId
errorMessage = "You cannot challenge yourself."
player.error(errors.PRIVATE_MESSAGE, challengeeId, errorMessage)
return false
else if @challenges[player.name]?[challengeeId] ||
@challenges[challengeeId]?[player.name]
errorMessage = "A challenge already exists between you two."
player.error(errors.PRIVATE_MESSAGE, challengeeId, errorMessage)
return false
# Do not allow rated battles or other unallowed conditions.
if _.difference(conditions, SelectableConditions).length > 0
player.error(errors.FIND_BATTLE, 'This battle cannot have certain conditions.')
return false
err = @validateTeam(team, format, conditions)
if err.length > 0
# TODO: Use a modal error instead
player.error(errors.FIND_BATTLE, err)
return false
@challenges[player.name] ?= {}
@challenges[player.name][challengeeId] = {format, team, conditions, challengerName: player.name, altName}
challengee = @users.get(challengeeId)
challengee.send("challenge", player.name, format, conditions)
return true
acceptChallenge: (player, challengerId, team, altName) ->
if !@challenges[challengerId]?[player.name]?
errorMessage = "The challenge no longer exists."
player.error(errors.PRIVATE_MESSAGE, challengerId, errorMessage)
return null
challenge = @challenges[challengerId][player.name]
err = @validateTeam(team, challenge.format, challenge.conditions)
if err.length > 0
# TODO: Use a modal error instead
player.error(errors.FIND_BATTLE, err)
return null
teams = [
{
id: challengerId,
name: challenge.altName || challenge.challengerName,
team: challenge.team,
ratingKey: alts.uniqueId(challengerId, challenge.altName)
}
{
id: player.name,
name: altName || player.name,
team: team,
ratingKey: alts.uniqueId(player.name, altName)
}
]
id = @createBattle(challenge.format, teams, challenge.conditions)
challenger = @users.get(challengerId)
challenger.send("challengeSuccess", player.name)
player.send("challengeSuccess", challengerId)
delete @challenges[challengerId][player.name]
return id
rejectChallenge: (player, challengerId) ->
if !@challenges[challengerId]?[player.name]?
errorMessage = "The challenge no longer exists."
player.error(errors.PRIVATE_MESSAGE, challengerId, errorMessage)
return false
delete @challenges[challengerId][player.name]
player.send("rejectChallenge", challengerId)
challenger = @users.get(challengerId)
challenger.send("rejectChallenge", player.name)
cancelChallenge: (player, challengeeId) ->
if !@challenges[player.name]?[challengeeId]?
errorMessage = "The challenge no longer exists."
player.error(errors.PRIVATE_MESSAGE, challengeeId, errorMessage)
return false
delete @challenges[player.name][challengeeId]
player.send("cancelChallenge", challengeeId)
challengee = @users.get(challengeeId)
challengee.send("cancelChallenge", player.name)
stopChallenges: (player) ->
playerId = player.name
for challengeeId of @challenges[playerId]
@cancelChallenge(player, challengeeId)
delete @challenges[playerId]
for challengerId of @challenges
if @challenges[challengerId][playerId]
@rejectChallenge(player, challengerId)
# Adds the player to the queue. Note that there is no validation on whether altName
# is correct, so make
queuePlayer: (playerId, team, format = DEFAULT_FORMAT, altName) ->
if @isLockedDown()
err = ["The server is restarting after all battles complete. No new battles can start at this time."]
else if format != DEFAULT_FORMAT
# TODO: Implement ratings for other formats
err = ["The server doesn't support this ladder at this time. Please ask for challenges instead."]
else
err = @validateTeam(team, format, FIND_BATTLE_CONDITIONS)
if err.length == 0
name = @users.get(playerId).name
ratingKey = alts.uniqueId(playerId, altName)
@queues[format].add(playerId, altName || name, team, ratingKey)
return err
queuedPlayers: (format = DEFAULT_FORMAT) ->
@queues[format].queuedPlayers()
removePlayer: (playerId, format = DEFAULT_FORMAT) ->
return false if format not of @queues
@queues[format].remove(playerId)
return true
beginBattles: (next) ->
array = for format in Object.keys(Formats)
do (format) => (callback) =>
@queues[format].pairPlayers (err, pairs) =>
if err then return callback(err)
# Create a battle for each pair
battleIds = []
for pair in pairs
id = @createBattle(format, pair, FIND_BATTLE_CONDITIONS)
battleIds.push(id)
callback(null, battleIds)
async.parallel array, (err, battleIds) ->
return next(err) if err
next(null, _.flatten(battleIds))
return true
# Creates a battle and returns its battleId
createBattle: (rawFormat = DEFAULT_FORMAT, pair = [], conditions = []) ->
format = Formats[rawFormat]
generation = format.generation
conditions = conditions.concat(format.conditions)
{Battle} = require("../server/#{generation}/battle")
{BattleController} = require("../server/#{generation}/battle_controller")
playerIds = pair.map((user) -> user.name)
battleId = @generateBattleId(playerIds)
battle = new Battle(battleId, pair, format: rawFormat, conditions: _.clone(conditions))
@battles[battleId] = new BattleController(battle)
for player in pair
# Add user to spectators
# TODO: player.id should be using player.name, but alts present a problem.
user = @users.get(player.id)
battle.add(spark) for spark in user.sparks
# Add/remove player ids to/from user battles
@userBattles[player.id] ?= {}
@userBattles[player.id][battleId] = true
# Add the player to the list if its not an alt
if player.id == player.ratingKey # hacky - but no alternative right now
@visibleUserBattles[player.id] ?= {}
@visibleUserBattles[player.id][battleId] = true
battle.once 'end', @removeUserBattle.bind(this, player.id, player.name, battleId)
battle.once 'expire', @removeBattle.bind(this, battleId)
# Add the battle to the achievements system
# Uneligible battles are ignored by this function
achievements.registerBattle(this, battle)
@rooms.push(battle)
@battles[battleId].beginBattle()
battleId
# Generate a random ID for a new battle.
generateBattleId: (players) ->
hmac = createHmac('sha1', config.SECRET_KEY)
hmac.update((new Date).toISOString())
for id in players
hmac.update(id)
hmac.digest('hex')
# Returns the battle with battleId.
findBattle: (battleId) ->
@battles[battleId]
getUserBattles: (userId) ->
(id for id, value of @userBattles[userId])
# Returns all non-alt battles the user is playing in
getVisibleUserBattles: (username) ->
(id for id, value of @visibleUserBattles[username])
getOngoingBattles: ->
# TODO: This is very inefficient. Improve this.
_.chain(@battles).values().reject((b) -> b.battle.isOver()).value()
removeUserBattle: (userId, username, battleId) ->
delete @userBattles[userId][battleId]
delete @visibleUserBattles[username]?[battleId]
removeBattle: (battleId) ->
for room, i in @rooms
if room.name == battleId
@rooms.splice(i, 1)
break
delete @battles[battleId]
# A length of -1 denotes a permanent ban.
ban: (username, reason, length = -1) ->
auth.ban(username, reason, length)
if user = @users.get(username)
user.error(errors.BANNED, reason, length)
user.close()
unban: (username, next) ->
auth.unban(username, next)
mute: (username, reason, length) ->
auth.mute(username, reason, length)
unmute: (username) ->
auth.unmute(username)
announce: (message) ->
for room in @rooms
room.announce("warning", message)
userMessage: (user, room, message) ->
@runIfUnmuted user, room.name, ->
room.userMessage(user, message)
runIfUnmuted: (user, roomId, next) ->
auth.getMuteTTL user.name, (err, ttl) ->
if ttl == -2
next()
else
user.announce(roomId, 'warning', "You are muted for another #{ttl} seconds!")
setAuthority: (user, newAuthority) ->
user = @users.get(user) if user not instanceof User
user.authority = newAuthority if user
limit: (player, kind, options, next) ->
attributes =
max: options.max
duration: options.duration
id: player.id
db: redis
@limiters[player.id][kind] ?= new Limiter(attributes)
@limiters[player.id][kind].get(next)
lockdown: ->
@canBattlesStart = false
for user in @users.getUsers()
@stopChallenges(user)
@announce("<strong>The server is restarting!</strong> We're waiting for all battles to finish to push some updates. No new battles may start at this time.")
unlockdown: ->
@canBattlesStart = true
@announce("<strong>Battles have been unlocked!</strong> You may battle again.")
isLockedDown: ->
!@canBattlesStart
# Returns an empty array if the given team is valid, an array of errors
# otherwise.
validateTeam: (team, format = DEFAULT_FORMAT, conditions = []) ->
return [ "Invalid format: #{format}." ] if format not of Formats
format = Formats[format]
return [ "Invalid team format." ] if team not instanceof Array
return [ "Team must have 1 to 6 Pokemon." ] unless 1 <= team.length <= 6
conditions = conditions.concat(format.conditions)
genData = gen.GenerationJSON[format.generation.toUpperCase()]
err = require('./conditions').validateTeam(conditions, team, genData)
return err if err.length > 0
err = team.map (pokemon, i) =>
@validatePokemon(conditions, pokemon, i + 1, format.generation)
return _.flatten(err)
# Returns an empty array if the given Pokemon is valid, an array of errors
# otherwise.
validatePokemon: (conditions, pokemon, slot, generation = gen.DEFAULT_GENERATION) ->
genData = gen.GenerationJSON[generation.toUpperCase()]
{SpeciesData, FormeData, MoveData} = genData
err = []
prefix = "Slot ##{slot}"
if !pokemon.species
err.push("#{prefix}: No species given.")
return err
species = SpeciesData[pokemon.species]
if !species
err.push("#{prefix}: Invalid species: #{pokemon.species}.")
return err
prefix += " (#{pokemon.species})"
@normalizePokemon(pokemon, generation)
forme = FormeData[pokemon.species][pokemon.forme]
if !forme
err.push("#{prefix}: Invalid forme: #{pokemon.forme}.")
return err
if forme.isBattleOnly
err.push("#{prefix}: #{pokemon.forme} forme is battle-only.")
return err
unless 0 < pokemon.name.length <= MAX_NICKNAME_LENGTH
err.push("#{prefix}: Nickname cannot be blank or be
#{MAX_NICKNAME_LENGTH} characters or higher.")
return err
if pokemon.name != pokemon.species && pokemon.name of SpeciesData
err.push("#{prefix}: Nickname cannot be another Pokemon's name.")
return err
if /[\u0300-\u036F\u20D0-\u20FF\uFE20-\uFE2F]/.test(pokemon.name)
err.push("#{prefix}: Nickname cannot contain some special characters.")
return err
if isNaN(pokemon.level)
err.push("#{prefix}: Invalid level: #{pokemon.level}.")
# TODO: 100 is a magic constant
else if !(1 <= pokemon.level <= 100)
err.push("#{prefix}: Level must be between 1 and 100.")
if pokemon.gender not in [ "M", "F", "Genderless" ]
err.push("#{prefix}: Invalid gender: #{pokemon.gender}.")
if species.genderRatio == -1 && pokemon.gender != "Genderless"
err.push("#{prefix}: Must be genderless.")
if species.genderRatio == 0 && pokemon.gender != "M"
err.push("#{prefix}: Must be male.")
if species.genderRatio == 8 && pokemon.gender != "F"
err.push("#{prefix}: Must be female.")
if (typeof pokemon.evs != "object")
err.push("#{prefix}: Invalid evs.")
if (typeof pokemon.ivs != "object")
err.push("#{prefix}: Invalid ivs.")
if !_.chain(pokemon.evs).values().all((ev) -> 0 <= ev <= 255).value()
err.push("#{prefix}: EVs must be between 0 and 255.")
if !_.chain(pokemon.ivs).values().all((iv) -> 0 <= iv <= 31).value()
err.push("#{prefix}: IVs must be between 0 and 31.")
if _.values(pokemon.evs).reduce(((x, y) -> x + y), 0) > 510
err.push("#{prefix}: EV total must be less than 510.")
if pokemon.ability not in forme["abilities"] &&
pokemon.ability != forme["hiddenAbility"]
err.push("#{prefix}: Invalid ability.")
if pokemon.moves not instanceof Array
err.push("#{prefix}: Invalid moves.")
# TODO: 4 is a magic constant
else if !(1 <= pokemon.moves.length <= 4)
err.push("#{prefix}: Must have 1 to 4 moves.")
else if !_(pokemon.moves).all((name) -> MoveData[name]?)
invalidMove = _(pokemon.moves).find((name) -> !MoveData[name]?)
err.push("#{prefix}: Invalid move name: #{invalidMove}")
else if !learnsets.checkMoveset(gen.GenerationJSON, pokemon,
gen.GENERATION_TO_INT[generation], pokemon.moves)
err.push("#{prefix}: Invalid moveset.")
err.push require('./conditions').validatePokemon(conditions, pokemon, genData, prefix)...
return err
# Normalizes a Pokemon by setting default values where applicable.
# Assumes that the Pokemon is a real Pokemon (i.e. its species/forme is valid)
normalizePokemon: (pokemon, generation = gen.DEFAULT_GENERATION) ->
{SpeciesData, FormeData} = gen.GenerationJSON[generation.toUpperCase()]
pokemon.forme ?= "default"
pokemon.name ?= pokemon.species
pokemon.ability ?= FormeData[pokemon.species][pokemon.forme]?["abilities"][0]
if !pokemon.gender?
{genderRatio} = SpeciesData[pokemon.species]
if genderRatio == -1 then pokemon.gender = "Genderless"
else if Math.random() < (genderRatio / 8) then pokemon.gender = "F"
else pokemon.gender = "M"
pokemon.evs ?= {}
pokemon.ivs ?= {}
pokemon.level ?= 100
pokemon.level = Math.floor(pokemon.level)
return pokemon
| 98788 | {createHmac} = require 'crypto'
{_} = require 'underscore'
Limiter = require 'ratelimiter'
{User} = require('./user')
{BattleQueue} = require './queue'
{UserStore} = require './user_store'
async = require('async')
gen = require './generations'
auth = require('./auth')
learnsets = require '../shared/learnsets'
{Conditions, SelectableConditions, Formats, DEFAULT_FORMAT} = require '../shared/conditions'
pbv = require '../shared/pokebattle_values'
config = require './config'
errors = require '../shared/errors'
redis = require('./redis')
alts = require './alts'
achievements = require './achievements'
FIND_BATTLE_CONDITIONS = [
Conditions.TEAM_PREVIEW
Conditions.RATED_BATTLE
Conditions.TIMED_BATTLE
Conditions.SLEEP_CLAUSE
Conditions.EVASION_CLAUSE
Conditions.SPECIES_CLAUSE
Conditions.PRANKSTER_SWAGGER_CLAUSE
Conditions.OHKO_CLAUSE
Conditions.UNRELEASED_BAN
]
MAX_NICKNAME_LENGTH = 15
class @BattleServer
constructor: ->
@queues = {}
for format of Formats
@queues[format] = new BattleQueue()
@battles = {}
# A hash mapping users to battles.
@userBattles = {}
# same as user battles, but indexed by name and does not include alts
@visibleUserBattles = {}
# A hash mapping user ids to challenges
# challenges[challengeeId][challengerId] = {generation: 'xy', team: []}
@challenges = {}
# A hash mapping ids to users
@users = new UserStore()
@rooms = []
# rate limiters
@limiters = {}
# Battles can start.
@unlockdown()
hasRoom: (roomId) ->
!!@getRoom(roomId)
getRoom: (roomId) ->
_.find(@rooms, (room) -> room.name == roomId)
# Creates a new user or finds an existing one, and adds a spark to it
findOrCreateUser: (json, spark) ->
user = @users.get(json.name)
user = @users.add(json, spark)
user
getUser: (userId) ->
@users.get(userId)
join: (spark) ->
@showTopic(spark)
for battleId of @userBattles[spark.user.name]
battle = @battles[battleId]
battle.add(spark)
battle.sendRequestTo(spark.user.name)
battle.sendUpdates()
@limiters[spark.user.id] ?= {}
return spark
leave: (spark) ->
for room in @rooms
room.remove(spark)
@users.remove(spark)
return if spark.user.hasSparks()
delete @limiters[spark.user.id]
@stopChallenges(spark.user)
showTopic: (player) ->
redis.hget "topic", "main", (err, topic) ->
player.send('topic', topic) if topic
registerChallenge: (player, challengeeId, format, team, conditions, altName) ->
if @isLockedDown()
errorMessage = "The server is locked. No new battles can start at this time."
player.error(errors.PRIVATE_MESSAGE, challengeeId, errorMessage)
return false
else if !@users.contains(challengeeId)
errorMessage = "This user is offline."
player.error(errors.PRIVATE_MESSAGE, challengeeId, errorMessage)
return false
else if player.name == challengeeId
errorMessage = "You cannot challenge yourself."
player.error(errors.PRIVATE_MESSAGE, challengeeId, errorMessage)
return false
else if @challenges[player.name]?[challengeeId] ||
@challenges[challengeeId]?[player.name]
errorMessage = "A challenge already exists between you two."
player.error(errors.PRIVATE_MESSAGE, challengeeId, errorMessage)
return false
# Do not allow rated battles or other unallowed conditions.
if _.difference(conditions, SelectableConditions).length > 0
player.error(errors.FIND_BATTLE, 'This battle cannot have certain conditions.')
return false
err = @validateTeam(team, format, conditions)
if err.length > 0
# TODO: Use a modal error instead
player.error(errors.FIND_BATTLE, err)
return false
@challenges[player.name] ?= {}
@challenges[player.name][challengeeId] = {format, team, conditions, challengerName: player.name, altName}
challengee = @users.get(challengeeId)
challengee.send("challenge", player.name, format, conditions)
return true
acceptChallenge: (player, challengerId, team, altName) ->
if !@challenges[challengerId]?[player.name]?
errorMessage = "The challenge no longer exists."
player.error(errors.PRIVATE_MESSAGE, challengerId, errorMessage)
return null
challenge = @challenges[challengerId][player.name]
err = @validateTeam(team, challenge.format, challenge.conditions)
if err.length > 0
# TODO: Use a modal error instead
player.error(errors.FIND_BATTLE, err)
return null
teams = [
{
id: challengerId,
name: challenge.altName || challenge.challengerName,
team: challenge.team,
ratingKey: al<KEY>(challenger<KEY>, challenge.altName)
}
{
id: player.name,
name: altName || player.name,
team: team,
ratingKey: alts.<KEY>Id(player.name, altName)
}
]
id = @createBattle(challenge.format, teams, challenge.conditions)
challenger = @users.get(challengerId)
challenger.send("challengeSuccess", player.name)
player.send("challengeSuccess", challengerId)
delete @challenges[challengerId][player.name]
return id
rejectChallenge: (player, challengerId) ->
if !@challenges[challengerId]?[player.name]?
errorMessage = "The challenge no longer exists."
player.error(errors.PRIVATE_MESSAGE, challengerId, errorMessage)
return false
delete @challenges[challengerId][player.name]
player.send("rejectChallenge", challengerId)
challenger = @users.get(challengerId)
challenger.send("rejectChallenge", player.name)
cancelChallenge: (player, challengeeId) ->
if !@challenges[player.name]?[challengeeId]?
errorMessage = "The challenge no longer exists."
player.error(errors.PRIVATE_MESSAGE, challengeeId, errorMessage)
return false
delete @challenges[player.name][challengeeId]
player.send("cancelChallenge", challengeeId)
challengee = @users.get(challengeeId)
challengee.send("cancelChallenge", player.name)
stopChallenges: (player) ->
playerId = player.name
for challengeeId of @challenges[playerId]
@cancelChallenge(player, challengeeId)
delete @challenges[playerId]
for challengerId of @challenges
if @challenges[challengerId][playerId]
@rejectChallenge(player, challengerId)
# Adds the player to the queue. Note that there is no validation on whether altName
# is correct, so make
queuePlayer: (playerId, team, format = DEFAULT_FORMAT, altName) ->
if @isLockedDown()
err = ["The server is restarting after all battles complete. No new battles can start at this time."]
else if format != DEFAULT_FORMAT
# TODO: Implement ratings for other formats
err = ["The server doesn't support this ladder at this time. Please ask for challenges instead."]
else
err = @validateTeam(team, format, FIND_BATTLE_CONDITIONS)
if err.length == 0
name = @users.get(playerId).name
ratingKey = alts.uniqueId(playerId, altName)
@queues[format].add(playerId, altName || name, team, ratingKey)
return err
queuedPlayers: (format = DEFAULT_FORMAT) ->
@queues[format].queuedPlayers()
removePlayer: (playerId, format = DEFAULT_FORMAT) ->
return false if format not of @queues
@queues[format].remove(playerId)
return true
beginBattles: (next) ->
array = for format in Object.keys(Formats)
do (format) => (callback) =>
@queues[format].pairPlayers (err, pairs) =>
if err then return callback(err)
# Create a battle for each pair
battleIds = []
for pair in pairs
id = @createBattle(format, pair, FIND_BATTLE_CONDITIONS)
battleIds.push(id)
callback(null, battleIds)
async.parallel array, (err, battleIds) ->
return next(err) if err
next(null, _.flatten(battleIds))
return true
# Creates a battle and returns its battleId
createBattle: (rawFormat = DEFAULT_FORMAT, pair = [], conditions = []) ->
format = Formats[rawFormat]
generation = format.generation
conditions = conditions.concat(format.conditions)
{Battle} = require("../server/#{generation}/battle")
{BattleController} = require("../server/#{generation}/battle_controller")
playerIds = pair.map((user) -> user.name)
battleId = @generateBattleId(playerIds)
battle = new Battle(battleId, pair, format: rawFormat, conditions: _.clone(conditions))
@battles[battleId] = new BattleController(battle)
for player in pair
# Add user to spectators
# TODO: player.id should be using player.name, but alts present a problem.
user = @users.get(player.id)
battle.add(spark) for spark in user.sparks
# Add/remove player ids to/from user battles
@userBattles[player.id] ?= {}
@userBattles[player.id][battleId] = true
# Add the player to the list if its not an alt
if player.id == player.ratingKey # hacky - but no alternative right now
@visibleUserBattles[player.id] ?= {}
@visibleUserBattles[player.id][battleId] = true
battle.once 'end', @removeUserBattle.bind(this, player.id, player.name, battleId)
battle.once 'expire', @removeBattle.bind(this, battleId)
# Add the battle to the achievements system
# Uneligible battles are ignored by this function
achievements.registerBattle(this, battle)
@rooms.push(battle)
@battles[battleId].beginBattle()
battleId
# Generate a random ID for a new battle.
generateBattleId: (players) ->
hmac = createHmac('sha1', config.SECRET_KEY)
hmac.update((new Date).toISOString())
for id in players
hmac.update(id)
hmac.digest('hex')
# Returns the battle with battleId.
findBattle: (battleId) ->
@battles[battleId]
getUserBattles: (userId) ->
(id for id, value of @userBattles[userId])
# Returns all non-alt battles the user is playing in
getVisibleUserBattles: (username) ->
(id for id, value of @visibleUserBattles[username])
getOngoingBattles: ->
# TODO: This is very inefficient. Improve this.
_.chain(@battles).values().reject((b) -> b.battle.isOver()).value()
removeUserBattle: (userId, username, battleId) ->
delete @userBattles[userId][battleId]
delete @visibleUserBattles[username]?[battleId]
removeBattle: (battleId) ->
for room, i in @rooms
if room.name == battleId
@rooms.splice(i, 1)
break
delete @battles[battleId]
# A length of -1 denotes a permanent ban.
ban: (username, reason, length = -1) ->
auth.ban(username, reason, length)
if user = @users.get(username)
user.error(errors.BANNED, reason, length)
user.close()
unban: (username, next) ->
auth.unban(username, next)
mute: (username, reason, length) ->
auth.mute(username, reason, length)
unmute: (username) ->
auth.unmute(username)
announce: (message) ->
for room in @rooms
room.announce("warning", message)
userMessage: (user, room, message) ->
@runIfUnmuted user, room.name, ->
room.userMessage(user, message)
runIfUnmuted: (user, roomId, next) ->
auth.getMuteTTL user.name, (err, ttl) ->
if ttl == -2
next()
else
user.announce(roomId, 'warning', "You are muted for another #{ttl} seconds!")
setAuthority: (user, newAuthority) ->
user = @users.get(user) if user not instanceof User
user.authority = newAuthority if user
limit: (player, kind, options, next) ->
attributes =
max: options.max
duration: options.duration
id: player.id
db: redis
@limiters[player.id][kind] ?= new Limiter(attributes)
@limiters[player.id][kind].get(next)
lockdown: ->
@canBattlesStart = false
for user in @users.getUsers()
@stopChallenges(user)
@announce("<strong>The server is restarting!</strong> We're waiting for all battles to finish to push some updates. No new battles may start at this time.")
unlockdown: ->
@canBattlesStart = true
@announce("<strong>Battles have been unlocked!</strong> You may battle again.")
isLockedDown: ->
!@canBattlesStart
# Returns an empty array if the given team is valid, an array of errors
# otherwise.
validateTeam: (team, format = DEFAULT_FORMAT, conditions = []) ->
return [ "Invalid format: #{format}." ] if format not of Formats
format = Formats[format]
return [ "Invalid team format." ] if team not instanceof Array
return [ "Team must have 1 to 6 Pokemon." ] unless 1 <= team.length <= 6
conditions = conditions.concat(format.conditions)
genData = gen.GenerationJSON[format.generation.toUpperCase()]
err = require('./conditions').validateTeam(conditions, team, genData)
return err if err.length > 0
err = team.map (pokemon, i) =>
@validatePokemon(conditions, pokemon, i + 1, format.generation)
return _.flatten(err)
# Returns an empty array if the given Pokemon is valid, an array of errors
# otherwise.
validatePokemon: (conditions, pokemon, slot, generation = gen.DEFAULT_GENERATION) ->
genData = gen.GenerationJSON[generation.toUpperCase()]
{SpeciesData, FormeData, MoveData} = genData
err = []
prefix = "Slot ##{slot}"
if !pokemon.species
err.push("#{prefix}: No species given.")
return err
species = SpeciesData[pokemon.species]
if !species
err.push("#{prefix}: Invalid species: #{pokemon.species}.")
return err
prefix += " (#{pokemon.species})"
@normalizePokemon(pokemon, generation)
forme = FormeData[pokemon.species][pokemon.forme]
if !forme
err.push("#{prefix}: Invalid forme: #{pokemon.forme}.")
return err
if forme.isBattleOnly
err.push("#{prefix}: #{pokemon.forme} forme is battle-only.")
return err
unless 0 < pokemon.name.length <= MAX_NICKNAME_LENGTH
err.push("#{prefix}: Nickname cannot be blank or be
#{MAX_NICKNAME_LENGTH} characters or higher.")
return err
if pokemon.name != pokemon.species && pokemon.name of SpeciesData
err.push("#{prefix}: Nickname cannot be another Pokemon's name.")
return err
if /[\u0300-\u036F\u20D0-\u20FF\uFE20-\uFE2F]/.test(pokemon.name)
err.push("#{prefix}: Nickname cannot contain some special characters.")
return err
if isNaN(pokemon.level)
err.push("#{prefix}: Invalid level: #{pokemon.level}.")
# TODO: 100 is a magic constant
else if !(1 <= pokemon.level <= 100)
err.push("#{prefix}: Level must be between 1 and 100.")
if pokemon.gender not in [ "M", "F", "Genderless" ]
err.push("#{prefix}: Invalid gender: #{pokemon.gender}.")
if species.genderRatio == -1 && pokemon.gender != "Genderless"
err.push("#{prefix}: Must be genderless.")
if species.genderRatio == 0 && pokemon.gender != "M"
err.push("#{prefix}: Must be male.")
if species.genderRatio == 8 && pokemon.gender != "F"
err.push("#{prefix}: Must be female.")
if (typeof pokemon.evs != "object")
err.push("#{prefix}: Invalid evs.")
if (typeof pokemon.ivs != "object")
err.push("#{prefix}: Invalid ivs.")
if !_.chain(pokemon.evs).values().all((ev) -> 0 <= ev <= 255).value()
err.push("#{prefix}: EVs must be between 0 and 255.")
if !_.chain(pokemon.ivs).values().all((iv) -> 0 <= iv <= 31).value()
err.push("#{prefix}: IVs must be between 0 and 31.")
if _.values(pokemon.evs).reduce(((x, y) -> x + y), 0) > 510
err.push("#{prefix}: EV total must be less than 510.")
if pokemon.ability not in forme["abilities"] &&
pokemon.ability != forme["hiddenAbility"]
err.push("#{prefix}: Invalid ability.")
if pokemon.moves not instanceof Array
err.push("#{prefix}: Invalid moves.")
# TODO: 4 is a magic constant
else if !(1 <= pokemon.moves.length <= 4)
err.push("#{prefix}: Must have 1 to 4 moves.")
else if !_(pokemon.moves).all((name) -> MoveData[name]?)
invalidMove = _(pokemon.moves).find((name) -> !MoveData[name]?)
err.push("#{prefix}: Invalid move name: #{invalidMove}")
else if !learnsets.checkMoveset(gen.GenerationJSON, pokemon,
gen.GENERATION_TO_INT[generation], pokemon.moves)
err.push("#{prefix}: Invalid moveset.")
err.push require('./conditions').validatePokemon(conditions, pokemon, genData, prefix)...
return err
# Normalizes a Pokemon by setting default values where applicable.
# Assumes that the Pokemon is a real Pokemon (i.e. its species/forme is valid)
normalizePokemon: (pokemon, generation = gen.DEFAULT_GENERATION) ->
{SpeciesData, FormeData} = gen.GenerationJSON[generation.toUpperCase()]
pokemon.forme ?= "default"
pokemon.name ?= pokemon.species
pokemon.ability ?= FormeData[pokemon.species][pokemon.forme]?["abilities"][0]
if !pokemon.gender?
{genderRatio} = SpeciesData[pokemon.species]
if genderRatio == -1 then pokemon.gender = "Genderless"
else if Math.random() < (genderRatio / 8) then pokemon.gender = "F"
else pokemon.gender = "M"
pokemon.evs ?= {}
pokemon.ivs ?= {}
pokemon.level ?= 100
pokemon.level = Math.floor(pokemon.level)
return pokemon
| true | {createHmac} = require 'crypto'
{_} = require 'underscore'
Limiter = require 'ratelimiter'
{User} = require('./user')
{BattleQueue} = require './queue'
{UserStore} = require './user_store'
async = require('async')
gen = require './generations'
auth = require('./auth')
learnsets = require '../shared/learnsets'
{Conditions, SelectableConditions, Formats, DEFAULT_FORMAT} = require '../shared/conditions'
pbv = require '../shared/pokebattle_values'
config = require './config'
errors = require '../shared/errors'
redis = require('./redis')
alts = require './alts'
achievements = require './achievements'
FIND_BATTLE_CONDITIONS = [
Conditions.TEAM_PREVIEW
Conditions.RATED_BATTLE
Conditions.TIMED_BATTLE
Conditions.SLEEP_CLAUSE
Conditions.EVASION_CLAUSE
Conditions.SPECIES_CLAUSE
Conditions.PRANKSTER_SWAGGER_CLAUSE
Conditions.OHKO_CLAUSE
Conditions.UNRELEASED_BAN
]
MAX_NICKNAME_LENGTH = 15
class @BattleServer
constructor: ->
@queues = {}
for format of Formats
@queues[format] = new BattleQueue()
@battles = {}
# A hash mapping users to battles.
@userBattles = {}
# same as user battles, but indexed by name and does not include alts
@visibleUserBattles = {}
# A hash mapping user ids to challenges
# challenges[challengeeId][challengerId] = {generation: 'xy', team: []}
@challenges = {}
# A hash mapping ids to users
@users = new UserStore()
@rooms = []
# rate limiters
@limiters = {}
# Battles can start.
@unlockdown()
hasRoom: (roomId) ->
!!@getRoom(roomId)
getRoom: (roomId) ->
_.find(@rooms, (room) -> room.name == roomId)
# Creates a new user or finds an existing one, and adds a spark to it
findOrCreateUser: (json, spark) ->
user = @users.get(json.name)
user = @users.add(json, spark)
user
getUser: (userId) ->
@users.get(userId)
join: (spark) ->
@showTopic(spark)
for battleId of @userBattles[spark.user.name]
battle = @battles[battleId]
battle.add(spark)
battle.sendRequestTo(spark.user.name)
battle.sendUpdates()
@limiters[spark.user.id] ?= {}
return spark
leave: (spark) ->
for room in @rooms
room.remove(spark)
@users.remove(spark)
return if spark.user.hasSparks()
delete @limiters[spark.user.id]
@stopChallenges(spark.user)
showTopic: (player) ->
redis.hget "topic", "main", (err, topic) ->
player.send('topic', topic) if topic
registerChallenge: (player, challengeeId, format, team, conditions, altName) ->
if @isLockedDown()
errorMessage = "The server is locked. No new battles can start at this time."
player.error(errors.PRIVATE_MESSAGE, challengeeId, errorMessage)
return false
else if !@users.contains(challengeeId)
errorMessage = "This user is offline."
player.error(errors.PRIVATE_MESSAGE, challengeeId, errorMessage)
return false
else if player.name == challengeeId
errorMessage = "You cannot challenge yourself."
player.error(errors.PRIVATE_MESSAGE, challengeeId, errorMessage)
return false
else if @challenges[player.name]?[challengeeId] ||
@challenges[challengeeId]?[player.name]
errorMessage = "A challenge already exists between you two."
player.error(errors.PRIVATE_MESSAGE, challengeeId, errorMessage)
return false
# Do not allow rated battles or other unallowed conditions.
if _.difference(conditions, SelectableConditions).length > 0
player.error(errors.FIND_BATTLE, 'This battle cannot have certain conditions.')
return false
err = @validateTeam(team, format, conditions)
if err.length > 0
# TODO: Use a modal error instead
player.error(errors.FIND_BATTLE, err)
return false
@challenges[player.name] ?= {}
@challenges[player.name][challengeeId] = {format, team, conditions, challengerName: player.name, altName}
challengee = @users.get(challengeeId)
challengee.send("challenge", player.name, format, conditions)
return true
acceptChallenge: (player, challengerId, team, altName) ->
if !@challenges[challengerId]?[player.name]?
errorMessage = "The challenge no longer exists."
player.error(errors.PRIVATE_MESSAGE, challengerId, errorMessage)
return null
challenge = @challenges[challengerId][player.name]
err = @validateTeam(team, challenge.format, challenge.conditions)
if err.length > 0
# TODO: Use a modal error instead
player.error(errors.FIND_BATTLE, err)
return null
teams = [
{
id: challengerId,
name: challenge.altName || challenge.challengerName,
team: challenge.team,
ratingKey: alPI:KEY:<KEY>END_PI(challengerPI:KEY:<KEY>END_PI, challenge.altName)
}
{
id: player.name,
name: altName || player.name,
team: team,
ratingKey: alts.PI:KEY:<KEY>END_PIId(player.name, altName)
}
]
id = @createBattle(challenge.format, teams, challenge.conditions)
challenger = @users.get(challengerId)
challenger.send("challengeSuccess", player.name)
player.send("challengeSuccess", challengerId)
delete @challenges[challengerId][player.name]
return id
rejectChallenge: (player, challengerId) ->
if !@challenges[challengerId]?[player.name]?
errorMessage = "The challenge no longer exists."
player.error(errors.PRIVATE_MESSAGE, challengerId, errorMessage)
return false
delete @challenges[challengerId][player.name]
player.send("rejectChallenge", challengerId)
challenger = @users.get(challengerId)
challenger.send("rejectChallenge", player.name)
cancelChallenge: (player, challengeeId) ->
if !@challenges[player.name]?[challengeeId]?
errorMessage = "The challenge no longer exists."
player.error(errors.PRIVATE_MESSAGE, challengeeId, errorMessage)
return false
delete @challenges[player.name][challengeeId]
player.send("cancelChallenge", challengeeId)
challengee = @users.get(challengeeId)
challengee.send("cancelChallenge", player.name)
stopChallenges: (player) ->
playerId = player.name
for challengeeId of @challenges[playerId]
@cancelChallenge(player, challengeeId)
delete @challenges[playerId]
for challengerId of @challenges
if @challenges[challengerId][playerId]
@rejectChallenge(player, challengerId)
# Adds the player to the queue. Note that there is no validation on whether altName
# is correct, so make
queuePlayer: (playerId, team, format = DEFAULT_FORMAT, altName) ->
if @isLockedDown()
err = ["The server is restarting after all battles complete. No new battles can start at this time."]
else if format != DEFAULT_FORMAT
# TODO: Implement ratings for other formats
err = ["The server doesn't support this ladder at this time. Please ask for challenges instead."]
else
err = @validateTeam(team, format, FIND_BATTLE_CONDITIONS)
if err.length == 0
name = @users.get(playerId).name
ratingKey = alts.uniqueId(playerId, altName)
@queues[format].add(playerId, altName || name, team, ratingKey)
return err
queuedPlayers: (format = DEFAULT_FORMAT) ->
@queues[format].queuedPlayers()
removePlayer: (playerId, format = DEFAULT_FORMAT) ->
return false if format not of @queues
@queues[format].remove(playerId)
return true
beginBattles: (next) ->
array = for format in Object.keys(Formats)
do (format) => (callback) =>
@queues[format].pairPlayers (err, pairs) =>
if err then return callback(err)
# Create a battle for each pair
battleIds = []
for pair in pairs
id = @createBattle(format, pair, FIND_BATTLE_CONDITIONS)
battleIds.push(id)
callback(null, battleIds)
async.parallel array, (err, battleIds) ->
return next(err) if err
next(null, _.flatten(battleIds))
return true
# Creates a battle and returns its battleId
createBattle: (rawFormat = DEFAULT_FORMAT, pair = [], conditions = []) ->
format = Formats[rawFormat]
generation = format.generation
conditions = conditions.concat(format.conditions)
{Battle} = require("../server/#{generation}/battle")
{BattleController} = require("../server/#{generation}/battle_controller")
playerIds = pair.map((user) -> user.name)
battleId = @generateBattleId(playerIds)
battle = new Battle(battleId, pair, format: rawFormat, conditions: _.clone(conditions))
@battles[battleId] = new BattleController(battle)
for player in pair
# Add user to spectators
# TODO: player.id should be using player.name, but alts present a problem.
user = @users.get(player.id)
battle.add(spark) for spark in user.sparks
# Add/remove player ids to/from user battles
@userBattles[player.id] ?= {}
@userBattles[player.id][battleId] = true
# Add the player to the list if its not an alt
if player.id == player.ratingKey # hacky - but no alternative right now
@visibleUserBattles[player.id] ?= {}
@visibleUserBattles[player.id][battleId] = true
battle.once 'end', @removeUserBattle.bind(this, player.id, player.name, battleId)
battle.once 'expire', @removeBattle.bind(this, battleId)
# Add the battle to the achievements system
# Uneligible battles are ignored by this function
achievements.registerBattle(this, battle)
@rooms.push(battle)
@battles[battleId].beginBattle()
battleId
# Generate a random ID for a new battle.
generateBattleId: (players) ->
hmac = createHmac('sha1', config.SECRET_KEY)
hmac.update((new Date).toISOString())
for id in players
hmac.update(id)
hmac.digest('hex')
# Returns the battle with battleId.
findBattle: (battleId) ->
@battles[battleId]
getUserBattles: (userId) ->
(id for id, value of @userBattles[userId])
# Returns all non-alt battles the user is playing in
getVisibleUserBattles: (username) ->
(id for id, value of @visibleUserBattles[username])
getOngoingBattles: ->
# TODO: This is very inefficient. Improve this.
_.chain(@battles).values().reject((b) -> b.battle.isOver()).value()
removeUserBattle: (userId, username, battleId) ->
delete @userBattles[userId][battleId]
delete @visibleUserBattles[username]?[battleId]
removeBattle: (battleId) ->
for room, i in @rooms
if room.name == battleId
@rooms.splice(i, 1)
break
delete @battles[battleId]
# A length of -1 denotes a permanent ban.
ban: (username, reason, length = -1) ->
auth.ban(username, reason, length)
if user = @users.get(username)
user.error(errors.BANNED, reason, length)
user.close()
unban: (username, next) ->
auth.unban(username, next)
mute: (username, reason, length) ->
auth.mute(username, reason, length)
unmute: (username) ->
auth.unmute(username)
announce: (message) ->
for room in @rooms
room.announce("warning", message)
userMessage: (user, room, message) ->
@runIfUnmuted user, room.name, ->
room.userMessage(user, message)
runIfUnmuted: (user, roomId, next) ->
auth.getMuteTTL user.name, (err, ttl) ->
if ttl == -2
next()
else
user.announce(roomId, 'warning', "You are muted for another #{ttl} seconds!")
setAuthority: (user, newAuthority) ->
user = @users.get(user) if user not instanceof User
user.authority = newAuthority if user
limit: (player, kind, options, next) ->
attributes =
max: options.max
duration: options.duration
id: player.id
db: redis
@limiters[player.id][kind] ?= new Limiter(attributes)
@limiters[player.id][kind].get(next)
lockdown: ->
@canBattlesStart = false
for user in @users.getUsers()
@stopChallenges(user)
@announce("<strong>The server is restarting!</strong> We're waiting for all battles to finish to push some updates. No new battles may start at this time.")
unlockdown: ->
@canBattlesStart = true
@announce("<strong>Battles have been unlocked!</strong> You may battle again.")
isLockedDown: ->
!@canBattlesStart
# Returns an empty array if the given team is valid, an array of errors
# otherwise.
validateTeam: (team, format = DEFAULT_FORMAT, conditions = []) ->
return [ "Invalid format: #{format}." ] if format not of Formats
format = Formats[format]
return [ "Invalid team format." ] if team not instanceof Array
return [ "Team must have 1 to 6 Pokemon." ] unless 1 <= team.length <= 6
conditions = conditions.concat(format.conditions)
genData = gen.GenerationJSON[format.generation.toUpperCase()]
err = require('./conditions').validateTeam(conditions, team, genData)
return err if err.length > 0
err = team.map (pokemon, i) =>
@validatePokemon(conditions, pokemon, i + 1, format.generation)
return _.flatten(err)
# Returns an empty array if the given Pokemon is valid, an array of errors
# otherwise.
validatePokemon: (conditions, pokemon, slot, generation = gen.DEFAULT_GENERATION) ->
genData = gen.GenerationJSON[generation.toUpperCase()]
{SpeciesData, FormeData, MoveData} = genData
err = []
prefix = "Slot ##{slot}"
if !pokemon.species
err.push("#{prefix}: No species given.")
return err
species = SpeciesData[pokemon.species]
if !species
err.push("#{prefix}: Invalid species: #{pokemon.species}.")
return err
prefix += " (#{pokemon.species})"
@normalizePokemon(pokemon, generation)
forme = FormeData[pokemon.species][pokemon.forme]
if !forme
err.push("#{prefix}: Invalid forme: #{pokemon.forme}.")
return err
if forme.isBattleOnly
err.push("#{prefix}: #{pokemon.forme} forme is battle-only.")
return err
unless 0 < pokemon.name.length <= MAX_NICKNAME_LENGTH
err.push("#{prefix}: Nickname cannot be blank or be
#{MAX_NICKNAME_LENGTH} characters or higher.")
return err
if pokemon.name != pokemon.species && pokemon.name of SpeciesData
err.push("#{prefix}: Nickname cannot be another Pokemon's name.")
return err
if /[\u0300-\u036F\u20D0-\u20FF\uFE20-\uFE2F]/.test(pokemon.name)
err.push("#{prefix}: Nickname cannot contain some special characters.")
return err
if isNaN(pokemon.level)
err.push("#{prefix}: Invalid level: #{pokemon.level}.")
# TODO: 100 is a magic constant
else if !(1 <= pokemon.level <= 100)
err.push("#{prefix}: Level must be between 1 and 100.")
if pokemon.gender not in [ "M", "F", "Genderless" ]
err.push("#{prefix}: Invalid gender: #{pokemon.gender}.")
if species.genderRatio == -1 && pokemon.gender != "Genderless"
err.push("#{prefix}: Must be genderless.")
if species.genderRatio == 0 && pokemon.gender != "M"
err.push("#{prefix}: Must be male.")
if species.genderRatio == 8 && pokemon.gender != "F"
err.push("#{prefix}: Must be female.")
if (typeof pokemon.evs != "object")
err.push("#{prefix}: Invalid evs.")
if (typeof pokemon.ivs != "object")
err.push("#{prefix}: Invalid ivs.")
if !_.chain(pokemon.evs).values().all((ev) -> 0 <= ev <= 255).value()
err.push("#{prefix}: EVs must be between 0 and 255.")
if !_.chain(pokemon.ivs).values().all((iv) -> 0 <= iv <= 31).value()
err.push("#{prefix}: IVs must be between 0 and 31.")
if _.values(pokemon.evs).reduce(((x, y) -> x + y), 0) > 510
err.push("#{prefix}: EV total must be less than 510.")
if pokemon.ability not in forme["abilities"] &&
pokemon.ability != forme["hiddenAbility"]
err.push("#{prefix}: Invalid ability.")
if pokemon.moves not instanceof Array
err.push("#{prefix}: Invalid moves.")
# TODO: 4 is a magic constant
else if !(1 <= pokemon.moves.length <= 4)
err.push("#{prefix}: Must have 1 to 4 moves.")
else if !_(pokemon.moves).all((name) -> MoveData[name]?)
invalidMove = _(pokemon.moves).find((name) -> !MoveData[name]?)
err.push("#{prefix}: Invalid move name: #{invalidMove}")
else if !learnsets.checkMoveset(gen.GenerationJSON, pokemon,
gen.GENERATION_TO_INT[generation], pokemon.moves)
err.push("#{prefix}: Invalid moveset.")
err.push require('./conditions').validatePokemon(conditions, pokemon, genData, prefix)...
return err
# Normalizes a Pokemon by setting default values where applicable.
# Assumes that the Pokemon is a real Pokemon (i.e. its species/forme is valid)
normalizePokemon: (pokemon, generation = gen.DEFAULT_GENERATION) ->
{SpeciesData, FormeData} = gen.GenerationJSON[generation.toUpperCase()]
pokemon.forme ?= "default"
pokemon.name ?= pokemon.species
pokemon.ability ?= FormeData[pokemon.species][pokemon.forme]?["abilities"][0]
if !pokemon.gender?
{genderRatio} = SpeciesData[pokemon.species]
if genderRatio == -1 then pokemon.gender = "Genderless"
else if Math.random() < (genderRatio / 8) then pokemon.gender = "F"
else pokemon.gender = "M"
pokemon.evs ?= {}
pokemon.ivs ?= {}
pokemon.level ?= 100
pokemon.level = Math.floor(pokemon.level)
return pokemon
|
[
{
"context": "d] - Resumes check by id\n#\n# Forked from script by patcon@myplanetdigital\n\napiKey = process.env.HUBOT_UPTIMEROBOT_APIKEY\n\nm",
"end": 344,
"score": 0.952419102191925,
"start": 322,
"tag": "EMAIL",
"value": "patcon@myplanetdigital"
}
] | scripts/uptimerobot.coffee | wunderkraut/care-hubot | 0 | # Description
# A hubot script to list, pause and resume monitor checks
#
# Configuration:
# HUBOT_UPTIMEROBOT_APIKEY
#
# Commands:
# hubot uptime list - Lists all checks in private message
# hubot uptime pause [id] - Pauses check by id
# hubot uptime resume [id] - Resumes check by id
#
# Forked from script by patcon@myplanetdigital
apiKey = process.env.HUBOT_UPTIMEROBOT_APIKEY
module.exports = (robot) ->
robot.respond /uptime help/i, (msg) ->
msg.send "List of available commands:"
msg.send "uptime list - lists all checks in private message"
msg.send "uptime pause [id] - pauses check by id"
msg.send "uptime resume [id] - resumes check by id"
robot.respond /uptime list/i, (msg) ->
msg.send "@" + msg.message.user.mention_name + " sent details as private message"
Client = require 'uptime-robot'
client = new Client apiKey
filter = msg.match[2]
data = {}
client.getMonitors data, (err, res) ->
if err
throw err
monitors = res
if filter
query = require 'array-query'
monitors = query('friendlyname')
.regex(new RegExp filter, 'i')
.on res
for monitor, i in monitors
name = monitor.friendlyname
id = monitor.id
robot.send({
user: msg.message.user.jid
},
"#{name} -> #{id}");
| 134693 | # Description
# A hubot script to list, pause and resume monitor checks
#
# Configuration:
# HUBOT_UPTIMEROBOT_APIKEY
#
# Commands:
# hubot uptime list - Lists all checks in private message
# hubot uptime pause [id] - Pauses check by id
# hubot uptime resume [id] - Resumes check by id
#
# Forked from script by <EMAIL>
apiKey = process.env.HUBOT_UPTIMEROBOT_APIKEY
module.exports = (robot) ->
robot.respond /uptime help/i, (msg) ->
msg.send "List of available commands:"
msg.send "uptime list - lists all checks in private message"
msg.send "uptime pause [id] - pauses check by id"
msg.send "uptime resume [id] - resumes check by id"
robot.respond /uptime list/i, (msg) ->
msg.send "@" + msg.message.user.mention_name + " sent details as private message"
Client = require 'uptime-robot'
client = new Client apiKey
filter = msg.match[2]
data = {}
client.getMonitors data, (err, res) ->
if err
throw err
monitors = res
if filter
query = require 'array-query'
monitors = query('friendlyname')
.regex(new RegExp filter, 'i')
.on res
for monitor, i in monitors
name = monitor.friendlyname
id = monitor.id
robot.send({
user: msg.message.user.jid
},
"#{name} -> #{id}");
| true | # Description
# A hubot script to list, pause and resume monitor checks
#
# Configuration:
# HUBOT_UPTIMEROBOT_APIKEY
#
# Commands:
# hubot uptime list - Lists all checks in private message
# hubot uptime pause [id] - Pauses check by id
# hubot uptime resume [id] - Resumes check by id
#
# Forked from script by PI:EMAIL:<EMAIL>END_PI
apiKey = process.env.HUBOT_UPTIMEROBOT_APIKEY
module.exports = (robot) ->
robot.respond /uptime help/i, (msg) ->
msg.send "List of available commands:"
msg.send "uptime list - lists all checks in private message"
msg.send "uptime pause [id] - pauses check by id"
msg.send "uptime resume [id] - resumes check by id"
robot.respond /uptime list/i, (msg) ->
msg.send "@" + msg.message.user.mention_name + " sent details as private message"
Client = require 'uptime-robot'
client = new Client apiKey
filter = msg.match[2]
data = {}
client.getMonitors data, (err, res) ->
if err
throw err
monitors = res
if filter
query = require 'array-query'
monitors = query('friendlyname')
.regex(new RegExp filter, 'i')
.on res
for monitor, i in monitors
name = monitor.friendlyname
id = monitor.id
robot.send({
user: msg.message.user.jid
},
"#{name} -> #{id}");
|
[
{
"context": "ion default false]\n }\n jsonStr = '{\"name\": \"ylw\", \"age\": \"12\"}'\n javaSrc = j2j.toJava jsonStr,",
"end": 599,
"score": 0.5201805830001831,
"start": 596,
"tag": "NAME",
"value": "ylw"
}
] | lib/gen-code/json-java-db-xutils.coffee | yuanliwei/generate | 0 | ClassModel = require '../model/class-model'
Modifiers = require '../model/modifiers'
Filed = require '../model/filed'
StringUtil = require '../utils/string-util'
###
JSON 转 Java model
使用:
Json2Java = require './json-java'
j2j = new Json2Java()
[option]
opts = {
packageName: 'com.ylw.generate' [option]
className: 'TestClass' [require]
genSetter: true [option default true]
genGetter: true [option default true]
genInnerClass: false [option default false]
}
jsonStr = '{"name": "ylw", "age": "12"}'
javaSrc = j2j.toJava jsonStr, opts
console.log javaSrc
###
module.exports = class Json2Java
constructor: () ->
@className = 'ClassName'
@genSetter = true
@genGetter = true
@genInnerClass = false
toJava: (jsonStr, opts) ->
@packageName = opts.packageName if 'packageName' of opts
@className = opts.className if 'className' of opts
@genSetter = opts.genSetter if 'genSetter' of opts
@genGetter = opts.genGetter if 'genGetter' of opts
@genInnerClass = opts.genInnerClass if 'genInnerClass' of opts
model = @getModel @className
model.package = @packageName
jsObj = JSON.parse jsonStr
@parseJsonToJava jsObj, model
builder = []
model.toSource builder
# console.dir model
java_src = builder.join('\n')
jsBeautify = require('js-beautify').js_beautify
b_java_src = jsBeautify(java_src, { })
getModel: (name)->
model = new DbCLassModel()
model.name = name
model.genGetter = @genGetter
model.genSetter = @genSetter
model
parseJsonToJava: (jsObj, model) ->
# window.jsObj = jsObj
# console.dir jsObj
switch ((jsObj).constructor)
when Object
# console.log "Object"
@parseJsonObject jsObj, model
when Array
console.log "Array"
when String
console.log "String"
when Number
console.log "Number"
when Boolean
console.log "Boolean"
parseJsonObject: (jsObj, model) ->
for name of jsObj
# console.log name
# (type, @name, @value, @comment)
value = jsObj[name]
type = @getType value, name, model
comment = JSON.stringify value
filed = new DbFiled(type, name, null, comment)
model.fileds.push filed
# name
getType: (jsObj, name, model) ->
switch ((jsObj).constructor)
when Object
name_ = StringUtil.format name, 2, 0
console.dir @genInnerClass
if @genInnerClass
innerModel = @getModel name_
model.innerClass.push innerModel
@parseJsonToJava jsObj, innerModel
name_
when Array
name_ = StringUtil.format name, 2, 0
if @genInnerClass
innerModel = @getModel name_
model.innerClass.push innerModel
@parseJsonToJava jsObj[0], innerModel if jsObj.length > 0
"List<#{name_}>"
when String
"String"
when Number
vstr = "#{jsObj}"
if vstr.match /^-?\d{1,10}$/
"int"
else if vstr.match /^-?\d+$/
"long"
else if vstr.match /^-?\d+\.\d+$/
"float"
else
"Number"
when Boolean
"boolean"
else "unkonwn type"
###
判断js数据类型
console.log([].constructor == Array);
console.log({}.constructor == Object);
console.log("string".constructor == String);
console.log((123).constructor == Number);
console.log(true.constructor == Boolean);
###
class DbCLassModel extends ClassModel
genClassName: (builder) ->
# @Table(name = "tree_chapter_info")
tem = '@Table(name = "{0}")'
tableName = StringUtil.format @name, 3
builder.push(tem.format(tableName))
super builder
genNormalFiled: (builder) ->
first = true
@fileds.forEach (filed) ->
if (filed.modifier & Modifiers.static) == 0
filed.toSource(builder, first)
first = false
class DbFiled extends Filed
toSource: (buffer, first) ->
# @Id(column = "id")
# @Column(column = "pid")
tem
if first
tem = '@Id(column = "{0}")'
if @type == 'int' or @type == 'long'
tem += '\n@NoAutoIncrement'
else
tem = '@Column(column = "{0}")'
columeName = StringUtil.format @name, 4
buffer.push tem.format columeName
tem = '{0} {1} {2}{3};{4}'
name_ = StringUtil.format @name, 2
buffer.push StringUtil.formatStr tem, @getModifier(), @type, name_, @getValue(), @getComment()
| 209172 | ClassModel = require '../model/class-model'
Modifiers = require '../model/modifiers'
Filed = require '../model/filed'
StringUtil = require '../utils/string-util'
###
JSON 转 Java model
使用:
Json2Java = require './json-java'
j2j = new Json2Java()
[option]
opts = {
packageName: 'com.ylw.generate' [option]
className: 'TestClass' [require]
genSetter: true [option default true]
genGetter: true [option default true]
genInnerClass: false [option default false]
}
jsonStr = '{"name": "<NAME>", "age": "12"}'
javaSrc = j2j.toJava jsonStr, opts
console.log javaSrc
###
module.exports = class Json2Java
constructor: () ->
@className = 'ClassName'
@genSetter = true
@genGetter = true
@genInnerClass = false
toJava: (jsonStr, opts) ->
@packageName = opts.packageName if 'packageName' of opts
@className = opts.className if 'className' of opts
@genSetter = opts.genSetter if 'genSetter' of opts
@genGetter = opts.genGetter if 'genGetter' of opts
@genInnerClass = opts.genInnerClass if 'genInnerClass' of opts
model = @getModel @className
model.package = @packageName
jsObj = JSON.parse jsonStr
@parseJsonToJava jsObj, model
builder = []
model.toSource builder
# console.dir model
java_src = builder.join('\n')
jsBeautify = require('js-beautify').js_beautify
b_java_src = jsBeautify(java_src, { })
getModel: (name)->
model = new DbCLassModel()
model.name = name
model.genGetter = @genGetter
model.genSetter = @genSetter
model
parseJsonToJava: (jsObj, model) ->
# window.jsObj = jsObj
# console.dir jsObj
switch ((jsObj).constructor)
when Object
# console.log "Object"
@parseJsonObject jsObj, model
when Array
console.log "Array"
when String
console.log "String"
when Number
console.log "Number"
when Boolean
console.log "Boolean"
parseJsonObject: (jsObj, model) ->
for name of jsObj
# console.log name
# (type, @name, @value, @comment)
value = jsObj[name]
type = @getType value, name, model
comment = JSON.stringify value
filed = new DbFiled(type, name, null, comment)
model.fileds.push filed
# name
getType: (jsObj, name, model) ->
switch ((jsObj).constructor)
when Object
name_ = StringUtil.format name, 2, 0
console.dir @genInnerClass
if @genInnerClass
innerModel = @getModel name_
model.innerClass.push innerModel
@parseJsonToJava jsObj, innerModel
name_
when Array
name_ = StringUtil.format name, 2, 0
if @genInnerClass
innerModel = @getModel name_
model.innerClass.push innerModel
@parseJsonToJava jsObj[0], innerModel if jsObj.length > 0
"List<#{name_}>"
when String
"String"
when Number
vstr = "#{jsObj}"
if vstr.match /^-?\d{1,10}$/
"int"
else if vstr.match /^-?\d+$/
"long"
else if vstr.match /^-?\d+\.\d+$/
"float"
else
"Number"
when Boolean
"boolean"
else "unkonwn type"
###
判断js数据类型
console.log([].constructor == Array);
console.log({}.constructor == Object);
console.log("string".constructor == String);
console.log((123).constructor == Number);
console.log(true.constructor == Boolean);
###
class DbCLassModel extends ClassModel
genClassName: (builder) ->
# @Table(name = "tree_chapter_info")
tem = '@Table(name = "{0}")'
tableName = StringUtil.format @name, 3
builder.push(tem.format(tableName))
super builder
genNormalFiled: (builder) ->
first = true
@fileds.forEach (filed) ->
if (filed.modifier & Modifiers.static) == 0
filed.toSource(builder, first)
first = false
class DbFiled extends Filed
toSource: (buffer, first) ->
# @Id(column = "id")
# @Column(column = "pid")
tem
if first
tem = '@Id(column = "{0}")'
if @type == 'int' or @type == 'long'
tem += '\n@NoAutoIncrement'
else
tem = '@Column(column = "{0}")'
columeName = StringUtil.format @name, 4
buffer.push tem.format columeName
tem = '{0} {1} {2}{3};{4}'
name_ = StringUtil.format @name, 2
buffer.push StringUtil.formatStr tem, @getModifier(), @type, name_, @getValue(), @getComment()
| true | ClassModel = require '../model/class-model'
Modifiers = require '../model/modifiers'
Filed = require '../model/filed'
StringUtil = require '../utils/string-util'
###
JSON 转 Java model
使用:
Json2Java = require './json-java'
j2j = new Json2Java()
[option]
opts = {
packageName: 'com.ylw.generate' [option]
className: 'TestClass' [require]
genSetter: true [option default true]
genGetter: true [option default true]
genInnerClass: false [option default false]
}
jsonStr = '{"name": "PI:NAME:<NAME>END_PI", "age": "12"}'
javaSrc = j2j.toJava jsonStr, opts
console.log javaSrc
###
module.exports = class Json2Java
constructor: () ->
@className = 'ClassName'
@genSetter = true
@genGetter = true
@genInnerClass = false
toJava: (jsonStr, opts) ->
@packageName = opts.packageName if 'packageName' of opts
@className = opts.className if 'className' of opts
@genSetter = opts.genSetter if 'genSetter' of opts
@genGetter = opts.genGetter if 'genGetter' of opts
@genInnerClass = opts.genInnerClass if 'genInnerClass' of opts
model = @getModel @className
model.package = @packageName
jsObj = JSON.parse jsonStr
@parseJsonToJava jsObj, model
builder = []
model.toSource builder
# console.dir model
java_src = builder.join('\n')
jsBeautify = require('js-beautify').js_beautify
b_java_src = jsBeautify(java_src, { })
getModel: (name)->
model = new DbCLassModel()
model.name = name
model.genGetter = @genGetter
model.genSetter = @genSetter
model
parseJsonToJava: (jsObj, model) ->
# window.jsObj = jsObj
# console.dir jsObj
switch ((jsObj).constructor)
when Object
# console.log "Object"
@parseJsonObject jsObj, model
when Array
console.log "Array"
when String
console.log "String"
when Number
console.log "Number"
when Boolean
console.log "Boolean"
parseJsonObject: (jsObj, model) ->
for name of jsObj
# console.log name
# (type, @name, @value, @comment)
value = jsObj[name]
type = @getType value, name, model
comment = JSON.stringify value
filed = new DbFiled(type, name, null, comment)
model.fileds.push filed
# name
getType: (jsObj, name, model) ->
switch ((jsObj).constructor)
when Object
name_ = StringUtil.format name, 2, 0
console.dir @genInnerClass
if @genInnerClass
innerModel = @getModel name_
model.innerClass.push innerModel
@parseJsonToJava jsObj, innerModel
name_
when Array
name_ = StringUtil.format name, 2, 0
if @genInnerClass
innerModel = @getModel name_
model.innerClass.push innerModel
@parseJsonToJava jsObj[0], innerModel if jsObj.length > 0
"List<#{name_}>"
when String
"String"
when Number
vstr = "#{jsObj}"
if vstr.match /^-?\d{1,10}$/
"int"
else if vstr.match /^-?\d+$/
"long"
else if vstr.match /^-?\d+\.\d+$/
"float"
else
"Number"
when Boolean
"boolean"
else "unkonwn type"
###
判断js数据类型
console.log([].constructor == Array);
console.log({}.constructor == Object);
console.log("string".constructor == String);
console.log((123).constructor == Number);
console.log(true.constructor == Boolean);
###
class DbCLassModel extends ClassModel
genClassName: (builder) ->
# @Table(name = "tree_chapter_info")
tem = '@Table(name = "{0}")'
tableName = StringUtil.format @name, 3
builder.push(tem.format(tableName))
super builder
genNormalFiled: (builder) ->
first = true
@fileds.forEach (filed) ->
if (filed.modifier & Modifiers.static) == 0
filed.toSource(builder, first)
first = false
class DbFiled extends Filed
toSource: (buffer, first) ->
# @Id(column = "id")
# @Column(column = "pid")
tem
if first
tem = '@Id(column = "{0}")'
if @type == 'int' or @type == 'long'
tem += '\n@NoAutoIncrement'
else
tem = '@Column(column = "{0}")'
columeName = StringUtil.format @name, 4
buffer.push tem.format columeName
tem = '{0} {1} {2}{3};{4}'
name_ = StringUtil.format @name, 2
buffer.push StringUtil.formatStr tem, @getModifier(), @type, name_, @getValue(), @getComment()
|
[
{
"context": "# Try POH\n# author: Leonardone @ NEETSDKASU\n\nprocess.stdin.resume()\nprocess.stdi",
"end": 30,
"score": 0.9995585680007935,
"start": 20,
"tag": "NAME",
"value": "Leonardone"
},
{
"context": "# Try POH\n# author: Leonardone @ NEETSDKASU\n\nprocess.stdin.resume()\nproc... | POH7/Mizugi/Main.coffee | neetsdkasu/Paiza-POH-MyAnswers | 3 | # Try POH
# author: Leonardone @ NEETSDKASU
process.stdin.resume()
process.stdin.setEncoding 'utf8'
process.stdin.on 'data', (data) ->
n = parseInt data.toString()
r = 1
c = 0
md = 1000000000
while n > 1
x = n--
while x % 5 == 0
x /= 5
c--
while x % 2 == 0
x /= 2
c++
r = (r * x) % md
while c-- > 0
r = (r * 2) % md
console.log r
| 149920 | # Try POH
# author: <NAME> @ NEETSDKASU
process.stdin.resume()
process.stdin.setEncoding 'utf8'
process.stdin.on 'data', (data) ->
n = parseInt data.toString()
r = 1
c = 0
md = 1000000000
while n > 1
x = n--
while x % 5 == 0
x /= 5
c--
while x % 2 == 0
x /= 2
c++
r = (r * x) % md
while c-- > 0
r = (r * 2) % md
console.log r
| true | # Try POH
# author: PI:NAME:<NAME>END_PI @ NEETSDKASU
process.stdin.resume()
process.stdin.setEncoding 'utf8'
process.stdin.on 'data', (data) ->
n = parseInt data.toString()
r = 1
c = 0
md = 1000000000
while n > 1
x = n--
while x % 5 == 0
x /= 5
c--
while x % 2 == 0
x /= 2
c++
r = (r * x) % md
while c-- > 0
r = (r * 2) % md
console.log r
|
[
{
"context": "nique-name', [\n {\n name: 'Test-package'\n action: 'added'\n }\n ",
"end": 3474,
"score": 0.6832570433616638,
"start": 3462,
"tag": "NAME",
"value": "Test-package"
},
{
"context": ".show bundles, null, [\n {\n ... | spec/name-view-spec.coffee | deprint/package-switch | 20 | { NameView } = require '../lib/name-view'
{ Bundles } = require '../lib/bundles'
describe 'Name View', ->
view = null
callbacks = null
bundles = null
beforeEach ->
bundles = new Bundles('')
bundles.addBundle 'already-used', [
{
name: 'Test-package'
action: 'added'
}
{
name: 'Test-package-2'
action: 'removed'
}
]
view = new NameView()
jasmine.attachToDOM(view.element)
callbacks = {
confirmCallback: jasmine.createSpy('confirm')
backCallback: jasmine.createSpy('back')
}
afterEach ->
view.destroy()
bundles.destroy()
expect(atom.workspace.getModalPanels()[0].visible).toBeFalsy()
describe 'When loading the view with items of both action types', ->
beforeEach ->
view.show bundles, null, [
{
name: 'Test-package'
action: 'added'
}
{
name: 'Test-package-2'
action: 'removed'
}
], callbacks
it 'attaches the view', ->
expect(atom.workspace.getModalPanels()[0].visible).toBeTruthy()
it 'shows the items', ->
expect(view.added.hasClass 'hidden').toBeFalsy()
expect(view.removed.hasClass 'hidden').toBeFalsy()
expect(view.added.html()).toBe 'Test-package'
expect(view.removed.html()).toBe 'Test-package-2'
describe 'When cancelling', ->
beforeEach ->
atom.commands.dispatch(view.element, 'core:cancel')
it 'detaches the view', ->
expect(atom.workspace.getModalPanels()[0].visible).toBeFalsy()
describe 'When clicking "Back"', ->
beforeEach ->
view.find('.icon-arrow-left').click()
it 'detaches the view', ->
expect(atom.workspace.getModalPanels()[0].visible).toBeFalsy()
it 'calls the backCallback', ->
expect(callbacks.backCallback).toHaveBeenCalledWith null, [
{
name: 'Test-package'
action: 'added'
}
{
name: 'Test-package-2'
action: 'removed'
}
]
describe 'When setting a name', ->
describe 'that is ""', ->
beforeEach ->
view.nameEditor.setText ''
view.find('.icon-check').click()
it 'shows an error', ->
expect(view.find('#name-error-none').hasClass 'hidden').toBeFalsy()
expect(view.find('#name-error-used').hasClass 'hidden').toBeTruthy()
it 'does not call the confirmCallback', ->
expect(callbacks.confirmCallback).not.toHaveBeenCalled()
describe 'that is already used', ->
beforeEach ->
view.nameEditor.setText 'already-used'
view.find('.icon-check').click()
it 'shows an error', ->
expect(view.find('#name-error-none').hasClass 'hidden').toBeTruthy()
expect(view.find('#name-error-used').hasClass 'hidden').toBeFalsy()
it 'does not call the confirmCallback', ->
expect(callbacks.confirmCallback).not.toHaveBeenCalled()
describe 'that is unique', ->
beforeEach ->
view.nameEditor.setText 'unique-name'
view.find('.icon-check').click()
it 'detaches the view', ->
expect(atom.workspace.getModalPanels()[0].visible).toBeFalsy()
it 'calls the callback function', ->
expect(callbacks.confirmCallback).toHaveBeenCalledWith null, 'unique-name', [
{
name: 'Test-package'
action: 'added'
}
{
name: 'Test-package-2'
action: 'removed'
}
]
describe 'When loading the view with items of one action type', ->
beforeEach ->
view.show bundles, null, [
{
name: 'Test-package'
action: 'added'
}
], callbacks
it 'attaches the view', ->
expect(atom.workspace.getModalPanels()[0].visible).toBeTruthy()
it 'shows the items', ->
expect(view.added.hasClass 'hidden').toBeFalsy()
expect(view.removed.hasClass 'hidden').toBeTruthy()
expect(view.added.html()).toBe 'Test-package'
| 172690 | { NameView } = require '../lib/name-view'
{ Bundles } = require '../lib/bundles'
describe 'Name View', ->
view = null
callbacks = null
bundles = null
beforeEach ->
bundles = new Bundles('')
bundles.addBundle 'already-used', [
{
name: 'Test-package'
action: 'added'
}
{
name: 'Test-package-2'
action: 'removed'
}
]
view = new NameView()
jasmine.attachToDOM(view.element)
callbacks = {
confirmCallback: jasmine.createSpy('confirm')
backCallback: jasmine.createSpy('back')
}
afterEach ->
view.destroy()
bundles.destroy()
expect(atom.workspace.getModalPanels()[0].visible).toBeFalsy()
describe 'When loading the view with items of both action types', ->
beforeEach ->
view.show bundles, null, [
{
name: 'Test-package'
action: 'added'
}
{
name: 'Test-package-2'
action: 'removed'
}
], callbacks
it 'attaches the view', ->
expect(atom.workspace.getModalPanels()[0].visible).toBeTruthy()
it 'shows the items', ->
expect(view.added.hasClass 'hidden').toBeFalsy()
expect(view.removed.hasClass 'hidden').toBeFalsy()
expect(view.added.html()).toBe 'Test-package'
expect(view.removed.html()).toBe 'Test-package-2'
describe 'When cancelling', ->
beforeEach ->
atom.commands.dispatch(view.element, 'core:cancel')
it 'detaches the view', ->
expect(atom.workspace.getModalPanels()[0].visible).toBeFalsy()
describe 'When clicking "Back"', ->
beforeEach ->
view.find('.icon-arrow-left').click()
it 'detaches the view', ->
expect(atom.workspace.getModalPanels()[0].visible).toBeFalsy()
it 'calls the backCallback', ->
expect(callbacks.backCallback).toHaveBeenCalledWith null, [
{
name: 'Test-package'
action: 'added'
}
{
name: 'Test-package-2'
action: 'removed'
}
]
describe 'When setting a name', ->
describe 'that is ""', ->
beforeEach ->
view.nameEditor.setText ''
view.find('.icon-check').click()
it 'shows an error', ->
expect(view.find('#name-error-none').hasClass 'hidden').toBeFalsy()
expect(view.find('#name-error-used').hasClass 'hidden').toBeTruthy()
it 'does not call the confirmCallback', ->
expect(callbacks.confirmCallback).not.toHaveBeenCalled()
describe 'that is already used', ->
beforeEach ->
view.nameEditor.setText 'already-used'
view.find('.icon-check').click()
it 'shows an error', ->
expect(view.find('#name-error-none').hasClass 'hidden').toBeTruthy()
expect(view.find('#name-error-used').hasClass 'hidden').toBeFalsy()
it 'does not call the confirmCallback', ->
expect(callbacks.confirmCallback).not.toHaveBeenCalled()
describe 'that is unique', ->
beforeEach ->
view.nameEditor.setText 'unique-name'
view.find('.icon-check').click()
it 'detaches the view', ->
expect(atom.workspace.getModalPanels()[0].visible).toBeFalsy()
it 'calls the callback function', ->
expect(callbacks.confirmCallback).toHaveBeenCalledWith null, 'unique-name', [
{
name: '<NAME>'
action: 'added'
}
{
name: 'Test-package-2'
action: 'removed'
}
]
describe 'When loading the view with items of one action type', ->
beforeEach ->
view.show bundles, null, [
{
name: '<NAME>-package'
action: 'added'
}
], callbacks
it 'attaches the view', ->
expect(atom.workspace.getModalPanels()[0].visible).toBeTruthy()
it 'shows the items', ->
expect(view.added.hasClass 'hidden').toBeFalsy()
expect(view.removed.hasClass 'hidden').toBeTruthy()
expect(view.added.html()).toBe 'Test-package'
| true | { NameView } = require '../lib/name-view'
{ Bundles } = require '../lib/bundles'
describe 'Name View', ->
view = null
callbacks = null
bundles = null
beforeEach ->
bundles = new Bundles('')
bundles.addBundle 'already-used', [
{
name: 'Test-package'
action: 'added'
}
{
name: 'Test-package-2'
action: 'removed'
}
]
view = new NameView()
jasmine.attachToDOM(view.element)
callbacks = {
confirmCallback: jasmine.createSpy('confirm')
backCallback: jasmine.createSpy('back')
}
afterEach ->
view.destroy()
bundles.destroy()
expect(atom.workspace.getModalPanels()[0].visible).toBeFalsy()
describe 'When loading the view with items of both action types', ->
beforeEach ->
view.show bundles, null, [
{
name: 'Test-package'
action: 'added'
}
{
name: 'Test-package-2'
action: 'removed'
}
], callbacks
it 'attaches the view', ->
expect(atom.workspace.getModalPanels()[0].visible).toBeTruthy()
it 'shows the items', ->
expect(view.added.hasClass 'hidden').toBeFalsy()
expect(view.removed.hasClass 'hidden').toBeFalsy()
expect(view.added.html()).toBe 'Test-package'
expect(view.removed.html()).toBe 'Test-package-2'
describe 'When cancelling', ->
beforeEach ->
atom.commands.dispatch(view.element, 'core:cancel')
it 'detaches the view', ->
expect(atom.workspace.getModalPanels()[0].visible).toBeFalsy()
describe 'When clicking "Back"', ->
beforeEach ->
view.find('.icon-arrow-left').click()
it 'detaches the view', ->
expect(atom.workspace.getModalPanels()[0].visible).toBeFalsy()
it 'calls the backCallback', ->
expect(callbacks.backCallback).toHaveBeenCalledWith null, [
{
name: 'Test-package'
action: 'added'
}
{
name: 'Test-package-2'
action: 'removed'
}
]
describe 'When setting a name', ->
describe 'that is ""', ->
beforeEach ->
view.nameEditor.setText ''
view.find('.icon-check').click()
it 'shows an error', ->
expect(view.find('#name-error-none').hasClass 'hidden').toBeFalsy()
expect(view.find('#name-error-used').hasClass 'hidden').toBeTruthy()
it 'does not call the confirmCallback', ->
expect(callbacks.confirmCallback).not.toHaveBeenCalled()
describe 'that is already used', ->
beforeEach ->
view.nameEditor.setText 'already-used'
view.find('.icon-check').click()
it 'shows an error', ->
expect(view.find('#name-error-none').hasClass 'hidden').toBeTruthy()
expect(view.find('#name-error-used').hasClass 'hidden').toBeFalsy()
it 'does not call the confirmCallback', ->
expect(callbacks.confirmCallback).not.toHaveBeenCalled()
describe 'that is unique', ->
beforeEach ->
view.nameEditor.setText 'unique-name'
view.find('.icon-check').click()
it 'detaches the view', ->
expect(atom.workspace.getModalPanels()[0].visible).toBeFalsy()
it 'calls the callback function', ->
expect(callbacks.confirmCallback).toHaveBeenCalledWith null, 'unique-name', [
{
name: 'PI:NAME:<NAME>END_PI'
action: 'added'
}
{
name: 'Test-package-2'
action: 'removed'
}
]
describe 'When loading the view with items of one action type', ->
beforeEach ->
view.show bundles, null, [
{
name: 'PI:NAME:<NAME>END_PI-package'
action: 'added'
}
], callbacks
it 'attaches the view', ->
expect(atom.workspace.getModalPanels()[0].visible).toBeTruthy()
it 'shows the items', ->
expect(view.added.hasClass 'hidden').toBeFalsy()
expect(view.removed.hasClass 'hidden').toBeTruthy()
expect(view.added.html()).toBe 'Test-package'
|
[
{
"context": "st <Magic the Gathering card name>\r\n# Author:\r\n# FaytLeingod\r\n\r\nmodule.exports = (robot) ->\r\n robot.r",
"end": 220,
"score": 0.8359100222587585,
"start": 217,
"tag": "NAME",
"value": "Fay"
},
{
"context": "Magic the Gathering card name>\r\n# Author:\r\n# ... | Hubot/MtG.coffee | FaytLeingod007/JabbR | 3 | # Description:
# Have Hubot look up a MtG card and return an image of it
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot cast <Magic the Gathering card name>
# Author:
# FaytLeingod
module.exports = (robot) ->
robot.respond /cast (.+)/i, (msg) ->
msg.http('https://api.scryfall.com/cards/named')
.query({
exact: msg.match[1]
})
.get() (err, res, body) ->
if err
msg.send "Encountered an error :( #{err}"
return
else
msg.send(JSON.parse(body).image_uris.normal) | 73667 | # Description:
# Have Hubot look up a MtG card and return an image of it
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot cast <Magic the Gathering card name>
# Author:
# <NAME>t<NAME>
module.exports = (robot) ->
robot.respond /cast (.+)/i, (msg) ->
msg.http('https://api.scryfall.com/cards/named')
.query({
exact: msg.match[1]
})
.get() (err, res, body) ->
if err
msg.send "Encountered an error :( #{err}"
return
else
msg.send(JSON.parse(body).image_uris.normal) | true | # Description:
# Have Hubot look up a MtG card and return an image of it
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot cast <Magic the Gathering card name>
# Author:
# PI:NAME:<NAME>END_PItPI:NAME:<NAME>END_PI
module.exports = (robot) ->
robot.respond /cast (.+)/i, (msg) ->
msg.http('https://api.scryfall.com/cards/named')
.query({
exact: msg.match[1]
})
.get() (err, res, body) ->
if err
msg.send "Encountered an error :( #{err}"
return
else
msg.send(JSON.parse(body).image_uris.normal) |
[
{
"context": "name: 'Azor'\nscopeName: 'azor'\ntype: 'tree-sitter'\nparser: 't",
"end": 11,
"score": 0.9792447090148926,
"start": 7,
"tag": "NAME",
"value": "Azor"
}
] | grammars/azor.cson | cstuartroe/language-azor | 0 | name: 'Azor'
scopeName: 'azor'
type: 'tree-sitter'
parser: 'tree-sitter-azor'
fileTypes: ['azor']
scopes:
'base_type > identifier, generics > identifier': 'entity.name.type',
'comment': 'comment',
'string': 'string',
'numeric, bool, char': 'constant.numeric.integer',
'''
definition > identifier,
simple > identifier,
list_unpack > identifier,
let > identifier,
tuple_of_identifiers > identifier,
generic_resolution > identifier,
''': 'punctuation.definition.identity',
'definition > "="': 'variable',
'''
definition > ":",
named_argument > ":",
list_unpack > "~",
expression > "~",
prefix > "-",
prefix > "!",
comparator,
logical,
add_sub,
mult_div,
exp
''': 'constant.other.symbol',
'named_argument > identifier': 'variable',
'''
let > "let",
let > "<-",
let > "in",
if > "if",
if > "then",
if > "else",
list_unpack > "<-",
empty_list > "of"
''': 'punctuation.definition.italic'
| 193749 | name: '<NAME>'
scopeName: 'azor'
type: 'tree-sitter'
parser: 'tree-sitter-azor'
fileTypes: ['azor']
scopes:
'base_type > identifier, generics > identifier': 'entity.name.type',
'comment': 'comment',
'string': 'string',
'numeric, bool, char': 'constant.numeric.integer',
'''
definition > identifier,
simple > identifier,
list_unpack > identifier,
let > identifier,
tuple_of_identifiers > identifier,
generic_resolution > identifier,
''': 'punctuation.definition.identity',
'definition > "="': 'variable',
'''
definition > ":",
named_argument > ":",
list_unpack > "~",
expression > "~",
prefix > "-",
prefix > "!",
comparator,
logical,
add_sub,
mult_div,
exp
''': 'constant.other.symbol',
'named_argument > identifier': 'variable',
'''
let > "let",
let > "<-",
let > "in",
if > "if",
if > "then",
if > "else",
list_unpack > "<-",
empty_list > "of"
''': 'punctuation.definition.italic'
| true | name: 'PI:NAME:<NAME>END_PI'
scopeName: 'azor'
type: 'tree-sitter'
parser: 'tree-sitter-azor'
fileTypes: ['azor']
scopes:
'base_type > identifier, generics > identifier': 'entity.name.type',
'comment': 'comment',
'string': 'string',
'numeric, bool, char': 'constant.numeric.integer',
'''
definition > identifier,
simple > identifier,
list_unpack > identifier,
let > identifier,
tuple_of_identifiers > identifier,
generic_resolution > identifier,
''': 'punctuation.definition.identity',
'definition > "="': 'variable',
'''
definition > ":",
named_argument > ":",
list_unpack > "~",
expression > "~",
prefix > "-",
prefix > "!",
comparator,
logical,
add_sub,
mult_div,
exp
''': 'constant.other.symbol',
'named_argument > identifier': 'variable',
'''
let > "let",
let > "<-",
let > "in",
if > "if",
if > "then",
if > "else",
list_unpack > "<-",
empty_list > "of"
''': 'punctuation.definition.italic'
|
[
{
"context": "urvey</a>?</p>\n\n<p>Thank you in advance.</p>\n\n<p>\nHenry <br>\nShareLaTeX Co-founder\n</p>\n'''\n\ntemplates.pa",
"end": 1200,
"score": 0.9996678233146667,
"start": 1195,
"tag": "NAME",
"value": "Henry"
}
] | app/coffee/Features/Email/EmailBuilder.coffee | bowlofstew/web-sharelatex | 0 | _ = require('underscore')
PersonalEmailLayout = require("./Layouts/PersonalEmailLayout")
NotificationEmailLayout = require("./Layouts/NotificationEmailLayout")
settings = require("settings-sharelatex")
templates = {}
templates.registered =
subject: _.template "Activate your #{settings.appName} Account"
layout: PersonalEmailLayout
type: "notification"
compiledTemplate: _.template """
<p>Congratulations, you've just had an account created for you on #{settings.appName} with the email address "<%= to %>".</p>
<p><a href="<%= setNewPasswordUrl %>">Click here to set your password and log in.</a></p>
<p>If you have any questions or problems, please contact <a href="mailto:#{settings.adminEmail}">#{settings.adminEmail}</a>.</p>
"""
templates.canceledSubscription =
subject: _.template "ShareLaTeX thoughts"
layout: PersonalEmailLayout
type:"lifecycle"
compiledTemplate: _.template '''
<p>Hi <%= first_name %>,</p>
<p>I'm sorry to see you cancelled your ShareLaTeX premium account. Would you mind giving me some advice on what the site is lacking at the moment via <a href="https://sharelatex.typeform.com/to/F7OzIY">this survey</a>?</p>
<p>Thank you in advance.</p>
<p>
Henry <br>
ShareLaTeX Co-founder
</p>
'''
templates.passwordResetRequested =
subject: _.template "Password Reset - #{settings.appName}"
layout: NotificationEmailLayout
type:"notification"
compiledTemplate: _.template """
<h2>Password Reset</h2>
<p>
We got a request to reset your #{settings.appName} password.
<p>
<center>
<div style="width:200px;background-color:#a93629;border:1px solid #e24b3b;border-radius:3px;padding:15px; margin:24px;">
<div style="padding-right:10px;padding-left:10px">
<a href="<%= setNewPasswordUrl %>" style="text-decoration:none" target="_blank">
<span style= "font-size:16px;font-family:Arial;font-weight:bold;color:#fff;white-space:nowrap;display:block; text-align:center">
Reset password
</span>
</a>
</div>
</div>
</center>
If you ignore this message, your password won't be changed.
<p>
If you didn't request a password reset, let us know.
</p>
<p>Thank you</p>
<p> <a href="<%= siteUrl %>">#{settings.appName}</a></p>
"""
templates.projectSharedWithYou =
subject: _.template "<%= owner.email %> wants to share <%= project.name %> with you"
layout: NotificationEmailLayout
type:"notification"
compiledTemplate: _.template """
<p>Hi, <%= owner.email %> wants to share <a href="<%= project.url %>">'<%= project.name %>'</a> with you</p>
<center>
<div style="width:200px;background-color:#a93629;border:1px solid #e24b3b;border-radius:3px;padding:15px; margin:24px;">
<div style="padding-right:10px;padding-left:10px">
<a href="<%= project.url %>" style="text-decoration:none" target="_blank">
<span style= "font-size:16px;font-family:Helvetica,Arial;font-weight:400;color:#fff;white-space:nowrap;display:block; text-align:center">
View Project
</span>
</a>
</div>
</div>
</center>
<p> Thank you</p>
<p> <a href="<%= siteUrl %>">#{settings.appName}</a></p>
"""
templates.completeJoinGroupAccount =
subject: _.template "Verify Email to join <%= group_name %> group"
layout: NotificationEmailLayout
type:"notification"
compiledTemplate: _.template """
<p>Hi, please verify your email to join the <%= group_name %> and get your free premium account</p>
<center>
<div style="width:200px;background-color:#a93629;border:1px solid #e24b3b;border-radius:3px;padding:15px; margin:24px;">
<div style="padding-right:10px;padding-left:10px">
<a href="<%= completeJoinUrl %>" style="text-decoration:none" target="_blank">
<span style= "font-size:16px;font-family:Helvetica,Arial;font-weight:400;color:#fff;white-space:nowrap;display:block; text-align:center">
Verify now
</span>
</a>
</div>
</div>
</center>
<p> Thank you</p>
<p> <a href="<%= siteUrl %>">#{settings.appName}</a></p>
"""
module.exports =
templates: templates
buildEmail: (templateName, opts)->
template = templates[templateName]
opts.siteUrl = settings.siteUrl
opts.body = template.compiledTemplate(opts)
if settings.email?.templates?.customFooter?
opts.body += settings.email?.templates?.customFooter
return {
subject : template.subject(opts)
html: template.layout(opts)
type:template.type
}
| 99376 | _ = require('underscore')
PersonalEmailLayout = require("./Layouts/PersonalEmailLayout")
NotificationEmailLayout = require("./Layouts/NotificationEmailLayout")
settings = require("settings-sharelatex")
templates = {}
templates.registered =
subject: _.template "Activate your #{settings.appName} Account"
layout: PersonalEmailLayout
type: "notification"
compiledTemplate: _.template """
<p>Congratulations, you've just had an account created for you on #{settings.appName} with the email address "<%= to %>".</p>
<p><a href="<%= setNewPasswordUrl %>">Click here to set your password and log in.</a></p>
<p>If you have any questions or problems, please contact <a href="mailto:#{settings.adminEmail}">#{settings.adminEmail}</a>.</p>
"""
templates.canceledSubscription =
subject: _.template "ShareLaTeX thoughts"
layout: PersonalEmailLayout
type:"lifecycle"
compiledTemplate: _.template '''
<p>Hi <%= first_name %>,</p>
<p>I'm sorry to see you cancelled your ShareLaTeX premium account. Would you mind giving me some advice on what the site is lacking at the moment via <a href="https://sharelatex.typeform.com/to/F7OzIY">this survey</a>?</p>
<p>Thank you in advance.</p>
<p>
<NAME> <br>
ShareLaTeX Co-founder
</p>
'''
templates.passwordResetRequested =
subject: _.template "Password Reset - #{settings.appName}"
layout: NotificationEmailLayout
type:"notification"
compiledTemplate: _.template """
<h2>Password Reset</h2>
<p>
We got a request to reset your #{settings.appName} password.
<p>
<center>
<div style="width:200px;background-color:#a93629;border:1px solid #e24b3b;border-radius:3px;padding:15px; margin:24px;">
<div style="padding-right:10px;padding-left:10px">
<a href="<%= setNewPasswordUrl %>" style="text-decoration:none" target="_blank">
<span style= "font-size:16px;font-family:Arial;font-weight:bold;color:#fff;white-space:nowrap;display:block; text-align:center">
Reset password
</span>
</a>
</div>
</div>
</center>
If you ignore this message, your password won't be changed.
<p>
If you didn't request a password reset, let us know.
</p>
<p>Thank you</p>
<p> <a href="<%= siteUrl %>">#{settings.appName}</a></p>
"""
templates.projectSharedWithYou =
subject: _.template "<%= owner.email %> wants to share <%= project.name %> with you"
layout: NotificationEmailLayout
type:"notification"
compiledTemplate: _.template """
<p>Hi, <%= owner.email %> wants to share <a href="<%= project.url %>">'<%= project.name %>'</a> with you</p>
<center>
<div style="width:200px;background-color:#a93629;border:1px solid #e24b3b;border-radius:3px;padding:15px; margin:24px;">
<div style="padding-right:10px;padding-left:10px">
<a href="<%= project.url %>" style="text-decoration:none" target="_blank">
<span style= "font-size:16px;font-family:Helvetica,Arial;font-weight:400;color:#fff;white-space:nowrap;display:block; text-align:center">
View Project
</span>
</a>
</div>
</div>
</center>
<p> Thank you</p>
<p> <a href="<%= siteUrl %>">#{settings.appName}</a></p>
"""
templates.completeJoinGroupAccount =
subject: _.template "Verify Email to join <%= group_name %> group"
layout: NotificationEmailLayout
type:"notification"
compiledTemplate: _.template """
<p>Hi, please verify your email to join the <%= group_name %> and get your free premium account</p>
<center>
<div style="width:200px;background-color:#a93629;border:1px solid #e24b3b;border-radius:3px;padding:15px; margin:24px;">
<div style="padding-right:10px;padding-left:10px">
<a href="<%= completeJoinUrl %>" style="text-decoration:none" target="_blank">
<span style= "font-size:16px;font-family:Helvetica,Arial;font-weight:400;color:#fff;white-space:nowrap;display:block; text-align:center">
Verify now
</span>
</a>
</div>
</div>
</center>
<p> Thank you</p>
<p> <a href="<%= siteUrl %>">#{settings.appName}</a></p>
"""
module.exports =
templates: templates
buildEmail: (templateName, opts)->
template = templates[templateName]
opts.siteUrl = settings.siteUrl
opts.body = template.compiledTemplate(opts)
if settings.email?.templates?.customFooter?
opts.body += settings.email?.templates?.customFooter
return {
subject : template.subject(opts)
html: template.layout(opts)
type:template.type
}
| true | _ = require('underscore')
PersonalEmailLayout = require("./Layouts/PersonalEmailLayout")
NotificationEmailLayout = require("./Layouts/NotificationEmailLayout")
settings = require("settings-sharelatex")
templates = {}
templates.registered =
subject: _.template "Activate your #{settings.appName} Account"
layout: PersonalEmailLayout
type: "notification"
compiledTemplate: _.template """
<p>Congratulations, you've just had an account created for you on #{settings.appName} with the email address "<%= to %>".</p>
<p><a href="<%= setNewPasswordUrl %>">Click here to set your password and log in.</a></p>
<p>If you have any questions or problems, please contact <a href="mailto:#{settings.adminEmail}">#{settings.adminEmail}</a>.</p>
"""
templates.canceledSubscription =
subject: _.template "ShareLaTeX thoughts"
layout: PersonalEmailLayout
type:"lifecycle"
compiledTemplate: _.template '''
<p>Hi <%= first_name %>,</p>
<p>I'm sorry to see you cancelled your ShareLaTeX premium account. Would you mind giving me some advice on what the site is lacking at the moment via <a href="https://sharelatex.typeform.com/to/F7OzIY">this survey</a>?</p>
<p>Thank you in advance.</p>
<p>
PI:NAME:<NAME>END_PI <br>
ShareLaTeX Co-founder
</p>
'''
templates.passwordResetRequested =
subject: _.template "Password Reset - #{settings.appName}"
layout: NotificationEmailLayout
type:"notification"
compiledTemplate: _.template """
<h2>Password Reset</h2>
<p>
We got a request to reset your #{settings.appName} password.
<p>
<center>
<div style="width:200px;background-color:#a93629;border:1px solid #e24b3b;border-radius:3px;padding:15px; margin:24px;">
<div style="padding-right:10px;padding-left:10px">
<a href="<%= setNewPasswordUrl %>" style="text-decoration:none" target="_blank">
<span style= "font-size:16px;font-family:Arial;font-weight:bold;color:#fff;white-space:nowrap;display:block; text-align:center">
Reset password
</span>
</a>
</div>
</div>
</center>
If you ignore this message, your password won't be changed.
<p>
If you didn't request a password reset, let us know.
</p>
<p>Thank you</p>
<p> <a href="<%= siteUrl %>">#{settings.appName}</a></p>
"""
templates.projectSharedWithYou =
subject: _.template "<%= owner.email %> wants to share <%= project.name %> with you"
layout: NotificationEmailLayout
type:"notification"
compiledTemplate: _.template """
<p>Hi, <%= owner.email %> wants to share <a href="<%= project.url %>">'<%= project.name %>'</a> with you</p>
<center>
<div style="width:200px;background-color:#a93629;border:1px solid #e24b3b;border-radius:3px;padding:15px; margin:24px;">
<div style="padding-right:10px;padding-left:10px">
<a href="<%= project.url %>" style="text-decoration:none" target="_blank">
<span style= "font-size:16px;font-family:Helvetica,Arial;font-weight:400;color:#fff;white-space:nowrap;display:block; text-align:center">
View Project
</span>
</a>
</div>
</div>
</center>
<p> Thank you</p>
<p> <a href="<%= siteUrl %>">#{settings.appName}</a></p>
"""
templates.completeJoinGroupAccount =
subject: _.template "Verify Email to join <%= group_name %> group"
layout: NotificationEmailLayout
type:"notification"
compiledTemplate: _.template """
<p>Hi, please verify your email to join the <%= group_name %> and get your free premium account</p>
<center>
<div style="width:200px;background-color:#a93629;border:1px solid #e24b3b;border-radius:3px;padding:15px; margin:24px;">
<div style="padding-right:10px;padding-left:10px">
<a href="<%= completeJoinUrl %>" style="text-decoration:none" target="_blank">
<span style= "font-size:16px;font-family:Helvetica,Arial;font-weight:400;color:#fff;white-space:nowrap;display:block; text-align:center">
Verify now
</span>
</a>
</div>
</div>
</center>
<p> Thank you</p>
<p> <a href="<%= siteUrl %>">#{settings.appName}</a></p>
"""
module.exports =
templates: templates
buildEmail: (templateName, opts)->
template = templates[templateName]
opts.siteUrl = settings.siteUrl
opts.body = template.compiledTemplate(opts)
if settings.email?.templates?.customFooter?
opts.body += settings.email?.templates?.customFooter
return {
subject : template.subject(opts)
html: template.layout(opts)
type:template.type
}
|
[
{
"context": " React.createElement Record, key: record.id, record: record",
"end": 639,
"score": 0.7380763292312622,
"start": 637,
"tag": "KEY",
"value": "id"
}
] | app/assets/javascripts/components/records.js.coffee | mbouzi/Accounts | 0 | @Records = React.createClass
getInitialState: ->
records: @props.data
getDefaultProps: ->
records: []
render: ->
React.DOM.div
className: 'records'
React.DOM.h2
className: 'title'
'Records'
React.DOM.table
className: 'table table-bordered'
React.DOM.thead null,
React.DOM.tr null,
React.DOM.th null, 'Date'
React.DOM.th null, 'Title'
React.DOM.th null, 'Amount'
React.DOM.tbody null,
for record in @state.records
React.createElement Record, key: record.id, record: record | 78487 | @Records = React.createClass
getInitialState: ->
records: @props.data
getDefaultProps: ->
records: []
render: ->
React.DOM.div
className: 'records'
React.DOM.h2
className: 'title'
'Records'
React.DOM.table
className: 'table table-bordered'
React.DOM.thead null,
React.DOM.tr null,
React.DOM.th null, 'Date'
React.DOM.th null, 'Title'
React.DOM.th null, 'Amount'
React.DOM.tbody null,
for record in @state.records
React.createElement Record, key: record.<KEY>, record: record | true | @Records = React.createClass
getInitialState: ->
records: @props.data
getDefaultProps: ->
records: []
render: ->
React.DOM.div
className: 'records'
React.DOM.h2
className: 'title'
'Records'
React.DOM.table
className: 'table table-bordered'
React.DOM.thead null,
React.DOM.tr null,
React.DOM.th null, 'Date'
React.DOM.th null, 'Title'
React.DOM.th null, 'Amount'
React.DOM.tbody null,
for record in @state.records
React.createElement Record, key: record.PI:KEY:<KEY>END_PI, record: record |
[
{
"context": " beforeEach ->\n file =\n name: \"test name\"\n size: 2 * 1000 * 1000\n dropzone",
"end": 15140,
"score": 0.9935028553009033,
"start": 15131,
"tag": "NAME",
"value": "test name"
}
] | src/Jariff/ProjectBundle/Resources/public/admin/plugins/jquery.dropzone/rsc/test/test.coffee | mrkahfi/stradetegy | 0 | chai.should()
describe "Dropzone", ->
getMockFile = ->
name: "test file name"
size: 123456
type: "text/html"
describe "static functions", ->
describe "Dropzone.createElement()", ->
element = Dropzone.createElement """<div class="test"><span>Hallo</span></div>"""
it "should properly create an element from a string", ->
element.tagName.should.equal "DIV"
it "should properly add the correct class", ->
element.classList.contains("test").should.be.ok
it "should properly create child elements", ->
element.querySelector("span").tagName.should.equal "SPAN"
it "should always return only one element", ->
element = Dropzone.createElement """<div></div><span></span>"""
element.tagName.should.equal "DIV"
describe "Dropzone.elementInside()", ->
element = Dropzone.createElement """<div id="test"><div class="child1"><div class="child2"></div></div></div>"""
document.body.appendChild element
child1 = element.querySelector ".child1"
child2 = element.querySelector ".child2"
after -> document.body.removeChild element
it "should return yes if elements are the same", ->
Dropzone.elementInside(element, element).should.be.ok
it "should return yes if element is direct child", ->
Dropzone.elementInside(child1, element).should.be.ok
it "should return yes if element is some child", ->
Dropzone.elementInside(child2, element).should.be.ok
Dropzone.elementInside(child2, document.body).should.be.ok
it "should return no unless element is some child", ->
Dropzone.elementInside(element, child1).should.not.be.ok
Dropzone.elementInside(document.body, child1).should.not.be.ok
describe "Dropzone.optionsForElement()", ->
testOptions =
url: "/some/url"
method: "put"
before -> Dropzone.options.testElement = testOptions
after -> delete Dropzone.options.testElement
element = document.createElement "div"
it "should take options set in Dropzone.options from camelized id", ->
element.id = "test-element"
Dropzone.optionsForElement(element).should.equal testOptions
it "should return undefined if no options set", ->
element.id = "test-element2"
expect(Dropzone.optionsForElement(element)).to.equal undefined
describe "Dropzone.forElement()", ->
element = document.createElement "div"
element.id = "some-test-element"
dropzone = null
before ->
document.body.appendChild element
dropzone = new Dropzone element, url: "/test"
after ->
dropzone.disable()
document.body.removeChild element
it "should return null if no dropzone attached", ->
expect(Dropzone.forElement document.createElement "div").to.equal null
it "should accept css selectors", ->
expect(Dropzone.forElement "#some-test-element").to.equal dropzone
it "should accept native elements", ->
expect(Dropzone.forElement element).to.equal dropzone
describe "Dropzone.discover()", ->
element1 = document.createElement "div"
element1.className = "dropzone"
element2 = element1.cloneNode()
element3 = element1.cloneNode()
element1.id = "test-element-1"
element2.id = "test-element-2"
element3.id = "test-element-3"
describe "specific options", ->
before ->
Dropzone.options.testElement1 = url: "test-url"
Dropzone.options.testElement2 = false # Disabled
document.body.appendChild element1
document.body.appendChild element2
Dropzone.discover()
after ->
document.body.removeChild element1
document.body.removeChild element2
it "should find elements with a .dropzone class", ->
element1.dropzone.should.be.ok
it "should not create dropzones with disabled options", ->
expect(element2.dropzone).to.not.be.ok
describe "Dropzone.autoDiscover", ->
before ->
Dropzone.options.testElement3 = url: "test-url"
document.body.appendChild element3
after ->
document.body.removeChild element3
it "should not create dropzones if Dropzone.autoDiscover == false", ->
Dropzone.autoDiscover = off
Dropzone.discover()
expect(element3.dropzone).to.not.be.ok
describe "Dropzone.isValidMimeType()", ->
it "should return true if called without acceptedMimeTypes", ->
Dropzone.isValidMimeType("some/type", null).should.be.ok
it "should properly validate if called with concrete mime types", ->
acceptedMimeTypes = "text/html,image/jpeg,application/json"
Dropzone.isValidMimeType("text/html", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("image/jpeg", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("application/json", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("image/bmp", acceptedMimeTypes).should.not.be.ok
it "should properly validate if called with base mime types", ->
acceptedMimeTypes = "text/*,image/*,application/*"
Dropzone.isValidMimeType("text/html", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("image/jpeg", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("application/json", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("image/bmp", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("some/type", acceptedMimeTypes).should.not.be.ok
it "should properly validate if called with mixed mime types", ->
acceptedMimeTypes = "text/*,image/jpeg,application/*"
Dropzone.isValidMimeType("text/html", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("image/jpeg", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("image/bmp", acceptedMimeTypes).should.not.be.ok
Dropzone.isValidMimeType("application/json", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("some/type", acceptedMimeTypes).should.not.be.ok
it "should properly validate even with spaces in between", ->
acceptedMimeTypes = "text/html , image/jpeg, application/json"
Dropzone.isValidMimeType("text/html", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("image/jpeg", acceptedMimeTypes).should.be.ok
describe "Dropzone.getElement() / getElements()", ->
tmpElements = [ ]
beforeEach ->
tmpElements = [ ]
tmpElements.push Dropzone.createElement """<div class="tmptest"></div>"""
tmpElements.push Dropzone.createElement """<div id="tmptest1" class="random"></div>"""
tmpElements.push Dropzone.createElement """<div class="random div"></div>"""
tmpElements.forEach (el) -> document.body.appendChild el
afterEach ->
tmpElements.forEach (el) -> document.body.removeChild el
describe ".getElement()", ->
it "should accept a string", ->
el = Dropzone.getElement ".tmptest"
el.should.equal tmpElements[0]
el = Dropzone.getElement "#tmptest1"
el.should.equal tmpElements[1]
it "should accept a node", ->
el = Dropzone.getElement tmpElements[2]
el.should.equal tmpElements[2]
it "should fail if invalid selector", ->
errorMessage = "Invalid `clickable` option provided. Please provide a CSS selector or a plain HTML element."
expect(-> Dropzone.getElement "lblasdlfsfl", "clickable").to.throw errorMessage
expect(-> Dropzone.getElement { "lblasdlfsfl" }, "clickable").to.throw errorMessage
expect(-> Dropzone.getElement [ "lblasdlfsfl" ], "clickable").to.throw errorMessage
describe ".getElements()", ->
it "should accept a list of strings", ->
els = Dropzone.getElements [ ".tmptest", "#tmptest1" ]
els.should.eql [ tmpElements[0], tmpElements[1] ]
it "should accept a list of nodes", ->
els = Dropzone.getElements [ tmpElements[0], tmpElements[2] ]
els.should.eql [ tmpElements[0], tmpElements[2] ]
it "should accept a mixed list", ->
els = Dropzone.getElements [ "#tmptest1", tmpElements[2] ]
els.should.eql [ tmpElements[1], tmpElements[2] ]
it "should accept a string selector", ->
els = Dropzone.getElements ".random"
els.should.eql [ tmpElements[1], tmpElements[2] ]
it "should accept a single node", ->
els = Dropzone.getElements tmpElements[1]
els.should.eql [ tmpElements[1] ]
it "should fail if invalid selector", ->
errorMessage = "Invalid `clickable` option provided. Please provide a CSS selector, a plain HTML element or a list of those."
expect(-> Dropzone.getElements "lblasdlfsfl", "clickable").to.throw errorMessage
expect(-> Dropzone.getElements [ "lblasdlfsfl" ], "clickable").to.throw errorMessage
describe "constructor()", ->
dropzone = null
afterEach -> dropzone.destroy() if dropzone?
it "should throw an exception if the element is invalid", ->
expect(-> dropzone = new Dropzone "#invalid-element").to.throw "Invalid dropzone element."
it "should throw an exception if assigned twice to the same element", ->
element = document.createElement "div"
dropzone = new Dropzone element, url: "url"
expect(-> new Dropzone element, url: "url").to.throw "Dropzone already attached."
it "should throw an exception if both acceptParameter and acceptedMimeTypes are specified", ->
element = document.createElement "div"
expect(-> dropzone = new Dropzone element, url: "test", acceptParameter: "param", acceptedMimeTypes: "types").to.throw "You can't provide both 'acceptParameter' and 'acceptedMimeTypes'. 'acceptParameter' is deprecated."
it "should set itself as element.dropzone", ->
element = document.createElement "div"
dropzone = new Dropzone element, url: "url"
element.dropzone.should.equal dropzone
describe "options", ->
element = null
element2 = null
beforeEach ->
element = document.createElement "div"
element.id = "test-element"
element2 = document.createElement "div"
element2.id = "test-element2"
Dropzone.options.testElement = url: "/some/url", parallelUploads: 10
afterEach -> delete Dropzone.options.testElement
it "should take the options set in Dropzone.options", ->
dropzone = new Dropzone element
dropzone.options.url.should.equal "/some/url"
dropzone.options.parallelUploads.should.equal 10
it "should prefer passed options over Dropzone.options", ->
dropzone = new Dropzone element, url: "/some/other/url"
dropzone.options.url.should.equal "/some/other/url"
it "should take the default options if nothing set in Dropzone.options", ->
dropzone = new Dropzone element2, url: "/some/url"
dropzone.options.parallelUploads.should.equal 2
it "should call the fallback function if forceFallback == true", (done) ->
dropzone = new Dropzone element,
url: "/some/other/url"
forceFallback: on
fallback: -> done()
describe "options.clickable", ->
clickableElement = null
dropzone = null
beforeEach ->
clickableElement = document.createElement "div"
clickableElement.className = "some-clickable"
document.body.appendChild clickableElement
afterEach ->
document.body.removeChild clickableElement
dropzone.destroy if dropzone?
it "should use the default element if clickable == true", ->
dropzone = new Dropzone element, clickable: yes
dropzone.clickableElements.should.eql [ dropzone.element ]
it "should lookup the element if clickable is a CSS selector", ->
dropzone = new Dropzone element, clickable: ".some-clickable"
dropzone.clickableElements.should.eql [ clickableElement ]
it "should simply use the provided element", ->
dropzone = new Dropzone element, clickable: clickableElement
dropzone.clickableElements.should.eql [ clickableElement ]
it "should accept multiple clickable elements", ->
dropzone = new Dropzone element, clickable: [ document.body, ".some-clickable" ]
dropzone.clickableElements.should.eql [ document.body, clickableElement ]
it "should throw an exception if the element is invalid", ->
expect(-> dropzone = new Dropzone element, clickable: ".some-invalid-clickable").to.throw "Invalid `clickable` option provided. Please provide a CSS selector, a plain HTML element or a list of those."
describe "init()", ->
describe "clickable", ->
dropzones =
"using acceptParameter": new Dropzone(Dropzone.createElement("""<form action="/"></form>"""), { clickable: yes, acceptParameter: "audio/*,video/*" })
"using acceptedMimeTypes": new Dropzone(Dropzone.createElement("""<form action="/"></form>"""), { clickable: yes, acceptedMimeTypes: "audio/*,video/*" })
it "should not add an accept attribute if no acceptParameter", ->
dropzone = new Dropzone (Dropzone.createElement """<form action="/"></form>"""), clickable: yes, acceptParameter: null, acceptedMimeTypes: null
dropzone.hiddenFileInput.hasAttribute("accept").should.be.false
for name, dropzone of dropzones
describe name, ->
do (dropzone) ->
it "should create a hidden file input if clickable", ->
dropzone.hiddenFileInput.should.be.ok
dropzone.hiddenFileInput.tagName.should.equal "INPUT"
it "should use the acceptParameter", ->
dropzone.hiddenFileInput.getAttribute("accept").should.equal "audio/*,video/*"
it "should create a new input element when something is selected to reset the input field", ->
for i in [0..3]
hiddenFileInput = dropzone.hiddenFileInput
event = document.createEvent "HTMLEvents"
event.initEvent "change", true, true
hiddenFileInput.dispatchEvent event
dropzone.hiddenFileInput.should.not.equal hiddenFileInput
Dropzone.elementInside(hiddenFileInput, document).should.not.be.ok
it "should create a data-dz-message element", ->
element = Dropzone.createElement """<form class="dropzone" action="/"></form>"""
dropzone = new Dropzone element, clickable: yes, acceptParameter: null, acceptedMimeTypes: null
element.querySelector("[data-dz-message]").should.be.instanceof Element
describe "options", ->
element = null
dropzone = null
beforeEach ->
element = Dropzone.createElement """<div></div>"""
dropzone = new Dropzone element, maxFilesize: 4, url: "url", acceptedMimeTypes: "audio/*,image/png"
describe "file specific", ->
file = null
beforeEach ->
file =
name: "test name"
size: 2 * 1000 * 1000
dropzone.options.addedfile.call dropzone, file
describe ".addedFile()", ->
it "should properly create the previewElement", ->
file.previewElement.should.be.instanceof Element
file.previewElement.querySelector("[data-dz-name]").innerHTML.should.eql "test name"
file.previewElement.querySelector("[data-dz-size]").innerHTML.should.eql "<strong>2</strong> MB"
describe ".error()", ->
it "should properly insert the error", ->
dropzone.options.error.call dropzone, file, "test message"
file.previewElement.querySelector("[data-dz-errormessage]").innerHTML.should.eql "test message"
describe ".thumbnail()", ->
it "should properly insert the error", ->
transparentGif = "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="
dropzone.options.thumbnail.call dropzone, file, transparentGif
thumbnail = file.previewElement.querySelector("[data-dz-thumbnail]")
thumbnail.src.should.eql transparentGif
thumbnail.alt.should.eql "test name"
describe ".uploadprogress()", ->
it "should properly set the width", ->
dropzone.options.uploadprogress.call dropzone, file, 0
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql "0%"
dropzone.options.uploadprogress.call dropzone, file, 80
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql "80%"
dropzone.options.uploadprogress.call dropzone, file, 90
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql "90%"
dropzone.options.uploadprogress.call dropzone, file, 100
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql "100%"
describe "instance", ->
element = null
dropzone = null
xhr = null
requests = null
beforeEach ->
xhr = sinon.useFakeXMLHttpRequest()
requests = [ ]
xhr.onCreate = (xhr) -> requests.push xhr
element = Dropzone.createElement """<div></div>"""
document.body.appendChild element
dropzone = new Dropzone element, maxFilesize: 4, url: "url", acceptedMimeTypes: "audio/*,image/png", uploadprogress: ->
afterEach ->
document.body.removeChild element
dropzone.destroy()
xhr.restore()
describe ".accept()", ->
it "should pass if the filesize is OK", ->
dropzone.accept { size: 2 * 1024 * 1024, type: "audio/mp3" }, (err) -> expect(err).to.be.undefined
it "shouldn't pass if the filesize is too big", ->
dropzone.accept { size: 10 * 1024 * 1024, type: "audio/mp3" }, (err) -> err.should.eql "File is too big (10MB). Max filesize: 4MB."
it "should properly accept files which mime types are listed in acceptedMimeTypes", ->
dropzone.accept { type: "audio/mp3" }, (err) -> expect(err).to.be.undefined
dropzone.accept { type: "image/png" }, (err) -> expect(err).to.be.undefined
dropzone.accept { type: "audio/wav" }, (err) -> expect(err).to.be.undefined
it "should properly reject files when the mime type isn't listed in acceptedMimeTypes", ->
dropzone.accept { type: "image/jpeg" }, (err) -> err.should.eql "You can't upload files of this type."
describe ".removeFile()", ->
it "should abort uploading if file is currently being uploaded", ->
mockFile = getMockFile()
dropzone.uploadFile = (file) ->
dropzone.accept = (file, done) -> done()
sinon.stub dropzone, "cancelUpload"
dropzone.addFile mockFile
mockFile.status.should.equal Dropzone.UPLOADING
dropzone.filesProcessing[0].should.equal mockFile
dropzone.cancelUpload.callCount.should.equal 0
dropzone.removeFile mockFile
dropzone.cancelUpload.callCount.should.equal 1
describe ".cancelUpload()", ->
it "should properly cancel upload if file currently uploading", ->
mockFile = getMockFile()
dropzone.accept = (file, done) -> done()
dropzone.addFile mockFile
mockFile.status.should.equal Dropzone.UPLOADING
dropzone.filesProcessing[0].should.equal mockFile
dropzone.cancelUpload mockFile
mockFile.status.should.equal Dropzone.CANCELED
dropzone.filesProcessing.length.should.equal 0
dropzone.filesQueue.length.should.equal 0
it "should properly cancel the upload if file is not yet uploading", ->
mockFile = getMockFile()
dropzone.accept = (file, done) -> done()
# Making sure the file stays in the queue.
dropzone.options.parallelUploads = 0
dropzone.addFile mockFile
mockFile.status.should.equal Dropzone.ACCEPTED
dropzone.filesQueue[0].should.equal mockFile
dropzone.cancelUpload mockFile
mockFile.status.should.equal Dropzone.CANCELED
dropzone.filesQueue.length.should.equal 0
dropzone.filesProcessing.length.should.equal 0
describe ".disable()", ->
it "should properly cancel all pending uploads", ->
dropzone.accept = (file, done) -> done()
dropzone.options.parallelUploads = 1
dropzone.addFile getMockFile()
dropzone.addFile getMockFile()
dropzone.filesProcessing.length.should.equal 1
dropzone.filesQueue.length.should.equal 1
dropzone.files.length.should.equal 2
sinon.spy requests[0], "abort"
requests[0].abort.callCount.should.equal 0
dropzone.disable()
requests[0].abort.callCount.should.equal 1
dropzone.filesProcessing.length.should.equal 0
dropzone.filesQueue.length.should.equal 0
dropzone.files.length.should.equal 2
dropzone.files[0].status.should.equal Dropzone.CANCELED
dropzone.files[1].status.should.equal Dropzone.CANCELED
describe ".destroy()", ->
it "should properly cancel all pending uploads and remove all file references", ->
dropzone.accept = (file, done) -> done()
dropzone.options.parallelUploads = 1
dropzone.addFile getMockFile()
dropzone.addFile getMockFile()
dropzone.filesProcessing.length.should.equal 1
dropzone.filesQueue.length.should.equal 1
dropzone.files.length.should.equal 2
sinon.spy dropzone, "disable"
dropzone.destroy()
dropzone.disable.callCount.should.equal 1
describe ".filesize()", ->
it "should convert to KiloBytes, etc.. not KibiBytes", ->
dropzone.filesize(2 * 1024 * 1024).should.eql "<strong>2.1</strong> MB"
dropzone.filesize(2 * 1000 * 1000).should.eql "<strong>2</strong> MB"
dropzone.filesize(2 * 1024 * 1024 * 1024).should.eql "<strong>2.1</strong> GB"
dropzone.filesize(2 * 1000 * 1000 * 1000).should.eql "<strong>2</strong> GB"
describe "events", ->
describe "progress updates", ->
it "should properly emit a totaluploadprogress event", ->
dropzone.files = [
{
size: 1990
upload:
progress: 20
total: 2000 # The bytes to upload are higher than the file size
bytesSent: 400
}
{
size: 1990
upload:
progress: 10
total: 2000 # The bytes to upload are higher than the file size
bytesSent: 200
}
]
dropzone.acceptedFiles = dropzone.files
totalProgressExpectation = 15
dropzone.on "totaluploadprogress", (progress) -> progress.should.eql totalProgressExpectation
dropzone.emit "uploadprogress", { }
totalProgressExpectation = 97.5
dropzone.files[0].upload.bytesSent = 2000
dropzone.files[1].upload.bytesSent = 1900
# It shouldn't matter that progress is not properly updated since the total size
# should be calculated from the bytes
dropzone.on "totaluploadprogress", (progress) -> progress.should.eql totalProgressExpectation
dropzone.emit "uploadprogress", { }
totalProgressExpectation = 100
dropzone.files[0].upload.bytesSent = 2000
dropzone.files[1].upload.bytesSent = 2000
# It shouldn't matter that progress is not properly updated since the total size
# should be calculated from the bytes
dropzone.on "totaluploadprogress", (progress) -> progress.should.eql totalProgressExpectation
dropzone.emit "uploadprogress", { }
describe "helper function", ->
describe "getExistingFallback()", ->
element = null
dropzone = null
beforeEach ->
element = Dropzone.createElement """<div></div>"""
dropzone = new Dropzone element, url: "url"
it "should return undefined if no fallback", ->
expect(dropzone.getExistingFallback()).to.equal undefined
it "should only return the fallback element if it contains exactly fallback", ->
element.appendChild Dropzone.createElement """<form class="fallbacks"></form>"""
element.appendChild Dropzone.createElement """<form class="sfallback"></form>"""
expect(dropzone.getExistingFallback()).to.equal undefined
it "should return divs as fallback", ->
fallback = Dropzone.createElement """<form class=" abc fallback test "></form>"""
element.appendChild fallback
fallback.should.equal dropzone.getExistingFallback()
it "should return forms as fallback", ->
fallback = Dropzone.createElement """<div class=" abc fallback test "></div>"""
element.appendChild fallback
fallback.should.equal dropzone.getExistingFallback()
describe "file handling", ->
mockFile = null
dropzone = null
beforeEach ->
mockFile = getMockFile()
element = Dropzone.createElement """<div></div>"""
dropzone = new Dropzone element, url: "/the/url"
afterEach ->
dropzone.destroy()
describe "addFile()", ->
it "should properly set the status of the file", ->
doneFunction = null
dropzone.accept = (file, done) -> doneFunction = done
dropzone.processFile = ->
dropzone.uploadFile = ->
dropzone.addFile mockFile
mockFile.status.should.eql Dropzone.ADDED
doneFunction()
mockFile.status.should.eql Dropzone.ACCEPTED
mockFile = getMockFile()
dropzone.addFile mockFile
mockFile.status.should.eql Dropzone.ADDED
doneFunction("error")
mockFile.status.should.eql Dropzone.ERROR
describe "uploadFile()", ->
xhr = null
requests = null
beforeEach ->
xhr = sinon.useFakeXMLHttpRequest()
requests = [ ]
xhr.onCreate = (xhr) -> requests.push xhr
afterEach ->
xhr.restore()
it "should properly urlencode the filename for the headers", ->
dropzone.uploadFile mockFile
requests[0].requestHeaders["X-File-Name"].should.eql 'test%20file%20name'
describe "settings()", ->
it "should correctly set `withCredentials` on the xhr object", ->
dropzone.uploadFile mockFile
requests.length.should.eql 1
requests[0].withCredentials.should.eql no
dropzone.options.withCredentials = yes
dropzone.uploadFile mockFile
requests.length.should.eql 2
requests[1].withCredentials.should.eql yes
it "should correctly override headers on the xhr object", ->
dropzone.options.headers = {"Foo-Header": "foobar"}
dropzone.uploadFile mockFile
requests[0].requestHeaders["Foo-Header"].should.eql 'foobar'
requests[0].requestHeaders["X-File-Name"].should.eql 'test%20file%20name'
describe "should properly set status of file", ->
it "should correctly set `withCredentials` on the xhr object", ->
dropzone.addFile mockFile
mockFile.status.should.eql Dropzone.UPLOADING
requests.length.should.equal 1
requests[0].status = 400
requests[0].onload()
mockFile.status.should.eql Dropzone.ERROR
mockFile = getMockFile()
dropzone.addFile mockFile
mockFile.status.should.eql Dropzone.UPLOADING
requests.length.should.equal 2
requests[1].status = 200
requests[1].onload()
mockFile.status.should.eql Dropzone.SUCCESS
| 169829 | chai.should()
describe "Dropzone", ->
getMockFile = ->
name: "test file name"
size: 123456
type: "text/html"
describe "static functions", ->
describe "Dropzone.createElement()", ->
element = Dropzone.createElement """<div class="test"><span>Hallo</span></div>"""
it "should properly create an element from a string", ->
element.tagName.should.equal "DIV"
it "should properly add the correct class", ->
element.classList.contains("test").should.be.ok
it "should properly create child elements", ->
element.querySelector("span").tagName.should.equal "SPAN"
it "should always return only one element", ->
element = Dropzone.createElement """<div></div><span></span>"""
element.tagName.should.equal "DIV"
describe "Dropzone.elementInside()", ->
element = Dropzone.createElement """<div id="test"><div class="child1"><div class="child2"></div></div></div>"""
document.body.appendChild element
child1 = element.querySelector ".child1"
child2 = element.querySelector ".child2"
after -> document.body.removeChild element
it "should return yes if elements are the same", ->
Dropzone.elementInside(element, element).should.be.ok
it "should return yes if element is direct child", ->
Dropzone.elementInside(child1, element).should.be.ok
it "should return yes if element is some child", ->
Dropzone.elementInside(child2, element).should.be.ok
Dropzone.elementInside(child2, document.body).should.be.ok
it "should return no unless element is some child", ->
Dropzone.elementInside(element, child1).should.not.be.ok
Dropzone.elementInside(document.body, child1).should.not.be.ok
describe "Dropzone.optionsForElement()", ->
testOptions =
url: "/some/url"
method: "put"
before -> Dropzone.options.testElement = testOptions
after -> delete Dropzone.options.testElement
element = document.createElement "div"
it "should take options set in Dropzone.options from camelized id", ->
element.id = "test-element"
Dropzone.optionsForElement(element).should.equal testOptions
it "should return undefined if no options set", ->
element.id = "test-element2"
expect(Dropzone.optionsForElement(element)).to.equal undefined
describe "Dropzone.forElement()", ->
element = document.createElement "div"
element.id = "some-test-element"
dropzone = null
before ->
document.body.appendChild element
dropzone = new Dropzone element, url: "/test"
after ->
dropzone.disable()
document.body.removeChild element
it "should return null if no dropzone attached", ->
expect(Dropzone.forElement document.createElement "div").to.equal null
it "should accept css selectors", ->
expect(Dropzone.forElement "#some-test-element").to.equal dropzone
it "should accept native elements", ->
expect(Dropzone.forElement element).to.equal dropzone
describe "Dropzone.discover()", ->
element1 = document.createElement "div"
element1.className = "dropzone"
element2 = element1.cloneNode()
element3 = element1.cloneNode()
element1.id = "test-element-1"
element2.id = "test-element-2"
element3.id = "test-element-3"
describe "specific options", ->
before ->
Dropzone.options.testElement1 = url: "test-url"
Dropzone.options.testElement2 = false # Disabled
document.body.appendChild element1
document.body.appendChild element2
Dropzone.discover()
after ->
document.body.removeChild element1
document.body.removeChild element2
it "should find elements with a .dropzone class", ->
element1.dropzone.should.be.ok
it "should not create dropzones with disabled options", ->
expect(element2.dropzone).to.not.be.ok
describe "Dropzone.autoDiscover", ->
before ->
Dropzone.options.testElement3 = url: "test-url"
document.body.appendChild element3
after ->
document.body.removeChild element3
it "should not create dropzones if Dropzone.autoDiscover == false", ->
Dropzone.autoDiscover = off
Dropzone.discover()
expect(element3.dropzone).to.not.be.ok
describe "Dropzone.isValidMimeType()", ->
it "should return true if called without acceptedMimeTypes", ->
Dropzone.isValidMimeType("some/type", null).should.be.ok
it "should properly validate if called with concrete mime types", ->
acceptedMimeTypes = "text/html,image/jpeg,application/json"
Dropzone.isValidMimeType("text/html", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("image/jpeg", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("application/json", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("image/bmp", acceptedMimeTypes).should.not.be.ok
it "should properly validate if called with base mime types", ->
acceptedMimeTypes = "text/*,image/*,application/*"
Dropzone.isValidMimeType("text/html", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("image/jpeg", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("application/json", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("image/bmp", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("some/type", acceptedMimeTypes).should.not.be.ok
it "should properly validate if called with mixed mime types", ->
acceptedMimeTypes = "text/*,image/jpeg,application/*"
Dropzone.isValidMimeType("text/html", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("image/jpeg", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("image/bmp", acceptedMimeTypes).should.not.be.ok
Dropzone.isValidMimeType("application/json", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("some/type", acceptedMimeTypes).should.not.be.ok
it "should properly validate even with spaces in between", ->
acceptedMimeTypes = "text/html , image/jpeg, application/json"
Dropzone.isValidMimeType("text/html", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("image/jpeg", acceptedMimeTypes).should.be.ok
describe "Dropzone.getElement() / getElements()", ->
tmpElements = [ ]
beforeEach ->
tmpElements = [ ]
tmpElements.push Dropzone.createElement """<div class="tmptest"></div>"""
tmpElements.push Dropzone.createElement """<div id="tmptest1" class="random"></div>"""
tmpElements.push Dropzone.createElement """<div class="random div"></div>"""
tmpElements.forEach (el) -> document.body.appendChild el
afterEach ->
tmpElements.forEach (el) -> document.body.removeChild el
describe ".getElement()", ->
it "should accept a string", ->
el = Dropzone.getElement ".tmptest"
el.should.equal tmpElements[0]
el = Dropzone.getElement "#tmptest1"
el.should.equal tmpElements[1]
it "should accept a node", ->
el = Dropzone.getElement tmpElements[2]
el.should.equal tmpElements[2]
it "should fail if invalid selector", ->
errorMessage = "Invalid `clickable` option provided. Please provide a CSS selector or a plain HTML element."
expect(-> Dropzone.getElement "lblasdlfsfl", "clickable").to.throw errorMessage
expect(-> Dropzone.getElement { "lblasdlfsfl" }, "clickable").to.throw errorMessage
expect(-> Dropzone.getElement [ "lblasdlfsfl" ], "clickable").to.throw errorMessage
describe ".getElements()", ->
it "should accept a list of strings", ->
els = Dropzone.getElements [ ".tmptest", "#tmptest1" ]
els.should.eql [ tmpElements[0], tmpElements[1] ]
it "should accept a list of nodes", ->
els = Dropzone.getElements [ tmpElements[0], tmpElements[2] ]
els.should.eql [ tmpElements[0], tmpElements[2] ]
it "should accept a mixed list", ->
els = Dropzone.getElements [ "#tmptest1", tmpElements[2] ]
els.should.eql [ tmpElements[1], tmpElements[2] ]
it "should accept a string selector", ->
els = Dropzone.getElements ".random"
els.should.eql [ tmpElements[1], tmpElements[2] ]
it "should accept a single node", ->
els = Dropzone.getElements tmpElements[1]
els.should.eql [ tmpElements[1] ]
it "should fail if invalid selector", ->
errorMessage = "Invalid `clickable` option provided. Please provide a CSS selector, a plain HTML element or a list of those."
expect(-> Dropzone.getElements "lblasdlfsfl", "clickable").to.throw errorMessage
expect(-> Dropzone.getElements [ "lblasdlfsfl" ], "clickable").to.throw errorMessage
describe "constructor()", ->
dropzone = null
afterEach -> dropzone.destroy() if dropzone?
it "should throw an exception if the element is invalid", ->
expect(-> dropzone = new Dropzone "#invalid-element").to.throw "Invalid dropzone element."
it "should throw an exception if assigned twice to the same element", ->
element = document.createElement "div"
dropzone = new Dropzone element, url: "url"
expect(-> new Dropzone element, url: "url").to.throw "Dropzone already attached."
it "should throw an exception if both acceptParameter and acceptedMimeTypes are specified", ->
element = document.createElement "div"
expect(-> dropzone = new Dropzone element, url: "test", acceptParameter: "param", acceptedMimeTypes: "types").to.throw "You can't provide both 'acceptParameter' and 'acceptedMimeTypes'. 'acceptParameter' is deprecated."
it "should set itself as element.dropzone", ->
element = document.createElement "div"
dropzone = new Dropzone element, url: "url"
element.dropzone.should.equal dropzone
describe "options", ->
element = null
element2 = null
beforeEach ->
element = document.createElement "div"
element.id = "test-element"
element2 = document.createElement "div"
element2.id = "test-element2"
Dropzone.options.testElement = url: "/some/url", parallelUploads: 10
afterEach -> delete Dropzone.options.testElement
it "should take the options set in Dropzone.options", ->
dropzone = new Dropzone element
dropzone.options.url.should.equal "/some/url"
dropzone.options.parallelUploads.should.equal 10
it "should prefer passed options over Dropzone.options", ->
dropzone = new Dropzone element, url: "/some/other/url"
dropzone.options.url.should.equal "/some/other/url"
it "should take the default options if nothing set in Dropzone.options", ->
dropzone = new Dropzone element2, url: "/some/url"
dropzone.options.parallelUploads.should.equal 2
it "should call the fallback function if forceFallback == true", (done) ->
dropzone = new Dropzone element,
url: "/some/other/url"
forceFallback: on
fallback: -> done()
describe "options.clickable", ->
clickableElement = null
dropzone = null
beforeEach ->
clickableElement = document.createElement "div"
clickableElement.className = "some-clickable"
document.body.appendChild clickableElement
afterEach ->
document.body.removeChild clickableElement
dropzone.destroy if dropzone?
it "should use the default element if clickable == true", ->
dropzone = new Dropzone element, clickable: yes
dropzone.clickableElements.should.eql [ dropzone.element ]
it "should lookup the element if clickable is a CSS selector", ->
dropzone = new Dropzone element, clickable: ".some-clickable"
dropzone.clickableElements.should.eql [ clickableElement ]
it "should simply use the provided element", ->
dropzone = new Dropzone element, clickable: clickableElement
dropzone.clickableElements.should.eql [ clickableElement ]
it "should accept multiple clickable elements", ->
dropzone = new Dropzone element, clickable: [ document.body, ".some-clickable" ]
dropzone.clickableElements.should.eql [ document.body, clickableElement ]
it "should throw an exception if the element is invalid", ->
expect(-> dropzone = new Dropzone element, clickable: ".some-invalid-clickable").to.throw "Invalid `clickable` option provided. Please provide a CSS selector, a plain HTML element or a list of those."
describe "init()", ->
describe "clickable", ->
dropzones =
"using acceptParameter": new Dropzone(Dropzone.createElement("""<form action="/"></form>"""), { clickable: yes, acceptParameter: "audio/*,video/*" })
"using acceptedMimeTypes": new Dropzone(Dropzone.createElement("""<form action="/"></form>"""), { clickable: yes, acceptedMimeTypes: "audio/*,video/*" })
it "should not add an accept attribute if no acceptParameter", ->
dropzone = new Dropzone (Dropzone.createElement """<form action="/"></form>"""), clickable: yes, acceptParameter: null, acceptedMimeTypes: null
dropzone.hiddenFileInput.hasAttribute("accept").should.be.false
for name, dropzone of dropzones
describe name, ->
do (dropzone) ->
it "should create a hidden file input if clickable", ->
dropzone.hiddenFileInput.should.be.ok
dropzone.hiddenFileInput.tagName.should.equal "INPUT"
it "should use the acceptParameter", ->
dropzone.hiddenFileInput.getAttribute("accept").should.equal "audio/*,video/*"
it "should create a new input element when something is selected to reset the input field", ->
for i in [0..3]
hiddenFileInput = dropzone.hiddenFileInput
event = document.createEvent "HTMLEvents"
event.initEvent "change", true, true
hiddenFileInput.dispatchEvent event
dropzone.hiddenFileInput.should.not.equal hiddenFileInput
Dropzone.elementInside(hiddenFileInput, document).should.not.be.ok
it "should create a data-dz-message element", ->
element = Dropzone.createElement """<form class="dropzone" action="/"></form>"""
dropzone = new Dropzone element, clickable: yes, acceptParameter: null, acceptedMimeTypes: null
element.querySelector("[data-dz-message]").should.be.instanceof Element
describe "options", ->
element = null
dropzone = null
beforeEach ->
element = Dropzone.createElement """<div></div>"""
dropzone = new Dropzone element, maxFilesize: 4, url: "url", acceptedMimeTypes: "audio/*,image/png"
describe "file specific", ->
file = null
beforeEach ->
file =
name: "<NAME>"
size: 2 * 1000 * 1000
dropzone.options.addedfile.call dropzone, file
describe ".addedFile()", ->
it "should properly create the previewElement", ->
file.previewElement.should.be.instanceof Element
file.previewElement.querySelector("[data-dz-name]").innerHTML.should.eql "test name"
file.previewElement.querySelector("[data-dz-size]").innerHTML.should.eql "<strong>2</strong> MB"
describe ".error()", ->
it "should properly insert the error", ->
dropzone.options.error.call dropzone, file, "test message"
file.previewElement.querySelector("[data-dz-errormessage]").innerHTML.should.eql "test message"
describe ".thumbnail()", ->
it "should properly insert the error", ->
transparentGif = "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="
dropzone.options.thumbnail.call dropzone, file, transparentGif
thumbnail = file.previewElement.querySelector("[data-dz-thumbnail]")
thumbnail.src.should.eql transparentGif
thumbnail.alt.should.eql "test name"
describe ".uploadprogress()", ->
it "should properly set the width", ->
dropzone.options.uploadprogress.call dropzone, file, 0
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql "0%"
dropzone.options.uploadprogress.call dropzone, file, 80
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql "80%"
dropzone.options.uploadprogress.call dropzone, file, 90
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql "90%"
dropzone.options.uploadprogress.call dropzone, file, 100
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql "100%"
describe "instance", ->
element = null
dropzone = null
xhr = null
requests = null
beforeEach ->
xhr = sinon.useFakeXMLHttpRequest()
requests = [ ]
xhr.onCreate = (xhr) -> requests.push xhr
element = Dropzone.createElement """<div></div>"""
document.body.appendChild element
dropzone = new Dropzone element, maxFilesize: 4, url: "url", acceptedMimeTypes: "audio/*,image/png", uploadprogress: ->
afterEach ->
document.body.removeChild element
dropzone.destroy()
xhr.restore()
describe ".accept()", ->
it "should pass if the filesize is OK", ->
dropzone.accept { size: 2 * 1024 * 1024, type: "audio/mp3" }, (err) -> expect(err).to.be.undefined
it "shouldn't pass if the filesize is too big", ->
dropzone.accept { size: 10 * 1024 * 1024, type: "audio/mp3" }, (err) -> err.should.eql "File is too big (10MB). Max filesize: 4MB."
it "should properly accept files which mime types are listed in acceptedMimeTypes", ->
dropzone.accept { type: "audio/mp3" }, (err) -> expect(err).to.be.undefined
dropzone.accept { type: "image/png" }, (err) -> expect(err).to.be.undefined
dropzone.accept { type: "audio/wav" }, (err) -> expect(err).to.be.undefined
it "should properly reject files when the mime type isn't listed in acceptedMimeTypes", ->
dropzone.accept { type: "image/jpeg" }, (err) -> err.should.eql "You can't upload files of this type."
describe ".removeFile()", ->
it "should abort uploading if file is currently being uploaded", ->
mockFile = getMockFile()
dropzone.uploadFile = (file) ->
dropzone.accept = (file, done) -> done()
sinon.stub dropzone, "cancelUpload"
dropzone.addFile mockFile
mockFile.status.should.equal Dropzone.UPLOADING
dropzone.filesProcessing[0].should.equal mockFile
dropzone.cancelUpload.callCount.should.equal 0
dropzone.removeFile mockFile
dropzone.cancelUpload.callCount.should.equal 1
describe ".cancelUpload()", ->
it "should properly cancel upload if file currently uploading", ->
mockFile = getMockFile()
dropzone.accept = (file, done) -> done()
dropzone.addFile mockFile
mockFile.status.should.equal Dropzone.UPLOADING
dropzone.filesProcessing[0].should.equal mockFile
dropzone.cancelUpload mockFile
mockFile.status.should.equal Dropzone.CANCELED
dropzone.filesProcessing.length.should.equal 0
dropzone.filesQueue.length.should.equal 0
it "should properly cancel the upload if file is not yet uploading", ->
mockFile = getMockFile()
dropzone.accept = (file, done) -> done()
# Making sure the file stays in the queue.
dropzone.options.parallelUploads = 0
dropzone.addFile mockFile
mockFile.status.should.equal Dropzone.ACCEPTED
dropzone.filesQueue[0].should.equal mockFile
dropzone.cancelUpload mockFile
mockFile.status.should.equal Dropzone.CANCELED
dropzone.filesQueue.length.should.equal 0
dropzone.filesProcessing.length.should.equal 0
describe ".disable()", ->
it "should properly cancel all pending uploads", ->
dropzone.accept = (file, done) -> done()
dropzone.options.parallelUploads = 1
dropzone.addFile getMockFile()
dropzone.addFile getMockFile()
dropzone.filesProcessing.length.should.equal 1
dropzone.filesQueue.length.should.equal 1
dropzone.files.length.should.equal 2
sinon.spy requests[0], "abort"
requests[0].abort.callCount.should.equal 0
dropzone.disable()
requests[0].abort.callCount.should.equal 1
dropzone.filesProcessing.length.should.equal 0
dropzone.filesQueue.length.should.equal 0
dropzone.files.length.should.equal 2
dropzone.files[0].status.should.equal Dropzone.CANCELED
dropzone.files[1].status.should.equal Dropzone.CANCELED
describe ".destroy()", ->
it "should properly cancel all pending uploads and remove all file references", ->
dropzone.accept = (file, done) -> done()
dropzone.options.parallelUploads = 1
dropzone.addFile getMockFile()
dropzone.addFile getMockFile()
dropzone.filesProcessing.length.should.equal 1
dropzone.filesQueue.length.should.equal 1
dropzone.files.length.should.equal 2
sinon.spy dropzone, "disable"
dropzone.destroy()
dropzone.disable.callCount.should.equal 1
describe ".filesize()", ->
it "should convert to KiloBytes, etc.. not KibiBytes", ->
dropzone.filesize(2 * 1024 * 1024).should.eql "<strong>2.1</strong> MB"
dropzone.filesize(2 * 1000 * 1000).should.eql "<strong>2</strong> MB"
dropzone.filesize(2 * 1024 * 1024 * 1024).should.eql "<strong>2.1</strong> GB"
dropzone.filesize(2 * 1000 * 1000 * 1000).should.eql "<strong>2</strong> GB"
describe "events", ->
describe "progress updates", ->
it "should properly emit a totaluploadprogress event", ->
dropzone.files = [
{
size: 1990
upload:
progress: 20
total: 2000 # The bytes to upload are higher than the file size
bytesSent: 400
}
{
size: 1990
upload:
progress: 10
total: 2000 # The bytes to upload are higher than the file size
bytesSent: 200
}
]
dropzone.acceptedFiles = dropzone.files
totalProgressExpectation = 15
dropzone.on "totaluploadprogress", (progress) -> progress.should.eql totalProgressExpectation
dropzone.emit "uploadprogress", { }
totalProgressExpectation = 97.5
dropzone.files[0].upload.bytesSent = 2000
dropzone.files[1].upload.bytesSent = 1900
# It shouldn't matter that progress is not properly updated since the total size
# should be calculated from the bytes
dropzone.on "totaluploadprogress", (progress) -> progress.should.eql totalProgressExpectation
dropzone.emit "uploadprogress", { }
totalProgressExpectation = 100
dropzone.files[0].upload.bytesSent = 2000
dropzone.files[1].upload.bytesSent = 2000
# It shouldn't matter that progress is not properly updated since the total size
# should be calculated from the bytes
dropzone.on "totaluploadprogress", (progress) -> progress.should.eql totalProgressExpectation
dropzone.emit "uploadprogress", { }
describe "helper function", ->
describe "getExistingFallback()", ->
element = null
dropzone = null
beforeEach ->
element = Dropzone.createElement """<div></div>"""
dropzone = new Dropzone element, url: "url"
it "should return undefined if no fallback", ->
expect(dropzone.getExistingFallback()).to.equal undefined
it "should only return the fallback element if it contains exactly fallback", ->
element.appendChild Dropzone.createElement """<form class="fallbacks"></form>"""
element.appendChild Dropzone.createElement """<form class="sfallback"></form>"""
expect(dropzone.getExistingFallback()).to.equal undefined
it "should return divs as fallback", ->
fallback = Dropzone.createElement """<form class=" abc fallback test "></form>"""
element.appendChild fallback
fallback.should.equal dropzone.getExistingFallback()
it "should return forms as fallback", ->
fallback = Dropzone.createElement """<div class=" abc fallback test "></div>"""
element.appendChild fallback
fallback.should.equal dropzone.getExistingFallback()
describe "file handling", ->
mockFile = null
dropzone = null
beforeEach ->
mockFile = getMockFile()
element = Dropzone.createElement """<div></div>"""
dropzone = new Dropzone element, url: "/the/url"
afterEach ->
dropzone.destroy()
describe "addFile()", ->
it "should properly set the status of the file", ->
doneFunction = null
dropzone.accept = (file, done) -> doneFunction = done
dropzone.processFile = ->
dropzone.uploadFile = ->
dropzone.addFile mockFile
mockFile.status.should.eql Dropzone.ADDED
doneFunction()
mockFile.status.should.eql Dropzone.ACCEPTED
mockFile = getMockFile()
dropzone.addFile mockFile
mockFile.status.should.eql Dropzone.ADDED
doneFunction("error")
mockFile.status.should.eql Dropzone.ERROR
describe "uploadFile()", ->
xhr = null
requests = null
beforeEach ->
xhr = sinon.useFakeXMLHttpRequest()
requests = [ ]
xhr.onCreate = (xhr) -> requests.push xhr
afterEach ->
xhr.restore()
it "should properly urlencode the filename for the headers", ->
dropzone.uploadFile mockFile
requests[0].requestHeaders["X-File-Name"].should.eql 'test%20file%20name'
describe "settings()", ->
it "should correctly set `withCredentials` on the xhr object", ->
dropzone.uploadFile mockFile
requests.length.should.eql 1
requests[0].withCredentials.should.eql no
dropzone.options.withCredentials = yes
dropzone.uploadFile mockFile
requests.length.should.eql 2
requests[1].withCredentials.should.eql yes
it "should correctly override headers on the xhr object", ->
dropzone.options.headers = {"Foo-Header": "foobar"}
dropzone.uploadFile mockFile
requests[0].requestHeaders["Foo-Header"].should.eql 'foobar'
requests[0].requestHeaders["X-File-Name"].should.eql 'test%20file%20name'
describe "should properly set status of file", ->
it "should correctly set `withCredentials` on the xhr object", ->
dropzone.addFile mockFile
mockFile.status.should.eql Dropzone.UPLOADING
requests.length.should.equal 1
requests[0].status = 400
requests[0].onload()
mockFile.status.should.eql Dropzone.ERROR
mockFile = getMockFile()
dropzone.addFile mockFile
mockFile.status.should.eql Dropzone.UPLOADING
requests.length.should.equal 2
requests[1].status = 200
requests[1].onload()
mockFile.status.should.eql Dropzone.SUCCESS
| true | chai.should()
describe "Dropzone", ->
getMockFile = ->
name: "test file name"
size: 123456
type: "text/html"
describe "static functions", ->
describe "Dropzone.createElement()", ->
element = Dropzone.createElement """<div class="test"><span>Hallo</span></div>"""
it "should properly create an element from a string", ->
element.tagName.should.equal "DIV"
it "should properly add the correct class", ->
element.classList.contains("test").should.be.ok
it "should properly create child elements", ->
element.querySelector("span").tagName.should.equal "SPAN"
it "should always return only one element", ->
element = Dropzone.createElement """<div></div><span></span>"""
element.tagName.should.equal "DIV"
describe "Dropzone.elementInside()", ->
element = Dropzone.createElement """<div id="test"><div class="child1"><div class="child2"></div></div></div>"""
document.body.appendChild element
child1 = element.querySelector ".child1"
child2 = element.querySelector ".child2"
after -> document.body.removeChild element
it "should return yes if elements are the same", ->
Dropzone.elementInside(element, element).should.be.ok
it "should return yes if element is direct child", ->
Dropzone.elementInside(child1, element).should.be.ok
it "should return yes if element is some child", ->
Dropzone.elementInside(child2, element).should.be.ok
Dropzone.elementInside(child2, document.body).should.be.ok
it "should return no unless element is some child", ->
Dropzone.elementInside(element, child1).should.not.be.ok
Dropzone.elementInside(document.body, child1).should.not.be.ok
describe "Dropzone.optionsForElement()", ->
testOptions =
url: "/some/url"
method: "put"
before -> Dropzone.options.testElement = testOptions
after -> delete Dropzone.options.testElement
element = document.createElement "div"
it "should take options set in Dropzone.options from camelized id", ->
element.id = "test-element"
Dropzone.optionsForElement(element).should.equal testOptions
it "should return undefined if no options set", ->
element.id = "test-element2"
expect(Dropzone.optionsForElement(element)).to.equal undefined
describe "Dropzone.forElement()", ->
element = document.createElement "div"
element.id = "some-test-element"
dropzone = null
before ->
document.body.appendChild element
dropzone = new Dropzone element, url: "/test"
after ->
dropzone.disable()
document.body.removeChild element
it "should return null if no dropzone attached", ->
expect(Dropzone.forElement document.createElement "div").to.equal null
it "should accept css selectors", ->
expect(Dropzone.forElement "#some-test-element").to.equal dropzone
it "should accept native elements", ->
expect(Dropzone.forElement element).to.equal dropzone
describe "Dropzone.discover()", ->
element1 = document.createElement "div"
element1.className = "dropzone"
element2 = element1.cloneNode()
element3 = element1.cloneNode()
element1.id = "test-element-1"
element2.id = "test-element-2"
element3.id = "test-element-3"
describe "specific options", ->
before ->
Dropzone.options.testElement1 = url: "test-url"
Dropzone.options.testElement2 = false # Disabled
document.body.appendChild element1
document.body.appendChild element2
Dropzone.discover()
after ->
document.body.removeChild element1
document.body.removeChild element2
it "should find elements with a .dropzone class", ->
element1.dropzone.should.be.ok
it "should not create dropzones with disabled options", ->
expect(element2.dropzone).to.not.be.ok
describe "Dropzone.autoDiscover", ->
before ->
Dropzone.options.testElement3 = url: "test-url"
document.body.appendChild element3
after ->
document.body.removeChild element3
it "should not create dropzones if Dropzone.autoDiscover == false", ->
Dropzone.autoDiscover = off
Dropzone.discover()
expect(element3.dropzone).to.not.be.ok
describe "Dropzone.isValidMimeType()", ->
it "should return true if called without acceptedMimeTypes", ->
Dropzone.isValidMimeType("some/type", null).should.be.ok
it "should properly validate if called with concrete mime types", ->
acceptedMimeTypes = "text/html,image/jpeg,application/json"
Dropzone.isValidMimeType("text/html", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("image/jpeg", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("application/json", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("image/bmp", acceptedMimeTypes).should.not.be.ok
it "should properly validate if called with base mime types", ->
acceptedMimeTypes = "text/*,image/*,application/*"
Dropzone.isValidMimeType("text/html", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("image/jpeg", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("application/json", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("image/bmp", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("some/type", acceptedMimeTypes).should.not.be.ok
it "should properly validate if called with mixed mime types", ->
acceptedMimeTypes = "text/*,image/jpeg,application/*"
Dropzone.isValidMimeType("text/html", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("image/jpeg", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("image/bmp", acceptedMimeTypes).should.not.be.ok
Dropzone.isValidMimeType("application/json", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("some/type", acceptedMimeTypes).should.not.be.ok
it "should properly validate even with spaces in between", ->
acceptedMimeTypes = "text/html , image/jpeg, application/json"
Dropzone.isValidMimeType("text/html", acceptedMimeTypes).should.be.ok
Dropzone.isValidMimeType("image/jpeg", acceptedMimeTypes).should.be.ok
describe "Dropzone.getElement() / getElements()", ->
tmpElements = [ ]
beforeEach ->
tmpElements = [ ]
tmpElements.push Dropzone.createElement """<div class="tmptest"></div>"""
tmpElements.push Dropzone.createElement """<div id="tmptest1" class="random"></div>"""
tmpElements.push Dropzone.createElement """<div class="random div"></div>"""
tmpElements.forEach (el) -> document.body.appendChild el
afterEach ->
tmpElements.forEach (el) -> document.body.removeChild el
describe ".getElement()", ->
it "should accept a string", ->
el = Dropzone.getElement ".tmptest"
el.should.equal tmpElements[0]
el = Dropzone.getElement "#tmptest1"
el.should.equal tmpElements[1]
it "should accept a node", ->
el = Dropzone.getElement tmpElements[2]
el.should.equal tmpElements[2]
it "should fail if invalid selector", ->
errorMessage = "Invalid `clickable` option provided. Please provide a CSS selector or a plain HTML element."
expect(-> Dropzone.getElement "lblasdlfsfl", "clickable").to.throw errorMessage
expect(-> Dropzone.getElement { "lblasdlfsfl" }, "clickable").to.throw errorMessage
expect(-> Dropzone.getElement [ "lblasdlfsfl" ], "clickable").to.throw errorMessage
describe ".getElements()", ->
it "should accept a list of strings", ->
els = Dropzone.getElements [ ".tmptest", "#tmptest1" ]
els.should.eql [ tmpElements[0], tmpElements[1] ]
it "should accept a list of nodes", ->
els = Dropzone.getElements [ tmpElements[0], tmpElements[2] ]
els.should.eql [ tmpElements[0], tmpElements[2] ]
it "should accept a mixed list", ->
els = Dropzone.getElements [ "#tmptest1", tmpElements[2] ]
els.should.eql [ tmpElements[1], tmpElements[2] ]
it "should accept a string selector", ->
els = Dropzone.getElements ".random"
els.should.eql [ tmpElements[1], tmpElements[2] ]
it "should accept a single node", ->
els = Dropzone.getElements tmpElements[1]
els.should.eql [ tmpElements[1] ]
it "should fail if invalid selector", ->
errorMessage = "Invalid `clickable` option provided. Please provide a CSS selector, a plain HTML element or a list of those."
expect(-> Dropzone.getElements "lblasdlfsfl", "clickable").to.throw errorMessage
expect(-> Dropzone.getElements [ "lblasdlfsfl" ], "clickable").to.throw errorMessage
describe "constructor()", ->
dropzone = null
afterEach -> dropzone.destroy() if dropzone?
it "should throw an exception if the element is invalid", ->
expect(-> dropzone = new Dropzone "#invalid-element").to.throw "Invalid dropzone element."
it "should throw an exception if assigned twice to the same element", ->
element = document.createElement "div"
dropzone = new Dropzone element, url: "url"
expect(-> new Dropzone element, url: "url").to.throw "Dropzone already attached."
it "should throw an exception if both acceptParameter and acceptedMimeTypes are specified", ->
element = document.createElement "div"
expect(-> dropzone = new Dropzone element, url: "test", acceptParameter: "param", acceptedMimeTypes: "types").to.throw "You can't provide both 'acceptParameter' and 'acceptedMimeTypes'. 'acceptParameter' is deprecated."
it "should set itself as element.dropzone", ->
element = document.createElement "div"
dropzone = new Dropzone element, url: "url"
element.dropzone.should.equal dropzone
describe "options", ->
element = null
element2 = null
beforeEach ->
element = document.createElement "div"
element.id = "test-element"
element2 = document.createElement "div"
element2.id = "test-element2"
Dropzone.options.testElement = url: "/some/url", parallelUploads: 10
afterEach -> delete Dropzone.options.testElement
it "should take the options set in Dropzone.options", ->
dropzone = new Dropzone element
dropzone.options.url.should.equal "/some/url"
dropzone.options.parallelUploads.should.equal 10
it "should prefer passed options over Dropzone.options", ->
dropzone = new Dropzone element, url: "/some/other/url"
dropzone.options.url.should.equal "/some/other/url"
it "should take the default options if nothing set in Dropzone.options", ->
dropzone = new Dropzone element2, url: "/some/url"
dropzone.options.parallelUploads.should.equal 2
it "should call the fallback function if forceFallback == true", (done) ->
dropzone = new Dropzone element,
url: "/some/other/url"
forceFallback: on
fallback: -> done()
describe "options.clickable", ->
clickableElement = null
dropzone = null
beforeEach ->
clickableElement = document.createElement "div"
clickableElement.className = "some-clickable"
document.body.appendChild clickableElement
afterEach ->
document.body.removeChild clickableElement
dropzone.destroy if dropzone?
it "should use the default element if clickable == true", ->
dropzone = new Dropzone element, clickable: yes
dropzone.clickableElements.should.eql [ dropzone.element ]
it "should lookup the element if clickable is a CSS selector", ->
dropzone = new Dropzone element, clickable: ".some-clickable"
dropzone.clickableElements.should.eql [ clickableElement ]
it "should simply use the provided element", ->
dropzone = new Dropzone element, clickable: clickableElement
dropzone.clickableElements.should.eql [ clickableElement ]
it "should accept multiple clickable elements", ->
dropzone = new Dropzone element, clickable: [ document.body, ".some-clickable" ]
dropzone.clickableElements.should.eql [ document.body, clickableElement ]
it "should throw an exception if the element is invalid", ->
expect(-> dropzone = new Dropzone element, clickable: ".some-invalid-clickable").to.throw "Invalid `clickable` option provided. Please provide a CSS selector, a plain HTML element or a list of those."
describe "init()", ->
describe "clickable", ->
dropzones =
"using acceptParameter": new Dropzone(Dropzone.createElement("""<form action="/"></form>"""), { clickable: yes, acceptParameter: "audio/*,video/*" })
"using acceptedMimeTypes": new Dropzone(Dropzone.createElement("""<form action="/"></form>"""), { clickable: yes, acceptedMimeTypes: "audio/*,video/*" })
it "should not add an accept attribute if no acceptParameter", ->
dropzone = new Dropzone (Dropzone.createElement """<form action="/"></form>"""), clickable: yes, acceptParameter: null, acceptedMimeTypes: null
dropzone.hiddenFileInput.hasAttribute("accept").should.be.false
for name, dropzone of dropzones
describe name, ->
do (dropzone) ->
it "should create a hidden file input if clickable", ->
dropzone.hiddenFileInput.should.be.ok
dropzone.hiddenFileInput.tagName.should.equal "INPUT"
it "should use the acceptParameter", ->
dropzone.hiddenFileInput.getAttribute("accept").should.equal "audio/*,video/*"
it "should create a new input element when something is selected to reset the input field", ->
for i in [0..3]
hiddenFileInput = dropzone.hiddenFileInput
event = document.createEvent "HTMLEvents"
event.initEvent "change", true, true
hiddenFileInput.dispatchEvent event
dropzone.hiddenFileInput.should.not.equal hiddenFileInput
Dropzone.elementInside(hiddenFileInput, document).should.not.be.ok
it "should create a data-dz-message element", ->
element = Dropzone.createElement """<form class="dropzone" action="/"></form>"""
dropzone = new Dropzone element, clickable: yes, acceptParameter: null, acceptedMimeTypes: null
element.querySelector("[data-dz-message]").should.be.instanceof Element
describe "options", ->
element = null
dropzone = null
beforeEach ->
element = Dropzone.createElement """<div></div>"""
dropzone = new Dropzone element, maxFilesize: 4, url: "url", acceptedMimeTypes: "audio/*,image/png"
describe "file specific", ->
file = null
beforeEach ->
file =
name: "PI:NAME:<NAME>END_PI"
size: 2 * 1000 * 1000
dropzone.options.addedfile.call dropzone, file
describe ".addedFile()", ->
it "should properly create the previewElement", ->
file.previewElement.should.be.instanceof Element
file.previewElement.querySelector("[data-dz-name]").innerHTML.should.eql "test name"
file.previewElement.querySelector("[data-dz-size]").innerHTML.should.eql "<strong>2</strong> MB"
describe ".error()", ->
it "should properly insert the error", ->
dropzone.options.error.call dropzone, file, "test message"
file.previewElement.querySelector("[data-dz-errormessage]").innerHTML.should.eql "test message"
describe ".thumbnail()", ->
it "should properly insert the error", ->
transparentGif = "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="
dropzone.options.thumbnail.call dropzone, file, transparentGif
thumbnail = file.previewElement.querySelector("[data-dz-thumbnail]")
thumbnail.src.should.eql transparentGif
thumbnail.alt.should.eql "test name"
describe ".uploadprogress()", ->
it "should properly set the width", ->
dropzone.options.uploadprogress.call dropzone, file, 0
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql "0%"
dropzone.options.uploadprogress.call dropzone, file, 80
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql "80%"
dropzone.options.uploadprogress.call dropzone, file, 90
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql "90%"
dropzone.options.uploadprogress.call dropzone, file, 100
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql "100%"
describe "instance", ->
element = null
dropzone = null
xhr = null
requests = null
beforeEach ->
xhr = sinon.useFakeXMLHttpRequest()
requests = [ ]
xhr.onCreate = (xhr) -> requests.push xhr
element = Dropzone.createElement """<div></div>"""
document.body.appendChild element
dropzone = new Dropzone element, maxFilesize: 4, url: "url", acceptedMimeTypes: "audio/*,image/png", uploadprogress: ->
afterEach ->
document.body.removeChild element
dropzone.destroy()
xhr.restore()
describe ".accept()", ->
it "should pass if the filesize is OK", ->
dropzone.accept { size: 2 * 1024 * 1024, type: "audio/mp3" }, (err) -> expect(err).to.be.undefined
it "shouldn't pass if the filesize is too big", ->
dropzone.accept { size: 10 * 1024 * 1024, type: "audio/mp3" }, (err) -> err.should.eql "File is too big (10MB). Max filesize: 4MB."
it "should properly accept files which mime types are listed in acceptedMimeTypes", ->
dropzone.accept { type: "audio/mp3" }, (err) -> expect(err).to.be.undefined
dropzone.accept { type: "image/png" }, (err) -> expect(err).to.be.undefined
dropzone.accept { type: "audio/wav" }, (err) -> expect(err).to.be.undefined
it "should properly reject files when the mime type isn't listed in acceptedMimeTypes", ->
dropzone.accept { type: "image/jpeg" }, (err) -> err.should.eql "You can't upload files of this type."
describe ".removeFile()", ->
it "should abort uploading if file is currently being uploaded", ->
mockFile = getMockFile()
dropzone.uploadFile = (file) ->
dropzone.accept = (file, done) -> done()
sinon.stub dropzone, "cancelUpload"
dropzone.addFile mockFile
mockFile.status.should.equal Dropzone.UPLOADING
dropzone.filesProcessing[0].should.equal mockFile
dropzone.cancelUpload.callCount.should.equal 0
dropzone.removeFile mockFile
dropzone.cancelUpload.callCount.should.equal 1
describe ".cancelUpload()", ->
it "should properly cancel upload if file currently uploading", ->
mockFile = getMockFile()
dropzone.accept = (file, done) -> done()
dropzone.addFile mockFile
mockFile.status.should.equal Dropzone.UPLOADING
dropzone.filesProcessing[0].should.equal mockFile
dropzone.cancelUpload mockFile
mockFile.status.should.equal Dropzone.CANCELED
dropzone.filesProcessing.length.should.equal 0
dropzone.filesQueue.length.should.equal 0
it "should properly cancel the upload if file is not yet uploading", ->
mockFile = getMockFile()
dropzone.accept = (file, done) -> done()
# Making sure the file stays in the queue.
dropzone.options.parallelUploads = 0
dropzone.addFile mockFile
mockFile.status.should.equal Dropzone.ACCEPTED
dropzone.filesQueue[0].should.equal mockFile
dropzone.cancelUpload mockFile
mockFile.status.should.equal Dropzone.CANCELED
dropzone.filesQueue.length.should.equal 0
dropzone.filesProcessing.length.should.equal 0
describe ".disable()", ->
it "should properly cancel all pending uploads", ->
dropzone.accept = (file, done) -> done()
dropzone.options.parallelUploads = 1
dropzone.addFile getMockFile()
dropzone.addFile getMockFile()
dropzone.filesProcessing.length.should.equal 1
dropzone.filesQueue.length.should.equal 1
dropzone.files.length.should.equal 2
sinon.spy requests[0], "abort"
requests[0].abort.callCount.should.equal 0
dropzone.disable()
requests[0].abort.callCount.should.equal 1
dropzone.filesProcessing.length.should.equal 0
dropzone.filesQueue.length.should.equal 0
dropzone.files.length.should.equal 2
dropzone.files[0].status.should.equal Dropzone.CANCELED
dropzone.files[1].status.should.equal Dropzone.CANCELED
describe ".destroy()", ->
it "should properly cancel all pending uploads and remove all file references", ->
dropzone.accept = (file, done) -> done()
dropzone.options.parallelUploads = 1
dropzone.addFile getMockFile()
dropzone.addFile getMockFile()
dropzone.filesProcessing.length.should.equal 1
dropzone.filesQueue.length.should.equal 1
dropzone.files.length.should.equal 2
sinon.spy dropzone, "disable"
dropzone.destroy()
dropzone.disable.callCount.should.equal 1
describe ".filesize()", ->
it "should convert to KiloBytes, etc.. not KibiBytes", ->
dropzone.filesize(2 * 1024 * 1024).should.eql "<strong>2.1</strong> MB"
dropzone.filesize(2 * 1000 * 1000).should.eql "<strong>2</strong> MB"
dropzone.filesize(2 * 1024 * 1024 * 1024).should.eql "<strong>2.1</strong> GB"
dropzone.filesize(2 * 1000 * 1000 * 1000).should.eql "<strong>2</strong> GB"
describe "events", ->
describe "progress updates", ->
it "should properly emit a totaluploadprogress event", ->
dropzone.files = [
{
size: 1990
upload:
progress: 20
total: 2000 # The bytes to upload are higher than the file size
bytesSent: 400
}
{
size: 1990
upload:
progress: 10
total: 2000 # The bytes to upload are higher than the file size
bytesSent: 200
}
]
dropzone.acceptedFiles = dropzone.files
totalProgressExpectation = 15
dropzone.on "totaluploadprogress", (progress) -> progress.should.eql totalProgressExpectation
dropzone.emit "uploadprogress", { }
totalProgressExpectation = 97.5
dropzone.files[0].upload.bytesSent = 2000
dropzone.files[1].upload.bytesSent = 1900
# It shouldn't matter that progress is not properly updated since the total size
# should be calculated from the bytes
dropzone.on "totaluploadprogress", (progress) -> progress.should.eql totalProgressExpectation
dropzone.emit "uploadprogress", { }
totalProgressExpectation = 100
dropzone.files[0].upload.bytesSent = 2000
dropzone.files[1].upload.bytesSent = 2000
# It shouldn't matter that progress is not properly updated since the total size
# should be calculated from the bytes
dropzone.on "totaluploadprogress", (progress) -> progress.should.eql totalProgressExpectation
dropzone.emit "uploadprogress", { }
describe "helper function", ->
describe "getExistingFallback()", ->
element = null
dropzone = null
beforeEach ->
element = Dropzone.createElement """<div></div>"""
dropzone = new Dropzone element, url: "url"
it "should return undefined if no fallback", ->
expect(dropzone.getExistingFallback()).to.equal undefined
it "should only return the fallback element if it contains exactly fallback", ->
element.appendChild Dropzone.createElement """<form class="fallbacks"></form>"""
element.appendChild Dropzone.createElement """<form class="sfallback"></form>"""
expect(dropzone.getExistingFallback()).to.equal undefined
it "should return divs as fallback", ->
fallback = Dropzone.createElement """<form class=" abc fallback test "></form>"""
element.appendChild fallback
fallback.should.equal dropzone.getExistingFallback()
it "should return forms as fallback", ->
fallback = Dropzone.createElement """<div class=" abc fallback test "></div>"""
element.appendChild fallback
fallback.should.equal dropzone.getExistingFallback()
describe "file handling", ->
mockFile = null
dropzone = null
beforeEach ->
mockFile = getMockFile()
element = Dropzone.createElement """<div></div>"""
dropzone = new Dropzone element, url: "/the/url"
afterEach ->
dropzone.destroy()
describe "addFile()", ->
it "should properly set the status of the file", ->
doneFunction = null
dropzone.accept = (file, done) -> doneFunction = done
dropzone.processFile = ->
dropzone.uploadFile = ->
dropzone.addFile mockFile
mockFile.status.should.eql Dropzone.ADDED
doneFunction()
mockFile.status.should.eql Dropzone.ACCEPTED
mockFile = getMockFile()
dropzone.addFile mockFile
mockFile.status.should.eql Dropzone.ADDED
doneFunction("error")
mockFile.status.should.eql Dropzone.ERROR
describe "uploadFile()", ->
xhr = null
requests = null
beforeEach ->
xhr = sinon.useFakeXMLHttpRequest()
requests = [ ]
xhr.onCreate = (xhr) -> requests.push xhr
afterEach ->
xhr.restore()
it "should properly urlencode the filename for the headers", ->
dropzone.uploadFile mockFile
requests[0].requestHeaders["X-File-Name"].should.eql 'test%20file%20name'
describe "settings()", ->
it "should correctly set `withCredentials` on the xhr object", ->
dropzone.uploadFile mockFile
requests.length.should.eql 1
requests[0].withCredentials.should.eql no
dropzone.options.withCredentials = yes
dropzone.uploadFile mockFile
requests.length.should.eql 2
requests[1].withCredentials.should.eql yes
it "should correctly override headers on the xhr object", ->
dropzone.options.headers = {"Foo-Header": "foobar"}
dropzone.uploadFile mockFile
requests[0].requestHeaders["Foo-Header"].should.eql 'foobar'
requests[0].requestHeaders["X-File-Name"].should.eql 'test%20file%20name'
describe "should properly set status of file", ->
it "should correctly set `withCredentials` on the xhr object", ->
dropzone.addFile mockFile
mockFile.status.should.eql Dropzone.UPLOADING
requests.length.should.equal 1
requests[0].status = 400
requests[0].onload()
mockFile.status.should.eql Dropzone.ERROR
mockFile = getMockFile()
dropzone.addFile mockFile
mockFile.status.should.eql Dropzone.UPLOADING
requests.length.should.equal 2
requests[1].status = 200
requests[1].onload()
mockFile.status.should.eql Dropzone.SUCCESS
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9985182285308838,
"start": 12,
"tag": "NAME",
"value": "Joyent"
},
{
"context": " client.send msg, 0, msg.length, common.PORT, \"127.0.0.1\", (err) ->\n throw err i... | test/simple/test-child-process-fork-dgram.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.
#
# * The purpose of this test is to make sure that when forking a process,
# * sending a fd representing a UDP socket to the child and sending messages
# * to this endpoint, these messages are distributed to the parent and the
# * child process.
# *
# * Because it's not really possible to predict how the messages will be
# * distributed among the parent and the child processes, we keep sending
# * messages until both the parent and the child received at least one
# * message. The worst case scenario is when either one never receives
# * a message. In this case the test runner will timeout after 60 secs
# * and the test will fail.
#
dgram = require("dgram")
fork = require("child_process").fork
assert = require("assert")
common = require("../common")
if process.platform is "win32"
console.error "Sending dgram sockets to child processes not supported"
process.exit 0
if process.argv[2] is "child"
childCollected = 0
server = undefined
process.on "message", removeMe = (msg, clusterServer) ->
if msg is "server"
server = clusterServer
server.on "message", ->
process.send "gotMessage"
return
else if msg is "stop"
server.close()
process.removeListener "message", removeMe
return
else
server = dgram.createSocket("udp4")
client = dgram.createSocket("udp4")
child = fork(__filename, ["child"])
msg = new Buffer("Some bytes")
childGotMessage = false
parentGotMessage = false
server.on "message", (msg, rinfo) ->
parentGotMessage = true
return
server.on "listening", ->
child.send "server", server
child.once "message", (msg) ->
childGotMessage = true if msg is "gotMessage"
return
sendMessages()
return
sendMessages = ->
timer = setInterval(->
client.send msg, 0, msg.length, common.PORT, "127.0.0.1", (err) ->
throw err if err
return
#
# * Both the parent and the child got at least one message,
# * test passed, clean up everyting.
#
if parentGotMessage and childGotMessage
clearInterval timer
shutdown()
return
, 1)
return
shutdown = ->
child.send "stop"
server.close()
client.close()
return
server.bind common.PORT, "127.0.0.1"
process.once "exit", ->
assert parentGotMessage
assert childGotMessage
return
| 97311 | # 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.
#
# * The purpose of this test is to make sure that when forking a process,
# * sending a fd representing a UDP socket to the child and sending messages
# * to this endpoint, these messages are distributed to the parent and the
# * child process.
# *
# * Because it's not really possible to predict how the messages will be
# * distributed among the parent and the child processes, we keep sending
# * messages until both the parent and the child received at least one
# * message. The worst case scenario is when either one never receives
# * a message. In this case the test runner will timeout after 60 secs
# * and the test will fail.
#
dgram = require("dgram")
fork = require("child_process").fork
assert = require("assert")
common = require("../common")
if process.platform is "win32"
console.error "Sending dgram sockets to child processes not supported"
process.exit 0
if process.argv[2] is "child"
childCollected = 0
server = undefined
process.on "message", removeMe = (msg, clusterServer) ->
if msg is "server"
server = clusterServer
server.on "message", ->
process.send "gotMessage"
return
else if msg is "stop"
server.close()
process.removeListener "message", removeMe
return
else
server = dgram.createSocket("udp4")
client = dgram.createSocket("udp4")
child = fork(__filename, ["child"])
msg = new Buffer("Some bytes")
childGotMessage = false
parentGotMessage = false
server.on "message", (msg, rinfo) ->
parentGotMessage = true
return
server.on "listening", ->
child.send "server", server
child.once "message", (msg) ->
childGotMessage = true if msg is "gotMessage"
return
sendMessages()
return
sendMessages = ->
timer = setInterval(->
client.send msg, 0, msg.length, common.PORT, "127.0.0.1", (err) ->
throw err if err
return
#
# * Both the parent and the child got at least one message,
# * test passed, clean up everyting.
#
if parentGotMessage and childGotMessage
clearInterval timer
shutdown()
return
, 1)
return
shutdown = ->
child.send "stop"
server.close()
client.close()
return
server.bind common.PORT, "127.0.0.1"
process.once "exit", ->
assert parentGotMessage
assert childGotMessage
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.
#
# * The purpose of this test is to make sure that when forking a process,
# * sending a fd representing a UDP socket to the child and sending messages
# * to this endpoint, these messages are distributed to the parent and the
# * child process.
# *
# * Because it's not really possible to predict how the messages will be
# * distributed among the parent and the child processes, we keep sending
# * messages until both the parent and the child received at least one
# * message. The worst case scenario is when either one never receives
# * a message. In this case the test runner will timeout after 60 secs
# * and the test will fail.
#
dgram = require("dgram")
fork = require("child_process").fork
assert = require("assert")
common = require("../common")
if process.platform is "win32"
console.error "Sending dgram sockets to child processes not supported"
process.exit 0
if process.argv[2] is "child"
childCollected = 0
server = undefined
process.on "message", removeMe = (msg, clusterServer) ->
if msg is "server"
server = clusterServer
server.on "message", ->
process.send "gotMessage"
return
else if msg is "stop"
server.close()
process.removeListener "message", removeMe
return
else
server = dgram.createSocket("udp4")
client = dgram.createSocket("udp4")
child = fork(__filename, ["child"])
msg = new Buffer("Some bytes")
childGotMessage = false
parentGotMessage = false
server.on "message", (msg, rinfo) ->
parentGotMessage = true
return
server.on "listening", ->
child.send "server", server
child.once "message", (msg) ->
childGotMessage = true if msg is "gotMessage"
return
sendMessages()
return
sendMessages = ->
timer = setInterval(->
client.send msg, 0, msg.length, common.PORT, "127.0.0.1", (err) ->
throw err if err
return
#
# * Both the parent and the child got at least one message,
# * test passed, clean up everyting.
#
if parentGotMessage and childGotMessage
clearInterval timer
shutdown()
return
, 1)
return
shutdown = ->
child.send "stop"
server.close()
client.close()
return
server.bind common.PORT, "127.0.0.1"
process.once "exit", ->
assert parentGotMessage
assert childGotMessage
return
|
[
{
"context": "\n yield [\n new User(username: 'alice', flag: true, email: 'alice@bookstore').save()\n ",
"end": 378,
"score": 0.938847541809082,
"start": 373,
"tag": "USERNAME",
"value": "alice"
},
{
"context": " new User(username: 'alice', flag: true, email: 'al... | test/count.coffee | bgaeddert/bookshelf-schema | 44 | Bookshelf = require 'bookshelf'
CheckIt = require 'checkit'
Schema = require '../src/'
init = require './init'
describe "Count", ->
this.timeout 3000
db = null
User = null
before co ->
db = init.init()
yield init.users()
class User extends db.Model
tableName: 'users'
yield [
new User(username: 'alice', flag: true, email: 'alice@bookstore').save()
new User(username: 'bob', flag: true, email: 'bob@bookstore').save()
new User(username: 'alan', flag: false).save()
]
it 'counts the number of models in a collection', ->
User.collection().count().should.become 3
it 'optionally counts by column (excluding null values)', ->
User.collection().count('email').should.become 2
it 'counts a filtered query', ->
User.collection().query('where', 'flag', '=', true).count().should.become 2
| 215227 | Bookshelf = require 'bookshelf'
CheckIt = require 'checkit'
Schema = require '../src/'
init = require './init'
describe "Count", ->
this.timeout 3000
db = null
User = null
before co ->
db = init.init()
yield init.users()
class User extends db.Model
tableName: 'users'
yield [
new User(username: 'alice', flag: true, email: '<EMAIL>').save()
new User(username: 'bob', flag: true, email: '<EMAIL>').save()
new User(username: 'alan', flag: false).save()
]
it 'counts the number of models in a collection', ->
User.collection().count().should.become 3
it 'optionally counts by column (excluding null values)', ->
User.collection().count('email').should.become 2
it 'counts a filtered query', ->
User.collection().query('where', 'flag', '=', true).count().should.become 2
| true | Bookshelf = require 'bookshelf'
CheckIt = require 'checkit'
Schema = require '../src/'
init = require './init'
describe "Count", ->
this.timeout 3000
db = null
User = null
before co ->
db = init.init()
yield init.users()
class User extends db.Model
tableName: 'users'
yield [
new User(username: 'alice', flag: true, email: 'PI:EMAIL:<EMAIL>END_PI').save()
new User(username: 'bob', flag: true, email: 'PI:EMAIL:<EMAIL>END_PI').save()
new User(username: 'alan', flag: false).save()
]
it 'counts the number of models in a collection', ->
User.collection().count().should.become 3
it 'optionally counts by column (excluding null values)', ->
User.collection().count('email').should.become 2
it 'counts a filtered query', ->
User.collection().query('where', 'flag', '=', true).count().should.become 2
|
[
{
"context": "\"Email\"\n type: String\n firstName:\n label: \"First Name\"\n type: String\n lastName:\n label: \"Last Na",
"end": 8174,
"score": 0.9920589327812195,
"start": 8164,
"tag": "NAME",
"value": "First Name"
},
{
"context": "st Name\"\n type: String\n last... | lib/scriptoriumCollections.coffee | UK-AS-HIVE/Scriptorium | 4 | @AvailableManifests = new Meteor.Collection('availablemanifests')
@AvailableManifests.attachSchema new SimpleSchema
user:
label: "User"
type: String
project:
label: "Project ID"
type: String
manifestPayload:
label: "Manifest Payload"
type: Object
blackbox: true
manifestLocation:
label: "Manifest Location"
type: String
manifestTitle:
label: "Manifest Title"
type: String
@ImageMetadata = new Meteor.Collection('iiifImageMetadata')
@ImageMetadata.attachSchema new SimpleSchema
manifestId:
type: String
retrievalUrl:
type: String
regEx: SimpleSchema.RegEx.Url
retrievalTimestamp:
type: new Date()
payload:
type: Object
blackbox: true
@DeskWidgets = new Mongo.Collection 'deskWidgets'
@DeskSnapshots = new Mongo.Collection 'deskSnapshots'
@DeskSnapshots.attachSchema new SimpleSchema
projectId:
type: String
userId:
type: String
title:
type: String
description:
type: String
optional: true
timestamp:
type: new Date()
widgets:
type: [Object]
blackbox: true
@Projects = new Meteor.Collection('projects')
@Projects.attachSchema new SimpleSchema
projectName:
label: "Project Name"
type: String
personal:
label: "Personal ID"
type: String
optional: true
permissions:
label: "Permissions"
type: [ Object ]
'permissions.$.level':
label: "Permissions Level"
type: String
allowedValues: [ 'admin', 'contributor' ]
'permissions.$.user':
label: "Permissions User"
type: String
miradorData:
label: "Mirador Data"
type: [ Object ]
'miradorData.$.manifestUri':
label: "Manifest URI"
type: String
'miradorData.$.location':
label: "Manifest Location"
type: String
'miradorData.$.title':
label: "Manifest Title"
type: String
'miradorData.$.widgets':
label: "Mirador Widgets"
type: [Object]
@Annotations = new Meteor.Collection('annotations')
@Annotations.attachSchema new SimpleSchema
canvasIndex:
label: "Annotation Canvas"
type: Number
manifestId:
label: "Project Manifest"
type: String
projectId:
label: "Project"
type: String
type:
type: String
allowedValues: ['commentary', 'transcription']
text:
type: String
x:
type: Number
decimal: true
y:
type: Number
decimal: true
w:
type: Number
decimal: true
h:
type: Number
decimal: true
@FileCabinet = new Meteor.Collection('filecabinet')
@FileCabinet.attachSchema new SimpleSchema
# TODO: this stores either text from CKEditor, or a FileRegistry ID reference
# probably should split into separate fields
content:
label: "Content"
type: String
optional: true
fileRegistryId:
label: "File Registry ID"
type: String
optional: true
date:
label: "Date Uploaded"
type: new Date()
description:
optional: true
label: "Description"
type: String
fileType:
label: "File Type"
type: String
allowedValues: [ "upload", "editor", "annotation" ]
open:
label: "File Open?"
type: Boolean
project:
label: "Project ID"
type: String
title:
label: "Title"
type: String
user:
label: "User ID"
type: String
editorLockedByUserId:
label: "Editor Locked By User ID"
type: String
optional: true
editorLockedByConnectionId:
label: "Editor Locked By Connection ID"
type: String
optional: true
# class @folioItems extends Minimongoid
# @_collection: new Meteor.Collection('folioitems')
@folioItems = new Meteor.Collection('folioitems')
@folioItems.attachSchema new SimpleSchema
projectId:
type: String
addedBy: # user id
type: String
lastUpdatedBy: # user id
type: String
canvas:
type: Object
label: "IIIF fragment"
optional: true
blackbox: true
imageURL:
type: String
metadata:
type: Object
optional: true
blackbox: true
'metadata.city':
type: String
'metadata.repository':
type: String
'metadata.collectionNumber':
type: String
'metadata.dateRange':
type: [Number]
'metadata.scriptName':
label: 'Type of Document'
type: [String]
allowedValues: ['All', 'Teaching Text', 'Administrative Document', 'Pastoral Care', 'Used in Dispute, Litigation, or Judgment', 'Legal Theory', 'Instrument of Government', 'For Private Use', 'Other']
'metadata.scriptFamily':
label: 'Community Context'
type: String
allowedValues: ['All', 'School or University', 'Manor or Village', 'Monastery', 'Cathedral and Episcopal Court', 'Royal or Imperial Court', 'Papal Curia', 'Town', 'Other']
optional: true
'metadata.scriptLanguage':
label: 'Region'
type: String
'metadata.scriptAlphabet':
type: String
'metadata.scriptTradition':
type: String
optional: true
'metadata.specificText':
type: String
'metadata.folioNumber':
type: String
'metadata.description':
type: String
'metadata.features':
type: String
'metadata.transcription':
type: String
optional: true
'metadata.collection':
type: String
optional: true
'metadata.commonName':
type: String
optional: false
'metadata.origin':
type: String
optional: true
'metadata.provenance':
type: String
optional: true
'metadata.dateExpression':
type: String
optional: true
'metadata.author':
type: String
optional: true
'metadata.title':
type: String
optional: true
'metadata.contributors':
type: String
optional: true
'metadata.manuscriptLink':
type: String
optional: true
'metadata.info':
type: String
optional: true
dateAdded:
type: new Date()
defaultValue: -> new Date()
lastUpdated:
type: new Date()
published:
type: Boolean
manifest:
type: String
label: "Absolute URL to manifest json"
@Bookshelves = new Meteor.Collection('bookshelves')
@Bookshelves.attachSchema new SimpleSchema
category:
label: "Category"
type: String
project:
label: "Project ID"
type: String
color:
label: "Category Color"
type: String
rank:
label: "Rank"
type: Number
decimal: true
@Books = new Meteor.Collection('books')
@Books.attachSchema new SimpleSchema
name:
label: "Book Name"
type: String
url:
label: "Book URL"
type: String
optional: true
bookshelfId:
label: "Bookshelf ID"
type: String
rank:
label: "Book Rank"
type: Number
decimal: true
fileRegistryId:
label: "File Registry ID"
type: String
optional: true
@EventStream = new Meteor.Collection 'eventStream'
@EventStream.attachSchema new SimpleSchema
projectId:
label: "Project Id"
type: String
userId:
label: "User ID"
type: String
timestamp:
label: "Timestamp"
type: new Date()
autoValue: -> new Date()
type:
# TODO: Figure out what these are actually going to be
# Potential information to want to store: chat messages, document creation, save revision, user added to project, manifest added?
allowedValues: [ 'deskSnapshots', 'filecabinet', 'annotations', 'availablemanifests', 'chat', 'project' ]
type: String
label: "Event Type"
message:
type: String
label: "Message"
optional: true
otherId:
# FileCabinet ID, Bookshelf ID, Manifest ID, etc.
type: String
label: "Other ID"
optional: true
@Messages = new Mongo.Collection 'messages'
@Messages.attachSchema new SimpleSchema
subject:
label: "Subject"
type: String
roomId:
label: "Room/Project Id"
type: String
startedBy:
label: "Thread Started By"
type: String
timestamp:
type: new Date()
posts:
label: "Posts"
type: [ Object ]
optional: true
'posts.$.user':
label: "Post Author"
type: String
'posts.$.message':
label: "Post"
type: String
'posts.$.timestamp':
label: "Post Timestamp"
type: new Date()
@RequestedAccounts = new Mongo.Collection 'requestedAccounts'
@RequestedAccounts.attachSchema new SimpleSchema
email:
unique: true
label: "Email"
type: String
firstName:
label: "First Name"
type: String
lastName:
label: "Last Name"
type: String
institution:
label: "Institutional Affiliation"
type: String
optional: true
research:
label: "Area of Research"
type: String
newProjectRequest:
label: "New Project Request Information"
type: String
optional: true
existingProjectRequest:
label: "Existing Project Request Information"
type: String
optional: true
denied:
type: Boolean
defaultValue: false
approved:
type: Boolean
defaultValue: false
created:
type: Boolean
defaultValue: false
| 81572 | @AvailableManifests = new Meteor.Collection('availablemanifests')
@AvailableManifests.attachSchema new SimpleSchema
user:
label: "User"
type: String
project:
label: "Project ID"
type: String
manifestPayload:
label: "Manifest Payload"
type: Object
blackbox: true
manifestLocation:
label: "Manifest Location"
type: String
manifestTitle:
label: "Manifest Title"
type: String
@ImageMetadata = new Meteor.Collection('iiifImageMetadata')
@ImageMetadata.attachSchema new SimpleSchema
manifestId:
type: String
retrievalUrl:
type: String
regEx: SimpleSchema.RegEx.Url
retrievalTimestamp:
type: new Date()
payload:
type: Object
blackbox: true
@DeskWidgets = new Mongo.Collection 'deskWidgets'
@DeskSnapshots = new Mongo.Collection 'deskSnapshots'
@DeskSnapshots.attachSchema new SimpleSchema
projectId:
type: String
userId:
type: String
title:
type: String
description:
type: String
optional: true
timestamp:
type: new Date()
widgets:
type: [Object]
blackbox: true
@Projects = new Meteor.Collection('projects')
@Projects.attachSchema new SimpleSchema
projectName:
label: "Project Name"
type: String
personal:
label: "Personal ID"
type: String
optional: true
permissions:
label: "Permissions"
type: [ Object ]
'permissions.$.level':
label: "Permissions Level"
type: String
allowedValues: [ 'admin', 'contributor' ]
'permissions.$.user':
label: "Permissions User"
type: String
miradorData:
label: "Mirador Data"
type: [ Object ]
'miradorData.$.manifestUri':
label: "Manifest URI"
type: String
'miradorData.$.location':
label: "Manifest Location"
type: String
'miradorData.$.title':
label: "Manifest Title"
type: String
'miradorData.$.widgets':
label: "Mirador Widgets"
type: [Object]
@Annotations = new Meteor.Collection('annotations')
@Annotations.attachSchema new SimpleSchema
canvasIndex:
label: "Annotation Canvas"
type: Number
manifestId:
label: "Project Manifest"
type: String
projectId:
label: "Project"
type: String
type:
type: String
allowedValues: ['commentary', 'transcription']
text:
type: String
x:
type: Number
decimal: true
y:
type: Number
decimal: true
w:
type: Number
decimal: true
h:
type: Number
decimal: true
@FileCabinet = new Meteor.Collection('filecabinet')
@FileCabinet.attachSchema new SimpleSchema
# TODO: this stores either text from CKEditor, or a FileRegistry ID reference
# probably should split into separate fields
content:
label: "Content"
type: String
optional: true
fileRegistryId:
label: "File Registry ID"
type: String
optional: true
date:
label: "Date Uploaded"
type: new Date()
description:
optional: true
label: "Description"
type: String
fileType:
label: "File Type"
type: String
allowedValues: [ "upload", "editor", "annotation" ]
open:
label: "File Open?"
type: Boolean
project:
label: "Project ID"
type: String
title:
label: "Title"
type: String
user:
label: "User ID"
type: String
editorLockedByUserId:
label: "Editor Locked By User ID"
type: String
optional: true
editorLockedByConnectionId:
label: "Editor Locked By Connection ID"
type: String
optional: true
# class @folioItems extends Minimongoid
# @_collection: new Meteor.Collection('folioitems')
@folioItems = new Meteor.Collection('folioitems')
@folioItems.attachSchema new SimpleSchema
projectId:
type: String
addedBy: # user id
type: String
lastUpdatedBy: # user id
type: String
canvas:
type: Object
label: "IIIF fragment"
optional: true
blackbox: true
imageURL:
type: String
metadata:
type: Object
optional: true
blackbox: true
'metadata.city':
type: String
'metadata.repository':
type: String
'metadata.collectionNumber':
type: String
'metadata.dateRange':
type: [Number]
'metadata.scriptName':
label: 'Type of Document'
type: [String]
allowedValues: ['All', 'Teaching Text', 'Administrative Document', 'Pastoral Care', 'Used in Dispute, Litigation, or Judgment', 'Legal Theory', 'Instrument of Government', 'For Private Use', 'Other']
'metadata.scriptFamily':
label: 'Community Context'
type: String
allowedValues: ['All', 'School or University', 'Manor or Village', 'Monastery', 'Cathedral and Episcopal Court', 'Royal or Imperial Court', 'Papal Curia', 'Town', 'Other']
optional: true
'metadata.scriptLanguage':
label: 'Region'
type: String
'metadata.scriptAlphabet':
type: String
'metadata.scriptTradition':
type: String
optional: true
'metadata.specificText':
type: String
'metadata.folioNumber':
type: String
'metadata.description':
type: String
'metadata.features':
type: String
'metadata.transcription':
type: String
optional: true
'metadata.collection':
type: String
optional: true
'metadata.commonName':
type: String
optional: false
'metadata.origin':
type: String
optional: true
'metadata.provenance':
type: String
optional: true
'metadata.dateExpression':
type: String
optional: true
'metadata.author':
type: String
optional: true
'metadata.title':
type: String
optional: true
'metadata.contributors':
type: String
optional: true
'metadata.manuscriptLink':
type: String
optional: true
'metadata.info':
type: String
optional: true
dateAdded:
type: new Date()
defaultValue: -> new Date()
lastUpdated:
type: new Date()
published:
type: Boolean
manifest:
type: String
label: "Absolute URL to manifest json"
@Bookshelves = new Meteor.Collection('bookshelves')
@Bookshelves.attachSchema new SimpleSchema
category:
label: "Category"
type: String
project:
label: "Project ID"
type: String
color:
label: "Category Color"
type: String
rank:
label: "Rank"
type: Number
decimal: true
@Books = new Meteor.Collection('books')
@Books.attachSchema new SimpleSchema
name:
label: "Book Name"
type: String
url:
label: "Book URL"
type: String
optional: true
bookshelfId:
label: "Bookshelf ID"
type: String
rank:
label: "Book Rank"
type: Number
decimal: true
fileRegistryId:
label: "File Registry ID"
type: String
optional: true
@EventStream = new Meteor.Collection 'eventStream'
@EventStream.attachSchema new SimpleSchema
projectId:
label: "Project Id"
type: String
userId:
label: "User ID"
type: String
timestamp:
label: "Timestamp"
type: new Date()
autoValue: -> new Date()
type:
# TODO: Figure out what these are actually going to be
# Potential information to want to store: chat messages, document creation, save revision, user added to project, manifest added?
allowedValues: [ 'deskSnapshots', 'filecabinet', 'annotations', 'availablemanifests', 'chat', 'project' ]
type: String
label: "Event Type"
message:
type: String
label: "Message"
optional: true
otherId:
# FileCabinet ID, Bookshelf ID, Manifest ID, etc.
type: String
label: "Other ID"
optional: true
@Messages = new Mongo.Collection 'messages'
@Messages.attachSchema new SimpleSchema
subject:
label: "Subject"
type: String
roomId:
label: "Room/Project Id"
type: String
startedBy:
label: "Thread Started By"
type: String
timestamp:
type: new Date()
posts:
label: "Posts"
type: [ Object ]
optional: true
'posts.$.user':
label: "Post Author"
type: String
'posts.$.message':
label: "Post"
type: String
'posts.$.timestamp':
label: "Post Timestamp"
type: new Date()
@RequestedAccounts = new Mongo.Collection 'requestedAccounts'
@RequestedAccounts.attachSchema new SimpleSchema
email:
unique: true
label: "Email"
type: String
firstName:
label: "<NAME>"
type: String
lastName:
label: "<NAME>"
type: String
institution:
label: "Institutional Affiliation"
type: String
optional: true
research:
label: "Area of Research"
type: String
newProjectRequest:
label: "New Project Request Information"
type: String
optional: true
existingProjectRequest:
label: "Existing Project Request Information"
type: String
optional: true
denied:
type: Boolean
defaultValue: false
approved:
type: Boolean
defaultValue: false
created:
type: Boolean
defaultValue: false
| true | @AvailableManifests = new Meteor.Collection('availablemanifests')
@AvailableManifests.attachSchema new SimpleSchema
user:
label: "User"
type: String
project:
label: "Project ID"
type: String
manifestPayload:
label: "Manifest Payload"
type: Object
blackbox: true
manifestLocation:
label: "Manifest Location"
type: String
manifestTitle:
label: "Manifest Title"
type: String
@ImageMetadata = new Meteor.Collection('iiifImageMetadata')
@ImageMetadata.attachSchema new SimpleSchema
manifestId:
type: String
retrievalUrl:
type: String
regEx: SimpleSchema.RegEx.Url
retrievalTimestamp:
type: new Date()
payload:
type: Object
blackbox: true
@DeskWidgets = new Mongo.Collection 'deskWidgets'
@DeskSnapshots = new Mongo.Collection 'deskSnapshots'
@DeskSnapshots.attachSchema new SimpleSchema
projectId:
type: String
userId:
type: String
title:
type: String
description:
type: String
optional: true
timestamp:
type: new Date()
widgets:
type: [Object]
blackbox: true
@Projects = new Meteor.Collection('projects')
@Projects.attachSchema new SimpleSchema
projectName:
label: "Project Name"
type: String
personal:
label: "Personal ID"
type: String
optional: true
permissions:
label: "Permissions"
type: [ Object ]
'permissions.$.level':
label: "Permissions Level"
type: String
allowedValues: [ 'admin', 'contributor' ]
'permissions.$.user':
label: "Permissions User"
type: String
miradorData:
label: "Mirador Data"
type: [ Object ]
'miradorData.$.manifestUri':
label: "Manifest URI"
type: String
'miradorData.$.location':
label: "Manifest Location"
type: String
'miradorData.$.title':
label: "Manifest Title"
type: String
'miradorData.$.widgets':
label: "Mirador Widgets"
type: [Object]
@Annotations = new Meteor.Collection('annotations')
@Annotations.attachSchema new SimpleSchema
canvasIndex:
label: "Annotation Canvas"
type: Number
manifestId:
label: "Project Manifest"
type: String
projectId:
label: "Project"
type: String
type:
type: String
allowedValues: ['commentary', 'transcription']
text:
type: String
x:
type: Number
decimal: true
y:
type: Number
decimal: true
w:
type: Number
decimal: true
h:
type: Number
decimal: true
@FileCabinet = new Meteor.Collection('filecabinet')
@FileCabinet.attachSchema new SimpleSchema
# TODO: this stores either text from CKEditor, or a FileRegistry ID reference
# probably should split into separate fields
content:
label: "Content"
type: String
optional: true
fileRegistryId:
label: "File Registry ID"
type: String
optional: true
date:
label: "Date Uploaded"
type: new Date()
description:
optional: true
label: "Description"
type: String
fileType:
label: "File Type"
type: String
allowedValues: [ "upload", "editor", "annotation" ]
open:
label: "File Open?"
type: Boolean
project:
label: "Project ID"
type: String
title:
label: "Title"
type: String
user:
label: "User ID"
type: String
editorLockedByUserId:
label: "Editor Locked By User ID"
type: String
optional: true
editorLockedByConnectionId:
label: "Editor Locked By Connection ID"
type: String
optional: true
# class @folioItems extends Minimongoid
# @_collection: new Meteor.Collection('folioitems')
@folioItems = new Meteor.Collection('folioitems')
@folioItems.attachSchema new SimpleSchema
projectId:
type: String
addedBy: # user id
type: String
lastUpdatedBy: # user id
type: String
canvas:
type: Object
label: "IIIF fragment"
optional: true
blackbox: true
imageURL:
type: String
metadata:
type: Object
optional: true
blackbox: true
'metadata.city':
type: String
'metadata.repository':
type: String
'metadata.collectionNumber':
type: String
'metadata.dateRange':
type: [Number]
'metadata.scriptName':
label: 'Type of Document'
type: [String]
allowedValues: ['All', 'Teaching Text', 'Administrative Document', 'Pastoral Care', 'Used in Dispute, Litigation, or Judgment', 'Legal Theory', 'Instrument of Government', 'For Private Use', 'Other']
'metadata.scriptFamily':
label: 'Community Context'
type: String
allowedValues: ['All', 'School or University', 'Manor or Village', 'Monastery', 'Cathedral and Episcopal Court', 'Royal or Imperial Court', 'Papal Curia', 'Town', 'Other']
optional: true
'metadata.scriptLanguage':
label: 'Region'
type: String
'metadata.scriptAlphabet':
type: String
'metadata.scriptTradition':
type: String
optional: true
'metadata.specificText':
type: String
'metadata.folioNumber':
type: String
'metadata.description':
type: String
'metadata.features':
type: String
'metadata.transcription':
type: String
optional: true
'metadata.collection':
type: String
optional: true
'metadata.commonName':
type: String
optional: false
'metadata.origin':
type: String
optional: true
'metadata.provenance':
type: String
optional: true
'metadata.dateExpression':
type: String
optional: true
'metadata.author':
type: String
optional: true
'metadata.title':
type: String
optional: true
'metadata.contributors':
type: String
optional: true
'metadata.manuscriptLink':
type: String
optional: true
'metadata.info':
type: String
optional: true
dateAdded:
type: new Date()
defaultValue: -> new Date()
lastUpdated:
type: new Date()
published:
type: Boolean
manifest:
type: String
label: "Absolute URL to manifest json"
@Bookshelves = new Meteor.Collection('bookshelves')
@Bookshelves.attachSchema new SimpleSchema
category:
label: "Category"
type: String
project:
label: "Project ID"
type: String
color:
label: "Category Color"
type: String
rank:
label: "Rank"
type: Number
decimal: true
@Books = new Meteor.Collection('books')
@Books.attachSchema new SimpleSchema
name:
label: "Book Name"
type: String
url:
label: "Book URL"
type: String
optional: true
bookshelfId:
label: "Bookshelf ID"
type: String
rank:
label: "Book Rank"
type: Number
decimal: true
fileRegistryId:
label: "File Registry ID"
type: String
optional: true
@EventStream = new Meteor.Collection 'eventStream'
@EventStream.attachSchema new SimpleSchema
projectId:
label: "Project Id"
type: String
userId:
label: "User ID"
type: String
timestamp:
label: "Timestamp"
type: new Date()
autoValue: -> new Date()
type:
# TODO: Figure out what these are actually going to be
# Potential information to want to store: chat messages, document creation, save revision, user added to project, manifest added?
allowedValues: [ 'deskSnapshots', 'filecabinet', 'annotations', 'availablemanifests', 'chat', 'project' ]
type: String
label: "Event Type"
message:
type: String
label: "Message"
optional: true
otherId:
# FileCabinet ID, Bookshelf ID, Manifest ID, etc.
type: String
label: "Other ID"
optional: true
@Messages = new Mongo.Collection 'messages'
@Messages.attachSchema new SimpleSchema
subject:
label: "Subject"
type: String
roomId:
label: "Room/Project Id"
type: String
startedBy:
label: "Thread Started By"
type: String
timestamp:
type: new Date()
posts:
label: "Posts"
type: [ Object ]
optional: true
'posts.$.user':
label: "Post Author"
type: String
'posts.$.message':
label: "Post"
type: String
'posts.$.timestamp':
label: "Post Timestamp"
type: new Date()
@RequestedAccounts = new Mongo.Collection 'requestedAccounts'
@RequestedAccounts.attachSchema new SimpleSchema
email:
unique: true
label: "Email"
type: String
firstName:
label: "PI:NAME:<NAME>END_PI"
type: String
lastName:
label: "PI:NAME:<NAME>END_PI"
type: String
institution:
label: "Institutional Affiliation"
type: String
optional: true
research:
label: "Area of Research"
type: String
newProjectRequest:
label: "New Project Request Information"
type: String
optional: true
existingProjectRequest:
label: "Existing Project Request Information"
type: String
optional: true
denied:
type: Boolean
defaultValue: false
approved:
type: Boolean
defaultValue: false
created:
type: Boolean
defaultValue: false
|
[
{
"context": "gger'\n\n\nclient = redis.createClient()\n\nbaseKey = 'bbb:recordings:'\n\nwatch = ->\n #clear the keys first\n keys = clie",
"end": 204,
"score": 0.8938528895378113,
"start": 188,
"tag": "KEY",
"value": "bbb:recordings:'"
},
{
"context": " timestamp = pathArray[1]\n... | labs/api/recordings/lib/recording-dir-watcher.coffee | thong-hoczita/bigbluebutton | 0 | ##
## Watches the recording dirs for new recordings
##
chokidar = require 'chokidar'
redis = require 'redis'
log = require './logger'
client = redis.createClient()
baseKey = 'bbb:recordings:'
watch = ->
#clear the keys first
keys = client.keys(baseKey.concat('*'))
client.del(keys)
#start watching
chokidar.watch('/var/bigbluebutton/published', {ignored: /[\/\\]\./}).on 'all', (event, path) ->
somethingChanged(event,path)
chokidar.watch('/var/bigbluebutton/unpublished', {ignored: /[\/\\]\./}).on 'all', (event, path) ->
somethingChanged(event,path)
somethingChanged = (event, path) ->
uri = path.split('/')
if uri[5]? #excludes the parent directories being added
pathArray = path.substring(path.lastIndexOf('/')+1).split('-')
meetingID = pathArray[0]
timestamp = pathArray[1]
thisKey = baseKey.concat(meetingID)
json = {
"format": uri[4]
"timestamp": timestamp
}
log.info(event, path)
str = JSON.stringify(json)
client.sadd(thisKey, str)
getRecordingsArray = (meetingID, callback) ->
thisKey = baseKey.concat(meetingID)
client.smembers thisKey, (err, members) ->
if err
console.log "Error: #{err}"
else
callback members
exports.watch = watch
exports.getRecordingsArray = getRecordingsArray | 15508 | ##
## Watches the recording dirs for new recordings
##
chokidar = require 'chokidar'
redis = require 'redis'
log = require './logger'
client = redis.createClient()
baseKey = '<KEY>
watch = ->
#clear the keys first
keys = client.keys(baseKey.concat('*'))
client.del(keys)
#start watching
chokidar.watch('/var/bigbluebutton/published', {ignored: /[\/\\]\./}).on 'all', (event, path) ->
somethingChanged(event,path)
chokidar.watch('/var/bigbluebutton/unpublished', {ignored: /[\/\\]\./}).on 'all', (event, path) ->
somethingChanged(event,path)
somethingChanged = (event, path) ->
uri = path.split('/')
if uri[5]? #excludes the parent directories being added
pathArray = path.substring(path.lastIndexOf('/')+1).split('-')
meetingID = pathArray[0]
timestamp = pathArray[1]
thisKey = baseKey.<KEY>(meetingID)
json = {
"format": uri[4]
"timestamp": timestamp
}
log.info(event, path)
str = JSON.stringify(json)
client.sadd(thisKey, str)
getRecordingsArray = (meetingID, callback) ->
thisKey = baseKey.concat(meetingID)
client.smembers thisKey, (err, members) ->
if err
console.log "Error: #{err}"
else
callback members
exports.watch = watch
exports.getRecordingsArray = getRecordingsArray | true | ##
## Watches the recording dirs for new recordings
##
chokidar = require 'chokidar'
redis = require 'redis'
log = require './logger'
client = redis.createClient()
baseKey = 'PI:KEY:<KEY>END_PI
watch = ->
#clear the keys first
keys = client.keys(baseKey.concat('*'))
client.del(keys)
#start watching
chokidar.watch('/var/bigbluebutton/published', {ignored: /[\/\\]\./}).on 'all', (event, path) ->
somethingChanged(event,path)
chokidar.watch('/var/bigbluebutton/unpublished', {ignored: /[\/\\]\./}).on 'all', (event, path) ->
somethingChanged(event,path)
somethingChanged = (event, path) ->
uri = path.split('/')
if uri[5]? #excludes the parent directories being added
pathArray = path.substring(path.lastIndexOf('/')+1).split('-')
meetingID = pathArray[0]
timestamp = pathArray[1]
thisKey = baseKey.PI:KEY:<KEY>END_PI(meetingID)
json = {
"format": uri[4]
"timestamp": timestamp
}
log.info(event, path)
str = JSON.stringify(json)
client.sadd(thisKey, str)
getRecordingsArray = (meetingID, callback) ->
thisKey = baseKey.concat(meetingID)
client.smembers thisKey, (err, members) ->
if err
console.log "Error: #{err}"
else
callback members
exports.watch = watch
exports.getRecordingsArray = getRecordingsArray |
[
{
"context": " is 10\nok b is 20\nok c is 30\n\nperson = {\n name: \"Moe\"\n family: {\n 'elder-brother': {\n address",
"end": 700,
"score": 0.9997746348381042,
"start": 697,
"tag": "NAME",
"value": "Moe"
},
{
"context": "addresses: [one, {city: b}]}}} = person\n\nok a is \... | node_modules/.npm/.cache/express/1.0.1/package/support/connect/support/coffee-script/test/test_pattern_matching.coffee | financeCoding/wtfjs | 1 | # Simple variable swapping.
a = -1
b = -2
[a, b] = [b, a]
ok a is -2
ok b is -1
func = ->
[a, b] = [b, a]
ok func().join(' ') is '-1 -2'
noop = ->
noop [a,b] = [c,d] = [1,2]
ok a is 1 and b is 2
# Array destructuring, including splats.
arr = [1, 2, 3]
[a, b, c] = arr
ok a is 1
ok b is 2
ok c is 3
[x,y...,z] = [1,2,3,4,5]
ok x is 1
ok y.length is 3
ok z is 5
[x, [y, mids..., last], z..., end] = [1, [10, 20, 30, 40], 2,3,4, 5]
ok x is 1
ok y is 10
ok mids.length is 2 and mids[1] is 30
ok last is 40
ok z.length is 3 and z[2] is 4
ok end is 5
# Object destructuring.
obj = {x: 10, y: 20, z: 30}
{x: a, y: b, z: c} = obj
ok a is 10
ok b is 20
ok c is 30
person = {
name: "Moe"
family: {
'elder-brother': {
addresses: [
"first"
{
street: "101 Deercreek Ln."
city: "Moquasset NY, 10021"
}
]
}
}
}
{name: a, family: {'elder-brother': {addresses: [one, {city: b}]}}} = person
ok a is "Moe"
ok b is "Moquasset NY, 10021"
test = {
person: {
address: [
"------"
"Street 101"
"Apt 101"
"City 101"
]
}
}
{person: {address: [ignore, addr...]}} = test
ok addr.join(', ') is "Street 101, Apt 101, City 101"
# Pattern matching against an expression.
[a, b] = if true then [2, 1] else [1, 2]
ok a is 2
ok b is 1
# Pattern matching with object shorthand.
person = {
name: "Bob"
age: 26
dogs: ["Prince", "Bowie"]
}
{name, age, dogs: [first, second]} = person
ok name is "Bob"
ok age is 26
ok first is "Prince"
ok second is "Bowie"
# Pattern matching within for..loops
persons = {
George: { name: "Bob" },
Bob: { name: "Alice" }
Christopher: { name: "Stan" }
}
join1 = "#{key}: #{name}" for key, { name } of persons
deepEqual join1, ["George: Bob", "Bob: Alice", "Christopher: Stan"]
persons = [
{ name: "Bob", parent: { name: "George" } },
{ name: "Alice", parent: { name: "Bob" } },
{ name: "Stan", parent: { name: "Christopher" } }
]
join2 = "#{parent}: #{name}" for { name, parent: { name: parent } } in persons
deepEqual join1, join2
persons = [['Bob', ['George']], ['Alice', ['Bob']], ['Stan', ['Christopher']]]
join3 = "#{parent}: #{name}" for [name, [parent]] in persons
deepEqual join2, join3
| 151429 | # Simple variable swapping.
a = -1
b = -2
[a, b] = [b, a]
ok a is -2
ok b is -1
func = ->
[a, b] = [b, a]
ok func().join(' ') is '-1 -2'
noop = ->
noop [a,b] = [c,d] = [1,2]
ok a is 1 and b is 2
# Array destructuring, including splats.
arr = [1, 2, 3]
[a, b, c] = arr
ok a is 1
ok b is 2
ok c is 3
[x,y...,z] = [1,2,3,4,5]
ok x is 1
ok y.length is 3
ok z is 5
[x, [y, mids..., last], z..., end] = [1, [10, 20, 30, 40], 2,3,4, 5]
ok x is 1
ok y is 10
ok mids.length is 2 and mids[1] is 30
ok last is 40
ok z.length is 3 and z[2] is 4
ok end is 5
# Object destructuring.
obj = {x: 10, y: 20, z: 30}
{x: a, y: b, z: c} = obj
ok a is 10
ok b is 20
ok c is 30
person = {
name: "<NAME>"
family: {
'elder-brother': {
addresses: [
"first"
{
street: "101 Deercreek Ln."
city: "Moquasset NY, 10021"
}
]
}
}
}
{name: a, family: {'elder-brother': {addresses: [one, {city: b}]}}} = person
ok a is "<NAME>"
ok b is "Moquasset NY, 10021"
test = {
person: {
address: [
"------"
"Street 101"
"Apt 101"
"City 101"
]
}
}
{person: {address: [ignore, addr...]}} = test
ok addr.join(', ') is "Street 101, Apt 101, City 101"
# Pattern matching against an expression.
[a, b] = if true then [2, 1] else [1, 2]
ok a is 2
ok b is 1
# Pattern matching with object shorthand.
person = {
name: "<NAME>"
age: 26
dogs: ["<NAME>", "<NAME>"]
}
{name, age, dogs: [first, second]} = person
ok name is "<NAME>"
ok age is 26
ok first is "<NAME>"
ok second is "<NAME>"
# Pattern matching within for..loops
persons = {
<NAME>: { name: "<NAME>" },
<NAME>: { name: "<NAME>" }
<NAME>: { name: "<NAME>" }
}
join1 = "#{key}: #{name}" for key, { name } of persons
deepEqual join1, ["<NAME>: <NAME>", "<NAME>: <NAME>", "<NAME>: <NAME>"]
persons = [
{ name: "<NAME>", parent: { name: "<NAME>" } },
{ name: "<NAME>", parent: { name: "<NAME>" } },
{ name: "<NAME>", parent: { name: "<NAME>" } }
]
join2 = "#{parent}: #{name}" for { name, parent: { name: parent } } in persons
deepEqual join1, join2
persons = [['<NAME>', ['<NAME>']], ['<NAME>', ['<NAME>']], ['<NAME>', ['<NAME>']]]
join3 = "#{parent}: #{name}" for [name, [parent]] in persons
deepEqual join2, join3
| true | # Simple variable swapping.
a = -1
b = -2
[a, b] = [b, a]
ok a is -2
ok b is -1
func = ->
[a, b] = [b, a]
ok func().join(' ') is '-1 -2'
noop = ->
noop [a,b] = [c,d] = [1,2]
ok a is 1 and b is 2
# Array destructuring, including splats.
arr = [1, 2, 3]
[a, b, c] = arr
ok a is 1
ok b is 2
ok c is 3
[x,y...,z] = [1,2,3,4,5]
ok x is 1
ok y.length is 3
ok z is 5
[x, [y, mids..., last], z..., end] = [1, [10, 20, 30, 40], 2,3,4, 5]
ok x is 1
ok y is 10
ok mids.length is 2 and mids[1] is 30
ok last is 40
ok z.length is 3 and z[2] is 4
ok end is 5
# Object destructuring.
obj = {x: 10, y: 20, z: 30}
{x: a, y: b, z: c} = obj
ok a is 10
ok b is 20
ok c is 30
person = {
name: "PI:NAME:<NAME>END_PI"
family: {
'elder-brother': {
addresses: [
"first"
{
street: "101 Deercreek Ln."
city: "Moquasset NY, 10021"
}
]
}
}
}
{name: a, family: {'elder-brother': {addresses: [one, {city: b}]}}} = person
ok a is "PI:NAME:<NAME>END_PI"
ok b is "Moquasset NY, 10021"
test = {
person: {
address: [
"------"
"Street 101"
"Apt 101"
"City 101"
]
}
}
{person: {address: [ignore, addr...]}} = test
ok addr.join(', ') is "Street 101, Apt 101, City 101"
# Pattern matching against an expression.
[a, b] = if true then [2, 1] else [1, 2]
ok a is 2
ok b is 1
# Pattern matching with object shorthand.
person = {
name: "PI:NAME:<NAME>END_PI"
age: 26
dogs: ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"]
}
{name, age, dogs: [first, second]} = person
ok name is "PI:NAME:<NAME>END_PI"
ok age is 26
ok first is "PI:NAME:<NAME>END_PI"
ok second is "PI:NAME:<NAME>END_PI"
# Pattern matching within for..loops
persons = {
PI:NAME:<NAME>END_PI: { name: "PI:NAME:<NAME>END_PI" },
PI:NAME:<NAME>END_PI: { name: "PI:NAME:<NAME>END_PI" }
PI:NAME:<NAME>END_PI: { name: "PI:NAME:<NAME>END_PI" }
}
join1 = "#{key}: #{name}" for key, { name } of persons
deepEqual join1, ["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"]
persons = [
{ name: "PI:NAME:<NAME>END_PI", parent: { name: "PI:NAME:<NAME>END_PI" } },
{ name: "PI:NAME:<NAME>END_PI", parent: { name: "PI:NAME:<NAME>END_PI" } },
{ name: "PI:NAME:<NAME>END_PI", parent: { name: "PI:NAME:<NAME>END_PI" } }
]
join2 = "#{parent}: #{name}" for { name, parent: { name: parent } } in persons
deepEqual join1, join2
persons = [['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']]]
join3 = "#{parent}: #{name}" for [name, [parent]] in persons
deepEqual join2, join3
|
[
{
"context": "te()\n @tom = Mozart.MztObject.create({name: 'tom'})\n @john = Mozart.MztObject.create({name: '",
"end": 6067,
"score": 0.9872379302978516,
"start": 6064,
"tag": "NAME",
"value": "tom"
},
{
"context": "'})\n @john = Mozart.MztObject.create({name: 'john'})... | src/spec/object-spec.coffee | creativeprogramming/mozart | 1 | Test = window.Test = @Test = {}
Spec = window.Spec = @Spec = {}
describe 'Mozart.MztObject', ->
describe 'Mixins', ->
Mozart.TestMixin =
test: -> 'Mozart.TestMixin.text'
class TestModule1 extends Mozart.MztObject
@extend Mozart.TestMixin
class TestModule2 extends Mozart.MztObject
@include Mozart.TestMixin
it 'should allow call on mixin on instance when extended', ->
t = TestModule1.create()
expect(t.test()).toEqual('Mozart.TestMixin.text')
expect(TestModule1.test).not.toBeDefined()
it 'should allow call on mixin on instance when included', ->
t = TestModule2.create()
expect(t.test).not.toBeDefined()
expect(TestModule2.test()).toEqual('Mozart.TestMixin.text')
describe 'Events', ->
beforeEach ->
class Test.EventTestClass extends Mozart.MztObject
@t = Test.EventTestClass.create()
@testproc =
testcallback1: (data) ->
expect(data.prop1).toEqual('propone')
testcallback2: (data) ->
expect(data.prop2).toEqual('proptwo')
testcallback1_1: (data) ->
expect(data.prop2).toEqual('proptwo')
spyOn(@testproc,'testcallback1')
spyOn(@testproc,'testcallback2')
spyOn(@testproc,'testcallback1_1')
it 'should subscribe and publish an event', ->
@t.subscribe 'testeventone' , @testproc.testcallback1
@t.publish 'testeventone', { prop1: 'propone' }
expect(@testproc.testcallback1).toHaveBeenCalled()
expect(@testproc.testcallback2).not.toHaveBeenCalled()
it 'should subscribe and publish multiple events', ->
@t.subscribe 'testeventone' , @testproc.testcallback1
@t.subscribe 'testeventtwo' , @testproc.testcallback2
@t.publish 'testeventone', { prop1: 'propone' }
expect(@testproc.testcallback1).toHaveBeenCalled()
@t.publish 'testeventtwo', { prop2: 'proptwo' }
expect(@testproc.testcallback2).toHaveBeenCalled()
it 'should subscribe and publish multiple callbacks on one event', ->
@t.subscribe 'testeventone' , @testproc.testcallback1
@t.subscribe 'testeventone' , @testproc.testcallback1_1
@t.publish 'testeventone', { prop1: 'propone' }
expect(@testproc.testcallback1).toHaveBeenCalled()
expect(@testproc.testcallback1_1).toHaveBeenCalled()
it 'should unsubscribe from a single event and callback', ->
@t.subscribe 'testeventone' , @testproc.testcallback1
@t.subscribe 'testeventone' , @testproc.testcallback1_1
@t.unsubscribe 'testeventone', @testproc.testcallback1_1
@t.publish 'testeventone', { prop1: 'propone' }
expect(@testproc.testcallback1).toHaveBeenCalled()
expect(@testproc.testcallback1_1).not.toHaveBeenCalled()
it 'should unsubscribe all callbacks from a single event', ->
@t.subscribe 'testeventone' , @testproc.testcallback1
@t.subscribe 'testeventone' , @testproc.testcallback1_1
@t.subscribe 'testeventtwo' , @testproc.testcallback2
@t.unsubscribe 'testeventone'
@t.publish 'testeventone', { prop1: 'propone' }
@t.publish 'testeventtwo', { prop2: 'proptwo' }
expect(@testproc.testcallback1).not.toHaveBeenCalled()
expect(@testproc.testcallback1_1).not.toHaveBeenCalled()
expect(@testproc.testcallback2).toHaveBeenCalled()
it 'should unsubscribe all callbacks', ->
@t.subscribe 'testeventone' , @testproc.testcallback1
@t.subscribe 'testeventone' , @testproc.testcallback1_1
@t.subscribe 'testeventtwo' , @testproc.testcallback2
@t.unsubscribe()
@t.publish 'testeventone', { prop1: 'propone' }
@t.publish 'testeventtwo', { prop2: 'proptwo' }
expect(@testproc.testcallback1).not.toHaveBeenCalled()
expect(@testproc.testcallback1_1).not.toHaveBeenCalled()
expect(@testproc.testcallback2).not.toHaveBeenCalled()
it 'should subscribe and publish a once event, and not publish it twice', ->
@t.subscribeOnce 'testeventone' , @testproc.testcallback1
@t.publish 'testeventone', { prop1: 'propone' }
expect(@testproc.testcallback1).toHaveBeenCalled()
@testproc.testcallback1.reset()
@t.publish 'testeventone', { prop1: 'propone' }
expect(@testproc.testcallback1).not.toHaveBeenCalled()
describe "Getters and Setters", ->
beforeEach ->
@obj = Mozart.MztObject.create
coffee: 'black'
whiskey: null
tea: -> 'english'
it 'should be able to get an attribute', ->
expect(@obj.get('coffee')).toEqual('black')
it 'should get undefined for a property that doesn\'t exist', ->
expect(@obj.get('milo')).toEqual(undefined)
it 'should get null for a property that exists with no value', ->
expect(@obj.get('whiskey')).toEqual(null)
it 'should be able to get an function with a value', ->
expect(@obj.get('tea')).toEqual('english')
it 'should be able to set an attribute', ->
@obj.set('coffee', 'flat-white')
expect(@obj.coffee).toEqual('flat-white')
it 'should be error if attempting to set an function', ->
test = -> @obj.set('coffee', 'flat-white')
expect(test).toThrow()
describe "Lookup Properties", ->
beforeEach ->
Mozart.root = @
@Spec = {}
it 'should correctly get lookup properties', ->
@Spec.one = "one1"
x = Mozart.MztObject.create
valueLookup: 'Spec.one'
expect(x.value).toEqual("one1")
it 'should correctly get lookup properties with null values', ->
@Spec.one = null
x = Mozart.MztObject.create
valueLookup: 'Spec.one'
expect(x.value).toBeNull()
it 'should set undefined on get lookup property with bad path', ->
delete @Spec["one"]
x = Mozart.MztObject.create
valueLookup: 'Spec.one'
expect(x.value).not.toBeDefined()
describe "Bindings", ->
beforeEach ->
Mozart.root = window
Spec.personController = Mozart.MztObject.create()
@tom = Mozart.MztObject.create({name: 'tom'})
@john = Mozart.MztObject.create({name: 'john'})
it "should set up binding stuff", ->
expect(@tom._bindings.notify).toBeDefined()
expect(@tom._bindings.notify).toEqual({})
describe "Notify Bindings", ->
it "should add the binding to the internal map when transferable", ->
@view = Mozart.MztObject.create
personNotifyBinding: 'Spec.personController.subject'
expect(_.keys(@view._bindings.notify).length).toEqual(1)
expect(@view._bindings.notify.person).toBeDefined()
expect(@view._bindings.notify.subject).toBeUndefined()
expect(@view._bindings.notify.person.length).toEqual(1)
expect(@view._bindings.notify.person[0]).toEqual({attr:'subject', target: Spec.personController, transferable: true})
expect(_.keys(Spec.personController._bindings.observe).length).toEqual(1)
expect(Spec.personController._bindings.observe.subject).toBeDefined()
expect(Spec.personController._bindings.observe.person).toBeUndefined()
expect(Spec.personController._bindings.observe.subject.length).toEqual(1)
expect(Spec.personController._bindings.observe.subject[0]).toEqual({attr:'person', target: @view, transferable: true})
it "should add the binding to the internal map when non-transferable", ->
@cheston = Mozart.MztObject.create
name: 'Cheston'
@view = Mozart.MztObject.create
subject: @cheston
personNotifyBinding: 'subject.name'
expect(_.keys(@view._bindings.notify).length).toEqual(1)
expect(@view._bindings.notify.person).toBeDefined()
expect(@view._bindings.notify.subject).toBeUndefined()
expect(@view._bindings.notify.person.length).toEqual(1)
expect(@view._bindings.notify.person[0]).toEqual({attr:'name', target: @cheston, transferable: false})
expect(_.keys(@cheston._bindings.observe).length).toEqual(1)
expect(@cheston._bindings.observe.name).toBeDefined()
expect(@cheston._bindings.observe.person).toBeUndefined()
expect(@cheston._bindings.observe.name.length).toEqual(1)
expect(@cheston._bindings.observe.name[0]).toEqual({attr:'person', target: @view, transferable: false})
it "should change target on set", ->
@view = Mozart.MztObject.create
personNotifyBinding: 'Spec.personController.subject'
@view.set 'person', @tom
expect(Spec.personController.subject).toEqual(@tom)
@view.set 'person', @john
expect(Spec.personController.subject).toEqual(@john)
@view.set 'person', null
expect(Spec.personController.subject).toBeNull()
it "should set initial value", ->
@view = Mozart.MztObject.create
person: @tom
personNotifyBinding: 'Spec.personController.subject'
expect(Spec.personController.subject).toEqual(@tom)
it 'should allow multiple objects to notify one object', ->
@view1 = Mozart.MztObject.create
personNotifyBinding: 'Spec.personController.subject'
@view2 = Mozart.MztObject.create
personNotifyBinding: 'Spec.personController.subject'
expect(Spec.personController.subject).toBeUndefined()
@view1.set('person', @tom)
expect(Spec.personController.subject).toEqual(@tom)
@view2.set('person', @john)
expect(Spec.personController.subject).toEqual(@john)
it 'should allow bindings to be removed', ->
@view = Mozart.MztObject.create
personNotifyBinding: 'Spec.personController.subject'
@view.set 'person', @tom
expect(Spec.personController.subject).toEqual(@tom)
@view._removeBinding('person', Spec.personController, 'subject', Mozart.MztObject.NOTIFY)
@view.set 'person', @john
expect(Spec.personController.subject).toEqual(@tom)
@view.set 'person', null
expect(Spec.personController.subject).toEqual(@tom)
describe "Observe Bindings", ->
it 'should add the binding to the internal map of the target when transferable', ->
@view = Mozart.MztObject.create
personObserveBinding: 'Spec.personController.subject'
expect(_.keys(Spec.personController._bindings.notify).length).toEqual(1)
expect(Spec.personController._bindings.notify.subject).toBeDefined()
expect(Spec.personController._bindings.notify.person).toBeUndefined()
expect(Spec.personController._bindings.notify.subject.length).toEqual(1)
expect(Spec.personController._bindings.notify.subject[0]).toEqual({attr:'person', target: @view, transferable: true})
expect(_.keys(@view._bindings.observe).length).toEqual(1)
expect(@view._bindings.observe.person).toBeDefined()
expect(@view._bindings.observe.subject).toBeUndefined()
expect(@view._bindings.observe.person.length).toEqual(1)
expect(@view._bindings.observe.person[0]).toEqual({attr:'subject', target: Spec.personController, transferable: true})
it 'should add the binding to the internal map of the target when non-transferable', ->
@john = Mozart.MztObject.create
subject: "John"
@view = Mozart.MztObject.create
parent: @john
personObserveBinding: 'parent.subject'
expect(_.keys(@john._bindings.notify).length).toEqual(1)
expect(@john._bindings.notify.subject).toBeDefined()
expect(@john._bindings.notify.person).toBeUndefined()
expect(@john._bindings.notify.subject.length).toEqual(1)
expect(@john._bindings.notify.subject[0]).toEqual({attr:'person', target: @view, transferable: false})
expect(_.keys(@view._bindings.observe).length).toEqual(1)
expect(@view._bindings.observe.person).toBeDefined()
expect(@view._bindings.observe.subject).toBeUndefined()
expect(@view._bindings.observe.person.length).toEqual(1)
expect(@view._bindings.observe.person[0]).toEqual({attr:'subject', target: @john, transferable: false})
it "should change target on set", ->
@view = Mozart.MztObject.create
personObserveBinding: 'Spec.personController.subject'
Spec.personController.set 'subject', @tom
expect(@view.person).toEqual(@tom)
Spec.personController.set 'subject', @john
expect(@view.person).toEqual(@john)
Spec.personController.set 'subject', null
expect(@view.person).toBeNull()
it "should set initial value", ->
Spec.personController.set 'subject', @tom
@view = Mozart.MztObject.create
personObserveBinding: 'Spec.personController.subject'
expect(@view.person).toEqual(@tom)
it "should allow multiple objects to observe one object", ->
Spec.personController.set 'subject', @tom
@view1 = Mozart.MztObject.create
personObserveBinding: 'Spec.personController.subject'
@view2 = Mozart.MztObject.create
personObserveBinding: 'Spec.personController.subject'
expect(@view1.person).toEqual(@tom)
expect(@view2.person).toEqual(@tom)
Spec.personController.set 'subject', @john
expect(@view1.person).toEqual(@john)
expect(@view2.person).toEqual(@john)
it "should allow bindings to be removed", ->
@view = Mozart.MztObject.create
personObserveBinding: 'Spec.personController.subject'
Spec.personController.set 'subject', @tom
expect(@view.person).toEqual(@tom)
@view._removeBinding('person', Spec.personController, 'subject', Mozart.MztObject.OBSERVE)
Spec.personController.set 'subject', @john
expect(@view.person).toEqual(@tom)
Spec.personController.set 'subject', null
expect(@view.person).toEqual(@tom)
describe "Sync Bindings", ->
it 'should add the binding to the internal map of both the target and the target', ->
@view = Mozart.MztObject.create
personBinding: 'Spec.personController.subject'
expect(_.keys(@view._bindings.notify).length).toEqual(1)
expect(@view._bindings.notify.person).toBeDefined()
expect(@view._bindings.notify.subject).toBeUndefined()
expect(@view._bindings.notify.person[0]).toEqual({attr:'subject', target: Spec.personController, transferable: true})
expect(_.keys(Spec.personController._bindings.notify).length).toEqual(1)
expect(Spec.personController._bindings.notify.subject).toBeDefined()
expect(Spec.personController._bindings.notify.person).toBeUndefined()
expect(Spec.personController._bindings.notify.subject[0]).toEqual({attr:'person', target: @view, transferable: true})
it "should change target on set in both directions", ->
@view = Mozart.MztObject.create
personBinding: 'Spec.personController.subject'
Spec.personController.set 'subject', @tom
expect(@view.person).toEqual(@tom)
Spec.personController.set 'subject', @john
expect(@view.person).toEqual(@john)
Spec.personController.set 'subject', null
expect(@view.person).toBeNull()
@view.set 'person', @tom
expect(Spec.personController.subject).toEqual(@tom)
@view.set 'person', @john
expect(Spec.personController.subject).toEqual(@john)
@view.set 'person', null
expect(Spec.personController.subject).toBeNull()
it "should allow a binding to be removed", ->
@view = Mozart.MztObject.create
personBinding: 'Spec.personController.subject'
Spec.personController.set 'subject', @tom
expect(@view.person).toEqual(@tom)
@view.set 'person', @john
expect(Spec.personController.subject).toEqual(@john)
@view._removeBinding('person', Spec.personController, 'subject', Mozart.MztObject.SYNC)
Spec.personController.set 'subject', @tom
expect(@view.person).toEqual(@john)
@view.set 'person', null
expect(Spec.personController.subject).toEqual(@tom)
Spec.personController.set 'subject', @tom
expect(@view.person).toEqual(null)
@view.set 'person', @john
expect(Spec.personController.subject).toEqual(@tom)
describe "Relative Bindings", ->
it "should allow bindings on relative object paths", ->
@view1 = Mozart.MztObject.create
name: "TC"
@view2 = Mozart.MztObject.create
parent: @view1
parentNameBinding: "parent.name"
expect(@view2.parentName).toEqual("TC")
@view1.set("name","DOC")
expect(@view2.parentName).toEqual("DOC")
@view2.set("parentName","PZ")
expect(@view1.name).toEqual("PZ")
describe "Bindings on targets that change", ->
it 'should write to the correct object after a change', ->
Spec.personController.set 'subject', Mozart.MztObject.create({name:'Test'})
@view = Mozart.MztObject.create
subjectNameObserveBinding: 'Spec.personController.subject.name'
Spec.personController.set 'subject', @tom
expect(@view.subjectName).toEqual(@tom.name)
Spec.personController.set 'subject', @john
expect(@view.subjectName).toEqual(@john.name)
it 'should preserve bindings when a bound property is set to null then back', ->
Spec.personController.set 'subject', Mozart.MztObject.create({name:'Test'})
@view = Mozart.MztObject.create
subjectNameObserveBinding: 'Spec.personController.subject.name'
Spec.personController.set 'subject', @tom
expect(@view.subjectName).toEqual(@tom.name)
Spec.personController.set 'subject', null
expect(@view.subjectName).toEqual(null)
Spec.personController.set 'subject', @john
expect(@view.subjectName).toEqual(@john.name)
describe "Bindings and circular references", ->
it 'should handle circular references without an infinite loop', ->
a = Mozart.MztObject.create()
b = Mozart.MztObject.create()
c = Mozart.MztObject.create()
a._createBinding('test', b, 'test', Mozart.MztObject.SYNC, false)
b._createBinding('test', c, 'test', Mozart.MztObject.SYNC, false)
c._createBinding('test', a, 'test', Mozart.MztObject.SYNC, false)
a.set('test', 'one')
expect(b.test).toEqual('one')
expect(c.test).toEqual('one')
b.set('test', 'two')
expect(a.test).toEqual('two')
expect(c.test).toEqual('two')
c.set('test', 'three')
expect(b.test).toEqual('three')
expect(a.test).toEqual('three')
describe "Binding chaining", ->
it 'should not pollute objects when transfering bindings', ->
a = Mozart.MztObject.create({id:1})
b = Mozart.MztObject.create({id:2})
c = Mozart.MztObject.create({id:3})
Test.controller = Mozart.MztObject.create()
Mozart.root = window
e = Mozart.MztObject.create(
activeObserveBinding: "Test.controller.content"
)
Test.controller.set('content',a)
expect(Test.controller.content.id).toEqual(1)
expect(e.active.id).toEqual(1)
Test.controller.set('content',b)
expect(Test.controller.content.id).toEqual(2)
expect(e.active.id).toEqual(2)
Test.controller.set('content',c)
expect(Test.controller.content.id).toEqual(3)
expect(e.active.id).toEqual(3)
it "should not transfer non-transferable bindings", ->
Mozart.root = window
@objA = Mozart.MztObject.create
name: 'Cheston'
@objA2 = Mozart.MztObject.create
parent:@objA
parentNameObserveBinding: 'parent.name'
@objB = Mozart.MztObject.create
name: 'Ginger'
@objB2 = Mozart.MztObject.create
parent:@objB
parentNameObserveBinding: 'parent.name'
Test.controller = Mozart.MztObject.create
subject: @objA
@observer = Mozart.MztObject.create
subjectNameObserveBinding: 'Test.controller.subject.name'
expect(@observer.subjectName).toEqual('Cheston')
expect(@objA2.parentName).toEqual('Cheston')
expect(@objB2.parentName).toEqual('Ginger')
Test.controller.set('subject', @objB)
expect(@observer.subjectName).toEqual('Ginger')
expect(@objA2.parentName).toEqual('Cheston')
expect(@objB2.parentName).toEqual('Ginger')
describe "Binding removal", ->
it "should remove the correct binding when an object is released", ->
Mozart.root = window
Test.controller = Mozart.MztObject.create
subject: 'one'
y = Mozart.MztObject.create
testObserveBinding: 'Test.controller.subject'
z = Mozart.MztObject.create
testObserveBinding: 'Test.controller.subject'
Test.controller.set('subject', 'two')
expect(y.test).toEqual('two')
expect(z.test).toEqual('two')
y.release()
Test.controller.set('subject', 'three')
expect(z.test).toEqual('three')
| 37348 | Test = window.Test = @Test = {}
Spec = window.Spec = @Spec = {}
describe 'Mozart.MztObject', ->
describe 'Mixins', ->
Mozart.TestMixin =
test: -> 'Mozart.TestMixin.text'
class TestModule1 extends Mozart.MztObject
@extend Mozart.TestMixin
class TestModule2 extends Mozart.MztObject
@include Mozart.TestMixin
it 'should allow call on mixin on instance when extended', ->
t = TestModule1.create()
expect(t.test()).toEqual('Mozart.TestMixin.text')
expect(TestModule1.test).not.toBeDefined()
it 'should allow call on mixin on instance when included', ->
t = TestModule2.create()
expect(t.test).not.toBeDefined()
expect(TestModule2.test()).toEqual('Mozart.TestMixin.text')
describe 'Events', ->
beforeEach ->
class Test.EventTestClass extends Mozart.MztObject
@t = Test.EventTestClass.create()
@testproc =
testcallback1: (data) ->
expect(data.prop1).toEqual('propone')
testcallback2: (data) ->
expect(data.prop2).toEqual('proptwo')
testcallback1_1: (data) ->
expect(data.prop2).toEqual('proptwo')
spyOn(@testproc,'testcallback1')
spyOn(@testproc,'testcallback2')
spyOn(@testproc,'testcallback1_1')
it 'should subscribe and publish an event', ->
@t.subscribe 'testeventone' , @testproc.testcallback1
@t.publish 'testeventone', { prop1: 'propone' }
expect(@testproc.testcallback1).toHaveBeenCalled()
expect(@testproc.testcallback2).not.toHaveBeenCalled()
it 'should subscribe and publish multiple events', ->
@t.subscribe 'testeventone' , @testproc.testcallback1
@t.subscribe 'testeventtwo' , @testproc.testcallback2
@t.publish 'testeventone', { prop1: 'propone' }
expect(@testproc.testcallback1).toHaveBeenCalled()
@t.publish 'testeventtwo', { prop2: 'proptwo' }
expect(@testproc.testcallback2).toHaveBeenCalled()
it 'should subscribe and publish multiple callbacks on one event', ->
@t.subscribe 'testeventone' , @testproc.testcallback1
@t.subscribe 'testeventone' , @testproc.testcallback1_1
@t.publish 'testeventone', { prop1: 'propone' }
expect(@testproc.testcallback1).toHaveBeenCalled()
expect(@testproc.testcallback1_1).toHaveBeenCalled()
it 'should unsubscribe from a single event and callback', ->
@t.subscribe 'testeventone' , @testproc.testcallback1
@t.subscribe 'testeventone' , @testproc.testcallback1_1
@t.unsubscribe 'testeventone', @testproc.testcallback1_1
@t.publish 'testeventone', { prop1: 'propone' }
expect(@testproc.testcallback1).toHaveBeenCalled()
expect(@testproc.testcallback1_1).not.toHaveBeenCalled()
it 'should unsubscribe all callbacks from a single event', ->
@t.subscribe 'testeventone' , @testproc.testcallback1
@t.subscribe 'testeventone' , @testproc.testcallback1_1
@t.subscribe 'testeventtwo' , @testproc.testcallback2
@t.unsubscribe 'testeventone'
@t.publish 'testeventone', { prop1: 'propone' }
@t.publish 'testeventtwo', { prop2: 'proptwo' }
expect(@testproc.testcallback1).not.toHaveBeenCalled()
expect(@testproc.testcallback1_1).not.toHaveBeenCalled()
expect(@testproc.testcallback2).toHaveBeenCalled()
it 'should unsubscribe all callbacks', ->
@t.subscribe 'testeventone' , @testproc.testcallback1
@t.subscribe 'testeventone' , @testproc.testcallback1_1
@t.subscribe 'testeventtwo' , @testproc.testcallback2
@t.unsubscribe()
@t.publish 'testeventone', { prop1: 'propone' }
@t.publish 'testeventtwo', { prop2: 'proptwo' }
expect(@testproc.testcallback1).not.toHaveBeenCalled()
expect(@testproc.testcallback1_1).not.toHaveBeenCalled()
expect(@testproc.testcallback2).not.toHaveBeenCalled()
it 'should subscribe and publish a once event, and not publish it twice', ->
@t.subscribeOnce 'testeventone' , @testproc.testcallback1
@t.publish 'testeventone', { prop1: 'propone' }
expect(@testproc.testcallback1).toHaveBeenCalled()
@testproc.testcallback1.reset()
@t.publish 'testeventone', { prop1: 'propone' }
expect(@testproc.testcallback1).not.toHaveBeenCalled()
describe "Getters and Setters", ->
beforeEach ->
@obj = Mozart.MztObject.create
coffee: 'black'
whiskey: null
tea: -> 'english'
it 'should be able to get an attribute', ->
expect(@obj.get('coffee')).toEqual('black')
it 'should get undefined for a property that doesn\'t exist', ->
expect(@obj.get('milo')).toEqual(undefined)
it 'should get null for a property that exists with no value', ->
expect(@obj.get('whiskey')).toEqual(null)
it 'should be able to get an function with a value', ->
expect(@obj.get('tea')).toEqual('english')
it 'should be able to set an attribute', ->
@obj.set('coffee', 'flat-white')
expect(@obj.coffee).toEqual('flat-white')
it 'should be error if attempting to set an function', ->
test = -> @obj.set('coffee', 'flat-white')
expect(test).toThrow()
describe "Lookup Properties", ->
beforeEach ->
Mozart.root = @
@Spec = {}
it 'should correctly get lookup properties', ->
@Spec.one = "one1"
x = Mozart.MztObject.create
valueLookup: 'Spec.one'
expect(x.value).toEqual("one1")
it 'should correctly get lookup properties with null values', ->
@Spec.one = null
x = Mozart.MztObject.create
valueLookup: 'Spec.one'
expect(x.value).toBeNull()
it 'should set undefined on get lookup property with bad path', ->
delete @Spec["one"]
x = Mozart.MztObject.create
valueLookup: 'Spec.one'
expect(x.value).not.toBeDefined()
describe "Bindings", ->
beforeEach ->
Mozart.root = window
Spec.personController = Mozart.MztObject.create()
@tom = Mozart.MztObject.create({name: '<NAME>'})
@john = Mozart.MztObject.create({name: '<NAME>'})
it "should set up binding stuff", ->
expect(@tom._bindings.notify).toBeDefined()
expect(@tom._bindings.notify).toEqual({})
describe "Notify Bindings", ->
it "should add the binding to the internal map when transferable", ->
@view = Mozart.MztObject.create
personNotifyBinding: 'Spec.personController.subject'
expect(_.keys(@view._bindings.notify).length).toEqual(1)
expect(@view._bindings.notify.person).toBeDefined()
expect(@view._bindings.notify.subject).toBeUndefined()
expect(@view._bindings.notify.person.length).toEqual(1)
expect(@view._bindings.notify.person[0]).toEqual({attr:'subject', target: Spec.personController, transferable: true})
expect(_.keys(Spec.personController._bindings.observe).length).toEqual(1)
expect(Spec.personController._bindings.observe.subject).toBeDefined()
expect(Spec.personController._bindings.observe.person).toBeUndefined()
expect(Spec.personController._bindings.observe.subject.length).toEqual(1)
expect(Spec.personController._bindings.observe.subject[0]).toEqual({attr:'person', target: @view, transferable: true})
it "should add the binding to the internal map when non-transferable", ->
@cheston = Mozart.MztObject.create
name: '<NAME>'
@view = Mozart.MztObject.create
subject: @cheston
personNotifyBinding: 'subject.name'
expect(_.keys(@view._bindings.notify).length).toEqual(1)
expect(@view._bindings.notify.person).toBeDefined()
expect(@view._bindings.notify.subject).toBeUndefined()
expect(@view._bindings.notify.person.length).toEqual(1)
expect(@view._bindings.notify.person[0]).toEqual({attr:'name', target: @cheston, transferable: false})
expect(_.keys(@cheston._bindings.observe).length).toEqual(1)
expect(@cheston._bindings.observe.name).toBeDefined()
expect(@cheston._bindings.observe.person).toBeUndefined()
expect(@cheston._bindings.observe.name.length).toEqual(1)
expect(@cheston._bindings.observe.name[0]).toEqual({attr:'person', target: @view, transferable: false})
it "should change target on set", ->
@view = Mozart.MztObject.create
personNotifyBinding: 'Spec.personController.subject'
@view.set 'person',<NAME> @tom
expect(Spec.personController.subject).toEqual<NAME>(@tom)
@view.set 'person',<NAME> @john
expect(Spec.personController.subject).toEqual<NAME>(@john)
@view.set 'person', null
expect(Spec.personController.subject).toBeNull()
it "should set initial value", ->
@view = Mozart.MztObject.create
person:<NAME> @tom
personNotifyBinding: 'Spec.personController.subject'
expect(Spec.personController.subject).toEqual<NAME>(@tom)
it 'should allow multiple objects to notify one object', ->
@view1 = Mozart.MztObject.create
personNotifyBinding: 'Spec.personController.subject'
@view2 = Mozart.MztObject.create
personNotifyBinding: 'Spec.personController.subject'
expect(Spec.personController.subject).toBeUndefined()
@view1.set('person',<NAME> @tom)
expect(Spec.personController.subject).toEqual<NAME>(@tom)
@view2.set('person',<NAME> @john)
expect(Spec.personController.subject).toEqual<NAME>(@john)
it 'should allow bindings to be removed', ->
@view = Mozart.MztObject.create
personNotifyBinding: 'Spec.personController.subject'
@view.set 'person',<NAME> @tom
expect(Spec.personController.subject).toEqual<NAME>(@tom)
@view._removeBinding('person', Spec.personController, 'subject', Mozart.MztObject.NOTIFY)
@view.set 'person',<NAME> @john
expect(Spec.personController.subject).toEqual(<NAME>)
@view.set 'person', null
expect(Spec.personController.subject).toEqual<NAME>(@tom)
describe "Observe Bindings", ->
it 'should add the binding to the internal map of the target when transferable', ->
@view = Mozart.MztObject.create
personObserveBinding: 'Spec.personController.subject'
expect(_.keys(Spec.personController._bindings.notify).length).toEqual(1)
expect(Spec.personController._bindings.notify.subject).toBeDefined()
expect(Spec.personController._bindings.notify.person).toBeUndefined()
expect(Spec.personController._bindings.notify.subject.length).toEqual(1)
expect(Spec.personController._bindings.notify.subject[0]).toEqual({attr:'person', target: @view, transferable: true})
expect(_.keys(@view._bindings.observe).length).toEqual(1)
expect(@view._bindings.observe.person).toBeDefined()
expect(@view._bindings.observe.subject).toBeUndefined()
expect(@view._bindings.observe.person.length).toEqual(1)
expect(@view._bindings.observe.person[0]).toEqual({attr:'subject', target: Spec.personController, transferable: true})
it 'should add the binding to the internal map of the target when non-transferable', ->
@john = Mozart.MztObject.create
subject: "<NAME>"
@view = Mozart.MztObject.create
parent: @john
personObserveBinding: 'parent.subject'
expect(_.keys(@john._bindings.notify).length).toEqual(1)
expect(@john._bindings.notify.subject).toBeDefined()
expect(@john._bindings.notify.person).toBeUndefined()
expect(@john._bindings.notify.subject.length).toEqual(1)
expect(@john._bindings.notify.subject[0]).toEqual({attr:'person', target: @view, transferable: false})
expect(_.keys(@view._bindings.observe).length).toEqual(1)
expect(@view._bindings.observe.person).toBeDefined()
expect(@view._bindings.observe.subject).toBeUndefined()
expect(@view._bindings.observe.person.length).toEqual(1)
expect(@view._bindings.observe.person[0]).toEqual({attr:'subject', target: @john, transferable: false})
it "should change target on set", ->
@view = Mozart.MztObject.create
personObserveBinding: 'Spec.personController.subject'
Spec.personController.set 'subject', @tom
expect(@view.person).toEqual(@tom)
Spec.personController.set 'subject', @john
expect(@view.person).toEqual(@john)
Spec.personController.set 'subject', null
expect(@view.person).toBeNull()
it "should set initial value", ->
Spec.personController.set 'subject',<NAME> @tom
@view = Mozart.MztObject.create
personObserveBinding: 'Spec.personController.subject'
expect(@view.person).toEqual(@tom)
it "should allow multiple objects to observe one object", ->
Spec.personController.set 'subject',<NAME> @tom
@view1 = Mozart.MztObject.create
personObserveBinding: 'Spec.personController.subject'
@view2 = Mozart.MztObject.create
personObserveBinding: 'Spec.personController.subject'
expect(@view1.person).toEqual(@tom)
expect(@view2.person).toEqual(@tom)
Spec.personController.set 'subject',<NAME> @john
expect(@view1.person).toEqual(@john)
expect(@view2.person).toEqual(@john)
it "should allow bindings to be removed", ->
@view = Mozart.MztObject.create
personObserveBinding: 'Spec.personController.subject'
Spec.personController.set 'subject',<NAME> @tom
expect(@view.person).toEqual(@tom)
@view._removeBinding('person', Spec.personController, 'subject', Mozart.MztObject.OBSERVE)
Spec.personController.set 'subject',<NAME> @john
expect(@view.person).toEqual(@tom)
Spec.personController.set 'subject', null
expect(@view.person).toEqual(@tom)
describe "Sync Bindings", ->
it 'should add the binding to the internal map of both the target and the target', ->
@view = Mozart.MztObject.create
personBinding: 'Spec.personController.subject'
expect(_.keys(@view._bindings.notify).length).toEqual(1)
expect(@view._bindings.notify.person).toBeDefined()
expect(@view._bindings.notify.subject).toBeUndefined()
expect(@view._bindings.notify.person[0]).toEqual({attr:'subject', target: Spec.personController, transferable: true})
expect(_.keys(Spec.personController._bindings.notify).length).toEqual(1)
expect(Spec.personController._bindings.notify.subject).toBeDefined()
expect(Spec.personController._bindings.notify.person).toBeUndefined()
expect(Spec.personController._bindings.notify.subject[0]).toEqual({attr:'person', target: @view, transferable: true})
it "should change target on set in both directions", ->
@view = Mozart.MztObject.create
personBinding: 'Spec.personController.subject'
Spec.personController.set 'subject', @tom
expect(@view.person).toEqual(@tom)
Spec.personController.set 'subject', @john
expect(@view.person).toEqual(@john)
Spec.personController.set 'subject', null
expect(@view.person).toBeNull()
@view.set 'person', @tom
expect(Spec.personController.subject).toEqual(@tom)
@view.set 'person', @john
expect(Spec.personController.subject).toEqual(@john)
@view.set 'person', null
expect(Spec.personController.subject).toBeNull()
it "should allow a binding to be removed", ->
@view = Mozart.MztObject.create
personBinding: 'Spec.personController.subject'
Spec.personController.set 'subject', @tom
expect(@view.person).toEqual(@tom)
@view.set 'person', @john
expect(Spec.personController.subject).toEqual(@john)
@view._removeBinding('person', Spec.personController, 'subject', Mozart.MztObject.SYNC)
Spec.personController.set 'subject', @tom
expect(@view.person).toEqual(@john)
@view.set 'person', null
expect(Spec.personController.subject).toEqual<NAME>(@tom)
Spec.personController.set 'subject',<NAME> @tom
expect(@view.person).toEqual(null)
@view.set 'person',<NAME> @john
expect(Spec.personController.subject).toEqual(@tom)
describe "Relative Bindings", ->
it "should allow bindings on relative object paths", ->
@view1 = Mozart.MztObject.create
name: "TC"
@view2 = Mozart.MztObject.create
parent: @view1
parentNameBinding: "parent.name"
expect(@view2.parentName).toEqual("TC")
@view1.set("name","DOC")
expect(@view2.parentName).toEqual("DOC")
@view2.set("parentName","PZ")
expect(@view1.name).toEqual("PZ")
describe "Bindings on targets that change", ->
it 'should write to the correct object after a change', ->
Spec.personController.set 'subject', Mozart.MztObject.create({name:'Test'})
@view = Mozart.MztObject.create
subjectNameObserveBinding: 'Spec.personController.subject.name'
Spec.personController.set 'subject', @tom
expect(@view.subjectName).toEqual(@tom.name)
Spec.personController.set 'subject',<NAME> @john
expect(@view.subjectName).toEqual(@john.name)
it 'should preserve bindings when a bound property is set to null then back', ->
Spec.personController.set 'subject', Mozart.MztObject.create({name:'Test'})
@view = Mozart.MztObject.create
subjectNameObserveBinding: 'Spec.personController.subject.name'
Spec.personController.set 'subject', @tom
expect(@view.subjectName).toEqual(@tom.name)
Spec.personController.set 'subject', null
expect(@view.subjectName).toEqual(null)
Spec.personController.set 'subject',<NAME> @john
expect(@view.subjectName).toEqual(@john.name)
describe "Bindings and circular references", ->
it 'should handle circular references without an infinite loop', ->
a = Mozart.MztObject.create()
b = Mozart.MztObject.create()
c = Mozart.MztObject.create()
a._createBinding('test', b, 'test', Mozart.MztObject.SYNC, false)
b._createBinding('test', c, 'test', Mozart.MztObject.SYNC, false)
c._createBinding('test', a, 'test', Mozart.MztObject.SYNC, false)
a.set('test', 'one')
expect(b.test).toEqual('one')
expect(c.test).toEqual('one')
b.set('test', 'two')
expect(a.test).toEqual('two')
expect(c.test).toEqual('two')
c.set('test', 'three')
expect(b.test).toEqual('three')
expect(a.test).toEqual('three')
describe "Binding chaining", ->
it 'should not pollute objects when transfering bindings', ->
a = Mozart.MztObject.create({id:1})
b = Mozart.MztObject.create({id:2})
c = Mozart.MztObject.create({id:3})
Test.controller = Mozart.MztObject.create()
Mozart.root = window
e = Mozart.MztObject.create(
activeObserveBinding: "Test.controller.content"
)
Test.controller.set('content',a)
expect(Test.controller.content.id).toEqual(1)
expect(e.active.id).toEqual(1)
Test.controller.set('content',b)
expect(Test.controller.content.id).toEqual(2)
expect(e.active.id).toEqual(2)
Test.controller.set('content',c)
expect(Test.controller.content.id).toEqual(3)
expect(e.active.id).toEqual(3)
it "should not transfer non-transferable bindings", ->
Mozart.root = window
@objA = Mozart.MztObject.create
name: '<NAME>'
@objA2 = Mozart.MztObject.create
parent:@objA
parentNameObserveBinding: 'parent.name'
@objB = Mozart.MztObject.create
name: '<NAME>'
@objB2 = Mozart.MztObject.create
parent:@objB
parentNameObserveBinding: 'parent.name'
Test.controller = Mozart.MztObject.create
subject: @objA
@observer = Mozart.MztObject.create
subjectNameObserveBinding: 'Test.controller.subject.name'
expect(@observer.subjectName).toEqual('Che<NAME>')
expect(@objA2.parentName).toEqual('<NAME>')
expect(@objB2.parentName).toEqual('<NAME>')
Test.controller.set('subject', @objB)
expect(@observer.subjectName).toEqual('<NAME>')
expect(@objA2.parentName).toEqual('<NAME>')
expect(@objB2.parentName).toEqual('<NAME>')
describe "Binding removal", ->
it "should remove the correct binding when an object is released", ->
Mozart.root = window
Test.controller = Mozart.MztObject.create
subject: 'one'
y = Mozart.MztObject.create
testObserveBinding: 'Test.controller.subject'
z = Mozart.MztObject.create
testObserveBinding: 'Test.controller.subject'
Test.controller.set('subject', 'two')
expect(y.test).toEqual('two')
expect(z.test).toEqual('two')
y.release()
Test.controller.set('subject', 'three')
expect(z.test).toEqual('three')
| true | Test = window.Test = @Test = {}
Spec = window.Spec = @Spec = {}
describe 'Mozart.MztObject', ->
describe 'Mixins', ->
Mozart.TestMixin =
test: -> 'Mozart.TestMixin.text'
class TestModule1 extends Mozart.MztObject
@extend Mozart.TestMixin
class TestModule2 extends Mozart.MztObject
@include Mozart.TestMixin
it 'should allow call on mixin on instance when extended', ->
t = TestModule1.create()
expect(t.test()).toEqual('Mozart.TestMixin.text')
expect(TestModule1.test).not.toBeDefined()
it 'should allow call on mixin on instance when included', ->
t = TestModule2.create()
expect(t.test).not.toBeDefined()
expect(TestModule2.test()).toEqual('Mozart.TestMixin.text')
describe 'Events', ->
beforeEach ->
class Test.EventTestClass extends Mozart.MztObject
@t = Test.EventTestClass.create()
@testproc =
testcallback1: (data) ->
expect(data.prop1).toEqual('propone')
testcallback2: (data) ->
expect(data.prop2).toEqual('proptwo')
testcallback1_1: (data) ->
expect(data.prop2).toEqual('proptwo')
spyOn(@testproc,'testcallback1')
spyOn(@testproc,'testcallback2')
spyOn(@testproc,'testcallback1_1')
it 'should subscribe and publish an event', ->
@t.subscribe 'testeventone' , @testproc.testcallback1
@t.publish 'testeventone', { prop1: 'propone' }
expect(@testproc.testcallback1).toHaveBeenCalled()
expect(@testproc.testcallback2).not.toHaveBeenCalled()
it 'should subscribe and publish multiple events', ->
@t.subscribe 'testeventone' , @testproc.testcallback1
@t.subscribe 'testeventtwo' , @testproc.testcallback2
@t.publish 'testeventone', { prop1: 'propone' }
expect(@testproc.testcallback1).toHaveBeenCalled()
@t.publish 'testeventtwo', { prop2: 'proptwo' }
expect(@testproc.testcallback2).toHaveBeenCalled()
it 'should subscribe and publish multiple callbacks on one event', ->
@t.subscribe 'testeventone' , @testproc.testcallback1
@t.subscribe 'testeventone' , @testproc.testcallback1_1
@t.publish 'testeventone', { prop1: 'propone' }
expect(@testproc.testcallback1).toHaveBeenCalled()
expect(@testproc.testcallback1_1).toHaveBeenCalled()
it 'should unsubscribe from a single event and callback', ->
@t.subscribe 'testeventone' , @testproc.testcallback1
@t.subscribe 'testeventone' , @testproc.testcallback1_1
@t.unsubscribe 'testeventone', @testproc.testcallback1_1
@t.publish 'testeventone', { prop1: 'propone' }
expect(@testproc.testcallback1).toHaveBeenCalled()
expect(@testproc.testcallback1_1).not.toHaveBeenCalled()
it 'should unsubscribe all callbacks from a single event', ->
@t.subscribe 'testeventone' , @testproc.testcallback1
@t.subscribe 'testeventone' , @testproc.testcallback1_1
@t.subscribe 'testeventtwo' , @testproc.testcallback2
@t.unsubscribe 'testeventone'
@t.publish 'testeventone', { prop1: 'propone' }
@t.publish 'testeventtwo', { prop2: 'proptwo' }
expect(@testproc.testcallback1).not.toHaveBeenCalled()
expect(@testproc.testcallback1_1).not.toHaveBeenCalled()
expect(@testproc.testcallback2).toHaveBeenCalled()
it 'should unsubscribe all callbacks', ->
@t.subscribe 'testeventone' , @testproc.testcallback1
@t.subscribe 'testeventone' , @testproc.testcallback1_1
@t.subscribe 'testeventtwo' , @testproc.testcallback2
@t.unsubscribe()
@t.publish 'testeventone', { prop1: 'propone' }
@t.publish 'testeventtwo', { prop2: 'proptwo' }
expect(@testproc.testcallback1).not.toHaveBeenCalled()
expect(@testproc.testcallback1_1).not.toHaveBeenCalled()
expect(@testproc.testcallback2).not.toHaveBeenCalled()
it 'should subscribe and publish a once event, and not publish it twice', ->
@t.subscribeOnce 'testeventone' , @testproc.testcallback1
@t.publish 'testeventone', { prop1: 'propone' }
expect(@testproc.testcallback1).toHaveBeenCalled()
@testproc.testcallback1.reset()
@t.publish 'testeventone', { prop1: 'propone' }
expect(@testproc.testcallback1).not.toHaveBeenCalled()
describe "Getters and Setters", ->
beforeEach ->
@obj = Mozart.MztObject.create
coffee: 'black'
whiskey: null
tea: -> 'english'
it 'should be able to get an attribute', ->
expect(@obj.get('coffee')).toEqual('black')
it 'should get undefined for a property that doesn\'t exist', ->
expect(@obj.get('milo')).toEqual(undefined)
it 'should get null for a property that exists with no value', ->
expect(@obj.get('whiskey')).toEqual(null)
it 'should be able to get an function with a value', ->
expect(@obj.get('tea')).toEqual('english')
it 'should be able to set an attribute', ->
@obj.set('coffee', 'flat-white')
expect(@obj.coffee).toEqual('flat-white')
it 'should be error if attempting to set an function', ->
test = -> @obj.set('coffee', 'flat-white')
expect(test).toThrow()
describe "Lookup Properties", ->
beforeEach ->
Mozart.root = @
@Spec = {}
it 'should correctly get lookup properties', ->
@Spec.one = "one1"
x = Mozart.MztObject.create
valueLookup: 'Spec.one'
expect(x.value).toEqual("one1")
it 'should correctly get lookup properties with null values', ->
@Spec.one = null
x = Mozart.MztObject.create
valueLookup: 'Spec.one'
expect(x.value).toBeNull()
it 'should set undefined on get lookup property with bad path', ->
delete @Spec["one"]
x = Mozart.MztObject.create
valueLookup: 'Spec.one'
expect(x.value).not.toBeDefined()
describe "Bindings", ->
beforeEach ->
Mozart.root = window
Spec.personController = Mozart.MztObject.create()
@tom = Mozart.MztObject.create({name: 'PI:NAME:<NAME>END_PI'})
@john = Mozart.MztObject.create({name: 'PI:NAME:<NAME>END_PI'})
it "should set up binding stuff", ->
expect(@tom._bindings.notify).toBeDefined()
expect(@tom._bindings.notify).toEqual({})
describe "Notify Bindings", ->
it "should add the binding to the internal map when transferable", ->
@view = Mozart.MztObject.create
personNotifyBinding: 'Spec.personController.subject'
expect(_.keys(@view._bindings.notify).length).toEqual(1)
expect(@view._bindings.notify.person).toBeDefined()
expect(@view._bindings.notify.subject).toBeUndefined()
expect(@view._bindings.notify.person.length).toEqual(1)
expect(@view._bindings.notify.person[0]).toEqual({attr:'subject', target: Spec.personController, transferable: true})
expect(_.keys(Spec.personController._bindings.observe).length).toEqual(1)
expect(Spec.personController._bindings.observe.subject).toBeDefined()
expect(Spec.personController._bindings.observe.person).toBeUndefined()
expect(Spec.personController._bindings.observe.subject.length).toEqual(1)
expect(Spec.personController._bindings.observe.subject[0]).toEqual({attr:'person', target: @view, transferable: true})
it "should add the binding to the internal map when non-transferable", ->
@cheston = Mozart.MztObject.create
name: 'PI:NAME:<NAME>END_PI'
@view = Mozart.MztObject.create
subject: @cheston
personNotifyBinding: 'subject.name'
expect(_.keys(@view._bindings.notify).length).toEqual(1)
expect(@view._bindings.notify.person).toBeDefined()
expect(@view._bindings.notify.subject).toBeUndefined()
expect(@view._bindings.notify.person.length).toEqual(1)
expect(@view._bindings.notify.person[0]).toEqual({attr:'name', target: @cheston, transferable: false})
expect(_.keys(@cheston._bindings.observe).length).toEqual(1)
expect(@cheston._bindings.observe.name).toBeDefined()
expect(@cheston._bindings.observe.person).toBeUndefined()
expect(@cheston._bindings.observe.name.length).toEqual(1)
expect(@cheston._bindings.observe.name[0]).toEqual({attr:'person', target: @view, transferable: false})
it "should change target on set", ->
@view = Mozart.MztObject.create
personNotifyBinding: 'Spec.personController.subject'
@view.set 'person',PI:NAME:<NAME>END_PI @tom
expect(Spec.personController.subject).toEqualPI:NAME:<NAME>END_PI(@tom)
@view.set 'person',PI:NAME:<NAME>END_PI @john
expect(Spec.personController.subject).toEqualPI:NAME:<NAME>END_PI(@john)
@view.set 'person', null
expect(Spec.personController.subject).toBeNull()
it "should set initial value", ->
@view = Mozart.MztObject.create
person:PI:NAME:<NAME>END_PI @tom
personNotifyBinding: 'Spec.personController.subject'
expect(Spec.personController.subject).toEqualPI:NAME:<NAME>END_PI(@tom)
it 'should allow multiple objects to notify one object', ->
@view1 = Mozart.MztObject.create
personNotifyBinding: 'Spec.personController.subject'
@view2 = Mozart.MztObject.create
personNotifyBinding: 'Spec.personController.subject'
expect(Spec.personController.subject).toBeUndefined()
@view1.set('person',PI:NAME:<NAME>END_PI @tom)
expect(Spec.personController.subject).toEqualPI:NAME:<NAME>END_PI(@tom)
@view2.set('person',PI:NAME:<NAME>END_PI @john)
expect(Spec.personController.subject).toEqualPI:NAME:<NAME>END_PI(@john)
it 'should allow bindings to be removed', ->
@view = Mozart.MztObject.create
personNotifyBinding: 'Spec.personController.subject'
@view.set 'person',PI:NAME:<NAME>END_PI @tom
expect(Spec.personController.subject).toEqualPI:NAME:<NAME>END_PI(@tom)
@view._removeBinding('person', Spec.personController, 'subject', Mozart.MztObject.NOTIFY)
@view.set 'person',PI:NAME:<NAME>END_PI @john
expect(Spec.personController.subject).toEqual(PI:NAME:<NAME>END_PI)
@view.set 'person', null
expect(Spec.personController.subject).toEqualPI:NAME:<NAME>END_PI(@tom)
describe "Observe Bindings", ->
it 'should add the binding to the internal map of the target when transferable', ->
@view = Mozart.MztObject.create
personObserveBinding: 'Spec.personController.subject'
expect(_.keys(Spec.personController._bindings.notify).length).toEqual(1)
expect(Spec.personController._bindings.notify.subject).toBeDefined()
expect(Spec.personController._bindings.notify.person).toBeUndefined()
expect(Spec.personController._bindings.notify.subject.length).toEqual(1)
expect(Spec.personController._bindings.notify.subject[0]).toEqual({attr:'person', target: @view, transferable: true})
expect(_.keys(@view._bindings.observe).length).toEqual(1)
expect(@view._bindings.observe.person).toBeDefined()
expect(@view._bindings.observe.subject).toBeUndefined()
expect(@view._bindings.observe.person.length).toEqual(1)
expect(@view._bindings.observe.person[0]).toEqual({attr:'subject', target: Spec.personController, transferable: true})
it 'should add the binding to the internal map of the target when non-transferable', ->
@john = Mozart.MztObject.create
subject: "PI:NAME:<NAME>END_PI"
@view = Mozart.MztObject.create
parent: @john
personObserveBinding: 'parent.subject'
expect(_.keys(@john._bindings.notify).length).toEqual(1)
expect(@john._bindings.notify.subject).toBeDefined()
expect(@john._bindings.notify.person).toBeUndefined()
expect(@john._bindings.notify.subject.length).toEqual(1)
expect(@john._bindings.notify.subject[0]).toEqual({attr:'person', target: @view, transferable: false})
expect(_.keys(@view._bindings.observe).length).toEqual(1)
expect(@view._bindings.observe.person).toBeDefined()
expect(@view._bindings.observe.subject).toBeUndefined()
expect(@view._bindings.observe.person.length).toEqual(1)
expect(@view._bindings.observe.person[0]).toEqual({attr:'subject', target: @john, transferable: false})
it "should change target on set", ->
@view = Mozart.MztObject.create
personObserveBinding: 'Spec.personController.subject'
Spec.personController.set 'subject', @tom
expect(@view.person).toEqual(@tom)
Spec.personController.set 'subject', @john
expect(@view.person).toEqual(@john)
Spec.personController.set 'subject', null
expect(@view.person).toBeNull()
it "should set initial value", ->
Spec.personController.set 'subject',PI:NAME:<NAME>END_PI @tom
@view = Mozart.MztObject.create
personObserveBinding: 'Spec.personController.subject'
expect(@view.person).toEqual(@tom)
it "should allow multiple objects to observe one object", ->
Spec.personController.set 'subject',PI:NAME:<NAME>END_PI @tom
@view1 = Mozart.MztObject.create
personObserveBinding: 'Spec.personController.subject'
@view2 = Mozart.MztObject.create
personObserveBinding: 'Spec.personController.subject'
expect(@view1.person).toEqual(@tom)
expect(@view2.person).toEqual(@tom)
Spec.personController.set 'subject',PI:NAME:<NAME>END_PI @john
expect(@view1.person).toEqual(@john)
expect(@view2.person).toEqual(@john)
it "should allow bindings to be removed", ->
@view = Mozart.MztObject.create
personObserveBinding: 'Spec.personController.subject'
Spec.personController.set 'subject',PI:NAME:<NAME>END_PI @tom
expect(@view.person).toEqual(@tom)
@view._removeBinding('person', Spec.personController, 'subject', Mozart.MztObject.OBSERVE)
Spec.personController.set 'subject',PI:NAME:<NAME>END_PI @john
expect(@view.person).toEqual(@tom)
Spec.personController.set 'subject', null
expect(@view.person).toEqual(@tom)
describe "Sync Bindings", ->
it 'should add the binding to the internal map of both the target and the target', ->
@view = Mozart.MztObject.create
personBinding: 'Spec.personController.subject'
expect(_.keys(@view._bindings.notify).length).toEqual(1)
expect(@view._bindings.notify.person).toBeDefined()
expect(@view._bindings.notify.subject).toBeUndefined()
expect(@view._bindings.notify.person[0]).toEqual({attr:'subject', target: Spec.personController, transferable: true})
expect(_.keys(Spec.personController._bindings.notify).length).toEqual(1)
expect(Spec.personController._bindings.notify.subject).toBeDefined()
expect(Spec.personController._bindings.notify.person).toBeUndefined()
expect(Spec.personController._bindings.notify.subject[0]).toEqual({attr:'person', target: @view, transferable: true})
it "should change target on set in both directions", ->
@view = Mozart.MztObject.create
personBinding: 'Spec.personController.subject'
Spec.personController.set 'subject', @tom
expect(@view.person).toEqual(@tom)
Spec.personController.set 'subject', @john
expect(@view.person).toEqual(@john)
Spec.personController.set 'subject', null
expect(@view.person).toBeNull()
@view.set 'person', @tom
expect(Spec.personController.subject).toEqual(@tom)
@view.set 'person', @john
expect(Spec.personController.subject).toEqual(@john)
@view.set 'person', null
expect(Spec.personController.subject).toBeNull()
it "should allow a binding to be removed", ->
@view = Mozart.MztObject.create
personBinding: 'Spec.personController.subject'
Spec.personController.set 'subject', @tom
expect(@view.person).toEqual(@tom)
@view.set 'person', @john
expect(Spec.personController.subject).toEqual(@john)
@view._removeBinding('person', Spec.personController, 'subject', Mozart.MztObject.SYNC)
Spec.personController.set 'subject', @tom
expect(@view.person).toEqual(@john)
@view.set 'person', null
expect(Spec.personController.subject).toEqualPI:NAME:<NAME>END_PI(@tom)
Spec.personController.set 'subject',PI:NAME:<NAME>END_PI @tom
expect(@view.person).toEqual(null)
@view.set 'person',PI:NAME:<NAME>END_PI @john
expect(Spec.personController.subject).toEqual(@tom)
describe "Relative Bindings", ->
it "should allow bindings on relative object paths", ->
@view1 = Mozart.MztObject.create
name: "TC"
@view2 = Mozart.MztObject.create
parent: @view1
parentNameBinding: "parent.name"
expect(@view2.parentName).toEqual("TC")
@view1.set("name","DOC")
expect(@view2.parentName).toEqual("DOC")
@view2.set("parentName","PZ")
expect(@view1.name).toEqual("PZ")
describe "Bindings on targets that change", ->
it 'should write to the correct object after a change', ->
Spec.personController.set 'subject', Mozart.MztObject.create({name:'Test'})
@view = Mozart.MztObject.create
subjectNameObserveBinding: 'Spec.personController.subject.name'
Spec.personController.set 'subject', @tom
expect(@view.subjectName).toEqual(@tom.name)
Spec.personController.set 'subject',PI:NAME:<NAME>END_PI @john
expect(@view.subjectName).toEqual(@john.name)
it 'should preserve bindings when a bound property is set to null then back', ->
Spec.personController.set 'subject', Mozart.MztObject.create({name:'Test'})
@view = Mozart.MztObject.create
subjectNameObserveBinding: 'Spec.personController.subject.name'
Spec.personController.set 'subject', @tom
expect(@view.subjectName).toEqual(@tom.name)
Spec.personController.set 'subject', null
expect(@view.subjectName).toEqual(null)
Spec.personController.set 'subject',PI:NAME:<NAME>END_PI @john
expect(@view.subjectName).toEqual(@john.name)
describe "Bindings and circular references", ->
it 'should handle circular references without an infinite loop', ->
a = Mozart.MztObject.create()
b = Mozart.MztObject.create()
c = Mozart.MztObject.create()
a._createBinding('test', b, 'test', Mozart.MztObject.SYNC, false)
b._createBinding('test', c, 'test', Mozart.MztObject.SYNC, false)
c._createBinding('test', a, 'test', Mozart.MztObject.SYNC, false)
a.set('test', 'one')
expect(b.test).toEqual('one')
expect(c.test).toEqual('one')
b.set('test', 'two')
expect(a.test).toEqual('two')
expect(c.test).toEqual('two')
c.set('test', 'three')
expect(b.test).toEqual('three')
expect(a.test).toEqual('three')
describe "Binding chaining", ->
it 'should not pollute objects when transfering bindings', ->
a = Mozart.MztObject.create({id:1})
b = Mozart.MztObject.create({id:2})
c = Mozart.MztObject.create({id:3})
Test.controller = Mozart.MztObject.create()
Mozart.root = window
e = Mozart.MztObject.create(
activeObserveBinding: "Test.controller.content"
)
Test.controller.set('content',a)
expect(Test.controller.content.id).toEqual(1)
expect(e.active.id).toEqual(1)
Test.controller.set('content',b)
expect(Test.controller.content.id).toEqual(2)
expect(e.active.id).toEqual(2)
Test.controller.set('content',c)
expect(Test.controller.content.id).toEqual(3)
expect(e.active.id).toEqual(3)
it "should not transfer non-transferable bindings", ->
Mozart.root = window
@objA = Mozart.MztObject.create
name: 'PI:NAME:<NAME>END_PI'
@objA2 = Mozart.MztObject.create
parent:@objA
parentNameObserveBinding: 'parent.name'
@objB = Mozart.MztObject.create
name: 'PI:NAME:<NAME>END_PI'
@objB2 = Mozart.MztObject.create
parent:@objB
parentNameObserveBinding: 'parent.name'
Test.controller = Mozart.MztObject.create
subject: @objA
@observer = Mozart.MztObject.create
subjectNameObserveBinding: 'Test.controller.subject.name'
expect(@observer.subjectName).toEqual('ChePI:NAME:<NAME>END_PI')
expect(@objA2.parentName).toEqual('PI:NAME:<NAME>END_PI')
expect(@objB2.parentName).toEqual('PI:NAME:<NAME>END_PI')
Test.controller.set('subject', @objB)
expect(@observer.subjectName).toEqual('PI:NAME:<NAME>END_PI')
expect(@objA2.parentName).toEqual('PI:NAME:<NAME>END_PI')
expect(@objB2.parentName).toEqual('PI:NAME:<NAME>END_PI')
describe "Binding removal", ->
it "should remove the correct binding when an object is released", ->
Mozart.root = window
Test.controller = Mozart.MztObject.create
subject: 'one'
y = Mozart.MztObject.create
testObserveBinding: 'Test.controller.subject'
z = Mozart.MztObject.create
testObserveBinding: 'Test.controller.subject'
Test.controller.set('subject', 'two')
expect(y.test).toEqual('two')
expect(z.test).toEqual('two')
y.release()
Test.controller.set('subject', 'three')
expect(z.test).toEqual('three')
|
[
{
"context": "z.zone('America/New_York'))\n @user = new User('Jimmy Hendricks', 'jeff', false, timetable)\n describe '#parse(ro",
"end": 3592,
"score": 0.9998878240585327,
"start": 3577,
"tag": "NAME",
"value": "Jimmy Hendricks"
},
{
"context": "_York'))\n @user = new User('Ji... | tests/models/test_user.coffee | fangamer/ibizan | 0 | moment = require 'moment-timezone'
expect = require('chai').expect
constants = require '../../src/helpers/constants'
{User, Timetable} = require '../../src/models/user'
describe 'Timetable', ->
beforeEach ->
start = moment({day: 3, hour: 7})
end = moment({day: 3, hour: 18})
@timetable = new Timetable(start, end, 'America/New_York')
test_validate_set_values = (timetable, mode,
total, expectedTotal,
available, expectedAvailable) ->
timetable['set' + mode.charAt(0).toUpperCase() + mode.substring(1)](total, available)
expect(timetable[mode+'Total']).to.eql expectedTotal
if available and expectedAvailable
expect(timetable[mode+'Available']).to.eql expectedAvailable
describe '#setVacation(total, available)', ->
mode = 'vacation'
it 'should change the underlying values', ->
test_validate_set_values(@timetable, mode, 85, 85, 30, 30)
it 'should only take numbers', ->
test_validate_set_values(@timetable, mode, 'ghosts', 0, {}, 0)
it 'should only take positive numbers', ->
test_validate_set_values(@timetable, mode, -85, 0, -30, 0)
it 'should handle less than two arguments gracefully', ->
test_validate_set_values(@timetable, mode, undefined, 0)
describe '#setSick(total, available)', ->
mode = 'sick'
it 'should change the underlying values', ->
test_validate_set_values(@timetable, mode, 85, 85, 30, 30)
it 'should only take numbers', ->
test_validate_set_values(@timetable, mode, 'ghosts', 0, {}, 0)
it 'should only take positive numbers', ->
test_validate_set_values(@timetable, mode, -85, 0, -30, 0)
it 'should handle less than two arguments gracefully', ->
test_validate_set_values(@timetable, mode, undefined, 0)
describe '#setUnpaid(total)', ->
mode = 'unpaid'
it 'should change the underlying values', ->
test_validate_set_values(@timetable, mode, 85, 85)
it 'should only take numbers', ->
test_validate_set_values(@timetable, mode, 'ghosts', 0)
it 'should only take positive numbers', ->
test_validate_set_values(@timetable, mode, -85, 0)
it 'should handle less than two arguments gracefully', ->
test_validate_set_values(@timetable, mode, undefined, 0)
describe '#setLogged(total)', ->
mode = 'logged'
it 'should change the underlying values', ->
test_validate_set_values(@timetable, mode, 85, 85)
it 'should only take numbers', ->
test_validate_set_values(@timetable, mode, 'ghosts', 0)
it 'should only take positive numbers', ->
test_validate_set_values(@timetable, mode, -85, 0)
it 'should handle less than two arguments gracefully', ->
test_validate_set_values(@timetable, mode, undefined, 0)
describe '#setAverageLogged(total)', ->
mode = 'averageLogged'
it 'should change the underlying values', ->
test_validate_set_values(@timetable, mode, 85, 85)
it 'should only take numbers', ->
test_validate_set_values(@timetable, mode, 'ghosts', 0)
it 'should only take positive numbers', ->
test_validate_set_values(@timetable, mode, -85, 0)
it 'should handle less than two arguments gracefully', ->
test_validate_set_values(@timetable, mode, undefined, 0)
test_row = require('../mocks/mocked/mocked_employees.json')[0]
describe 'User', ->
beforeEach ->
start = moment({day: 3, hour: 7})
end = moment({day: 3, hour: 18})
timetable = new Timetable(start, end, moment.tz.zone('America/New_York'))
@user = new User('Jimmy Hendricks', 'jeff', false, timetable)
describe '#parse(row)', ->
it 'should return a new User when given a row', ->
user = User.parse test_row
expect(user).to.not.be.null
describe '#activeHours()', ->
it 'should return an array', ->
expect(@user.activeHours()).to.be.instanceof Array
it 'should return an array of two dates', ->
dates = @user.activeHours()
expect(dates).to.have.length(2)
expect(dates).to.have.deep.property('[0]')
.that.is.an.instanceof moment
expect(dates).to.have.deep.property('[1]')
.that.is.an.instanceof moment
it 'should return the start and end times', ->
dates = @user.activeHours()
expect(dates).to.have.deep.property '[0]', @user.timetable.start
expect(dates).to.have.deep.property '[1]', @user.timetable.end
describe '#activeTime()', ->
it 'should return the elapsed time between start and end', ->
elapsed = @user.activeTime()
expect(elapsed).to.be.a.Number
expect(elapsed).to.equal 8
describe '#isInactive()', ->
it 'should be true when it is earlier than the start time', ->
[start, end] = @user.activeHours()
time = moment(start).subtract(2, 'hours')
expect(@user.isInactive(time)).to.be.true
it 'should be true when it is later than the end time', ->
[start, end] = @user.activeHours()
time = moment(end).add(2, 'hours')
expect(@user.isInactive(time)).to.be.true
it 'should be false when it is in between the start and end time', ->
[start, end] = @user.activeHours()
time = moment(start).add(end.diff(start, 'hours') / 2, 'hours')
expect(@user.isInactive(time)).to.be.false
describe '#undoPunch()', ->
describe '#toRawPayroll(start, end)', ->
it 'should not return null', ->
payrollRow = @user.toRawPayroll()
expect(payrollRow).to.not.be.null
describe '#updateRow()', ->
describe '#description()', ->
it 'should return a description of the project for output', ->
description = @user.description()
expect(description).to.exist
| 221321 | moment = require 'moment-timezone'
expect = require('chai').expect
constants = require '../../src/helpers/constants'
{User, Timetable} = require '../../src/models/user'
describe 'Timetable', ->
beforeEach ->
start = moment({day: 3, hour: 7})
end = moment({day: 3, hour: 18})
@timetable = new Timetable(start, end, 'America/New_York')
test_validate_set_values = (timetable, mode,
total, expectedTotal,
available, expectedAvailable) ->
timetable['set' + mode.charAt(0).toUpperCase() + mode.substring(1)](total, available)
expect(timetable[mode+'Total']).to.eql expectedTotal
if available and expectedAvailable
expect(timetable[mode+'Available']).to.eql expectedAvailable
describe '#setVacation(total, available)', ->
mode = 'vacation'
it 'should change the underlying values', ->
test_validate_set_values(@timetable, mode, 85, 85, 30, 30)
it 'should only take numbers', ->
test_validate_set_values(@timetable, mode, 'ghosts', 0, {}, 0)
it 'should only take positive numbers', ->
test_validate_set_values(@timetable, mode, -85, 0, -30, 0)
it 'should handle less than two arguments gracefully', ->
test_validate_set_values(@timetable, mode, undefined, 0)
describe '#setSick(total, available)', ->
mode = 'sick'
it 'should change the underlying values', ->
test_validate_set_values(@timetable, mode, 85, 85, 30, 30)
it 'should only take numbers', ->
test_validate_set_values(@timetable, mode, 'ghosts', 0, {}, 0)
it 'should only take positive numbers', ->
test_validate_set_values(@timetable, mode, -85, 0, -30, 0)
it 'should handle less than two arguments gracefully', ->
test_validate_set_values(@timetable, mode, undefined, 0)
describe '#setUnpaid(total)', ->
mode = 'unpaid'
it 'should change the underlying values', ->
test_validate_set_values(@timetable, mode, 85, 85)
it 'should only take numbers', ->
test_validate_set_values(@timetable, mode, 'ghosts', 0)
it 'should only take positive numbers', ->
test_validate_set_values(@timetable, mode, -85, 0)
it 'should handle less than two arguments gracefully', ->
test_validate_set_values(@timetable, mode, undefined, 0)
describe '#setLogged(total)', ->
mode = 'logged'
it 'should change the underlying values', ->
test_validate_set_values(@timetable, mode, 85, 85)
it 'should only take numbers', ->
test_validate_set_values(@timetable, mode, 'ghosts', 0)
it 'should only take positive numbers', ->
test_validate_set_values(@timetable, mode, -85, 0)
it 'should handle less than two arguments gracefully', ->
test_validate_set_values(@timetable, mode, undefined, 0)
describe '#setAverageLogged(total)', ->
mode = 'averageLogged'
it 'should change the underlying values', ->
test_validate_set_values(@timetable, mode, 85, 85)
it 'should only take numbers', ->
test_validate_set_values(@timetable, mode, 'ghosts', 0)
it 'should only take positive numbers', ->
test_validate_set_values(@timetable, mode, -85, 0)
it 'should handle less than two arguments gracefully', ->
test_validate_set_values(@timetable, mode, undefined, 0)
test_row = require('../mocks/mocked/mocked_employees.json')[0]
describe 'User', ->
beforeEach ->
start = moment({day: 3, hour: 7})
end = moment({day: 3, hour: 18})
timetable = new Timetable(start, end, moment.tz.zone('America/New_York'))
@user = new User('<NAME>', 'jeff', false, timetable)
describe '#parse(row)', ->
it 'should return a new User when given a row', ->
user = User.parse test_row
expect(user).to.not.be.null
describe '#activeHours()', ->
it 'should return an array', ->
expect(@user.activeHours()).to.be.instanceof Array
it 'should return an array of two dates', ->
dates = @user.activeHours()
expect(dates).to.have.length(2)
expect(dates).to.have.deep.property('[0]')
.that.is.an.instanceof moment
expect(dates).to.have.deep.property('[1]')
.that.is.an.instanceof moment
it 'should return the start and end times', ->
dates = @user.activeHours()
expect(dates).to.have.deep.property '[0]', @user.timetable.start
expect(dates).to.have.deep.property '[1]', @user.timetable.end
describe '#activeTime()', ->
it 'should return the elapsed time between start and end', ->
elapsed = @user.activeTime()
expect(elapsed).to.be.a.Number
expect(elapsed).to.equal 8
describe '#isInactive()', ->
it 'should be true when it is earlier than the start time', ->
[start, end] = @user.activeHours()
time = moment(start).subtract(2, 'hours')
expect(@user.isInactive(time)).to.be.true
it 'should be true when it is later than the end time', ->
[start, end] = @user.activeHours()
time = moment(end).add(2, 'hours')
expect(@user.isInactive(time)).to.be.true
it 'should be false when it is in between the start and end time', ->
[start, end] = @user.activeHours()
time = moment(start).add(end.diff(start, 'hours') / 2, 'hours')
expect(@user.isInactive(time)).to.be.false
describe '#undoPunch()', ->
describe '#toRawPayroll(start, end)', ->
it 'should not return null', ->
payrollRow = @user.toRawPayroll()
expect(payrollRow).to.not.be.null
describe '#updateRow()', ->
describe '#description()', ->
it 'should return a description of the project for output', ->
description = @user.description()
expect(description).to.exist
| true | moment = require 'moment-timezone'
expect = require('chai').expect
constants = require '../../src/helpers/constants'
{User, Timetable} = require '../../src/models/user'
describe 'Timetable', ->
beforeEach ->
start = moment({day: 3, hour: 7})
end = moment({day: 3, hour: 18})
@timetable = new Timetable(start, end, 'America/New_York')
test_validate_set_values = (timetable, mode,
total, expectedTotal,
available, expectedAvailable) ->
timetable['set' + mode.charAt(0).toUpperCase() + mode.substring(1)](total, available)
expect(timetable[mode+'Total']).to.eql expectedTotal
if available and expectedAvailable
expect(timetable[mode+'Available']).to.eql expectedAvailable
describe '#setVacation(total, available)', ->
mode = 'vacation'
it 'should change the underlying values', ->
test_validate_set_values(@timetable, mode, 85, 85, 30, 30)
it 'should only take numbers', ->
test_validate_set_values(@timetable, mode, 'ghosts', 0, {}, 0)
it 'should only take positive numbers', ->
test_validate_set_values(@timetable, mode, -85, 0, -30, 0)
it 'should handle less than two arguments gracefully', ->
test_validate_set_values(@timetable, mode, undefined, 0)
describe '#setSick(total, available)', ->
mode = 'sick'
it 'should change the underlying values', ->
test_validate_set_values(@timetable, mode, 85, 85, 30, 30)
it 'should only take numbers', ->
test_validate_set_values(@timetable, mode, 'ghosts', 0, {}, 0)
it 'should only take positive numbers', ->
test_validate_set_values(@timetable, mode, -85, 0, -30, 0)
it 'should handle less than two arguments gracefully', ->
test_validate_set_values(@timetable, mode, undefined, 0)
describe '#setUnpaid(total)', ->
mode = 'unpaid'
it 'should change the underlying values', ->
test_validate_set_values(@timetable, mode, 85, 85)
it 'should only take numbers', ->
test_validate_set_values(@timetable, mode, 'ghosts', 0)
it 'should only take positive numbers', ->
test_validate_set_values(@timetable, mode, -85, 0)
it 'should handle less than two arguments gracefully', ->
test_validate_set_values(@timetable, mode, undefined, 0)
describe '#setLogged(total)', ->
mode = 'logged'
it 'should change the underlying values', ->
test_validate_set_values(@timetable, mode, 85, 85)
it 'should only take numbers', ->
test_validate_set_values(@timetable, mode, 'ghosts', 0)
it 'should only take positive numbers', ->
test_validate_set_values(@timetable, mode, -85, 0)
it 'should handle less than two arguments gracefully', ->
test_validate_set_values(@timetable, mode, undefined, 0)
describe '#setAverageLogged(total)', ->
mode = 'averageLogged'
it 'should change the underlying values', ->
test_validate_set_values(@timetable, mode, 85, 85)
it 'should only take numbers', ->
test_validate_set_values(@timetable, mode, 'ghosts', 0)
it 'should only take positive numbers', ->
test_validate_set_values(@timetable, mode, -85, 0)
it 'should handle less than two arguments gracefully', ->
test_validate_set_values(@timetable, mode, undefined, 0)
test_row = require('../mocks/mocked/mocked_employees.json')[0]
describe 'User', ->
beforeEach ->
start = moment({day: 3, hour: 7})
end = moment({day: 3, hour: 18})
timetable = new Timetable(start, end, moment.tz.zone('America/New_York'))
@user = new User('PI:NAME:<NAME>END_PI', 'jeff', false, timetable)
describe '#parse(row)', ->
it 'should return a new User when given a row', ->
user = User.parse test_row
expect(user).to.not.be.null
describe '#activeHours()', ->
it 'should return an array', ->
expect(@user.activeHours()).to.be.instanceof Array
it 'should return an array of two dates', ->
dates = @user.activeHours()
expect(dates).to.have.length(2)
expect(dates).to.have.deep.property('[0]')
.that.is.an.instanceof moment
expect(dates).to.have.deep.property('[1]')
.that.is.an.instanceof moment
it 'should return the start and end times', ->
dates = @user.activeHours()
expect(dates).to.have.deep.property '[0]', @user.timetable.start
expect(dates).to.have.deep.property '[1]', @user.timetable.end
describe '#activeTime()', ->
it 'should return the elapsed time between start and end', ->
elapsed = @user.activeTime()
expect(elapsed).to.be.a.Number
expect(elapsed).to.equal 8
describe '#isInactive()', ->
it 'should be true when it is earlier than the start time', ->
[start, end] = @user.activeHours()
time = moment(start).subtract(2, 'hours')
expect(@user.isInactive(time)).to.be.true
it 'should be true when it is later than the end time', ->
[start, end] = @user.activeHours()
time = moment(end).add(2, 'hours')
expect(@user.isInactive(time)).to.be.true
it 'should be false when it is in between the start and end time', ->
[start, end] = @user.activeHours()
time = moment(start).add(end.diff(start, 'hours') / 2, 'hours')
expect(@user.isInactive(time)).to.be.false
describe '#undoPunch()', ->
describe '#toRawPayroll(start, end)', ->
it 'should not return null', ->
payrollRow = @user.toRawPayroll()
expect(payrollRow).to.not.be.null
describe '#updateRow()', ->
describe '#description()', ->
it 'should return a description of the project for output', ->
description = @user.description()
expect(description).to.exist
|
[
{
"context": "nticationHandler = (req, res, next) ->\n token = 'EastIndiaCompany'\n timestamp = req.query['timestamp']\n nonce = r",
"end": 301,
"score": 0.9573272466659546,
"start": 285,
"tag": "PASSWORD",
"value": "EastIndiaCompany"
}
] | server/wechat/index.coffee | hotpxl/myap.ml | 1 | crypto = require 'crypto'
xml2js = require 'xml2js'
Q = require 'q'
utils = require '../utils'
database = require '../database'
logger = utils.logging.newConsoleLogger module.filename
redisConnection = database.getConnection()
authenticationHandler = (req, res, next) ->
token = 'EastIndiaCompany'
timestamp = req.query['timestamp']
nonce = req.query['nonce']
signature = req.query['signature']
echostr = req.query['echostr']
l = [token, timestamp, nonce].sort().join ''
shasum = crypto.createHash 'sha1'
shasum.update l
res.contentType = 'text'
if shasum.digest('hex') == signature
logger.debug 'authentication success'
res.send 200, echostr
else
logger.debug 'authentication failed'
res.send 200
echoHandler = (req, res, next) ->
logger.debug "request body #{req.body}"
Q.ninvoke xml2js, 'parseString', req.body
.then (parsed) ->
toUser = parsed.xml['FromUserName'][0]
fromUser = parsed.xml['ToUserName'][0]
createTime = (new Date()).getTime() // 1000
content = "echo #{parsed.xml['Content'][0]}"
ret = "
<xml>
<ToUserName><![CDATA[#{toUser}]]></ToUserName>
<FromUserName><![CDATA[#{fromUser}]]></FromUserName>
<CreateTime>#{createTime}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[#{content}]]></Content>
</xml>"
res.contentType = 'text'
res.send 200, ret
next()
.done()
rpcCall = (tag, payload, sendResponse) ->
if tag == 'echo'
sendResponse "echo #{payload.request}"
else if tag == 'login'
if payload.request.match /[^0-9a-z]/i
sendResponse 'only letters and digits allowed'
else
Q.ninvoke redisConnection, 'hset', 'login', payload.fromUser, payload.request
sendResponse 'OK'
else if tag == 'summary'
Q.ninvoke redisConnection, 'hget', 'login', payload.fromUser
.then (id) ->
logger.debug id
if not id
sendResponse 'please login first'
else
sendResponse "http://myap.ml/?id=#{id}"
.done()
else
sendResponse "invalid tag #{tag}"
rpcHandler = (req, res, next) ->
console.dir req.body
Q.ninvoke xml2js, 'parseString', req.body
.then (parsed) ->
fromUser = parsed.xml['FromUserName'][0]
toUser = parsed.xml['ToUserName'][0]
createTime = (new Date()).getTime() // 1000
sendResponse = (content) ->
ret = "
<xml>
<ToUserName><![CDATA[#{fromUser}]]></ToUserName>
<FromUserName><![CDATA[#{toUser}]]></FromUserName>
<CreateTime>#{createTime}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[#{content}]]></Content>
</xml>"
res.send 200, ret
next()
content = parsed.xml['Content'][0]
separatorIndex = content.indexOf ' '
if separatorIndex == 0
sendResponse 'invalid request'
else
if separatorIndex == -1
separatorIndex = content.length
tag = content[..separatorIndex - 1]
request = content[separatorIndex + 1..]
payload =
toUser: toUser
fromUser: fromUser
createTime: createTime
request: request
rpcCall tag, payload, sendResponse
.done()
exports.authenticationHandler = authenticationHandler
exports.echoHandler = echoHandler
exports.rpcHandler = rpcHandler
| 219948 | crypto = require 'crypto'
xml2js = require 'xml2js'
Q = require 'q'
utils = require '../utils'
database = require '../database'
logger = utils.logging.newConsoleLogger module.filename
redisConnection = database.getConnection()
authenticationHandler = (req, res, next) ->
token = '<PASSWORD>'
timestamp = req.query['timestamp']
nonce = req.query['nonce']
signature = req.query['signature']
echostr = req.query['echostr']
l = [token, timestamp, nonce].sort().join ''
shasum = crypto.createHash 'sha1'
shasum.update l
res.contentType = 'text'
if shasum.digest('hex') == signature
logger.debug 'authentication success'
res.send 200, echostr
else
logger.debug 'authentication failed'
res.send 200
echoHandler = (req, res, next) ->
logger.debug "request body #{req.body}"
Q.ninvoke xml2js, 'parseString', req.body
.then (parsed) ->
toUser = parsed.xml['FromUserName'][0]
fromUser = parsed.xml['ToUserName'][0]
createTime = (new Date()).getTime() // 1000
content = "echo #{parsed.xml['Content'][0]}"
ret = "
<xml>
<ToUserName><![CDATA[#{toUser}]]></ToUserName>
<FromUserName><![CDATA[#{fromUser}]]></FromUserName>
<CreateTime>#{createTime}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[#{content}]]></Content>
</xml>"
res.contentType = 'text'
res.send 200, ret
next()
.done()
rpcCall = (tag, payload, sendResponse) ->
if tag == 'echo'
sendResponse "echo #{payload.request}"
else if tag == 'login'
if payload.request.match /[^0-9a-z]/i
sendResponse 'only letters and digits allowed'
else
Q.ninvoke redisConnection, 'hset', 'login', payload.fromUser, payload.request
sendResponse 'OK'
else if tag == 'summary'
Q.ninvoke redisConnection, 'hget', 'login', payload.fromUser
.then (id) ->
logger.debug id
if not id
sendResponse 'please login first'
else
sendResponse "http://myap.ml/?id=#{id}"
.done()
else
sendResponse "invalid tag #{tag}"
rpcHandler = (req, res, next) ->
console.dir req.body
Q.ninvoke xml2js, 'parseString', req.body
.then (parsed) ->
fromUser = parsed.xml['FromUserName'][0]
toUser = parsed.xml['ToUserName'][0]
createTime = (new Date()).getTime() // 1000
sendResponse = (content) ->
ret = "
<xml>
<ToUserName><![CDATA[#{fromUser}]]></ToUserName>
<FromUserName><![CDATA[#{toUser}]]></FromUserName>
<CreateTime>#{createTime}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[#{content}]]></Content>
</xml>"
res.send 200, ret
next()
content = parsed.xml['Content'][0]
separatorIndex = content.indexOf ' '
if separatorIndex == 0
sendResponse 'invalid request'
else
if separatorIndex == -1
separatorIndex = content.length
tag = content[..separatorIndex - 1]
request = content[separatorIndex + 1..]
payload =
toUser: toUser
fromUser: fromUser
createTime: createTime
request: request
rpcCall tag, payload, sendResponse
.done()
exports.authenticationHandler = authenticationHandler
exports.echoHandler = echoHandler
exports.rpcHandler = rpcHandler
| true | crypto = require 'crypto'
xml2js = require 'xml2js'
Q = require 'q'
utils = require '../utils'
database = require '../database'
logger = utils.logging.newConsoleLogger module.filename
redisConnection = database.getConnection()
authenticationHandler = (req, res, next) ->
token = 'PI:PASSWORD:<PASSWORD>END_PI'
timestamp = req.query['timestamp']
nonce = req.query['nonce']
signature = req.query['signature']
echostr = req.query['echostr']
l = [token, timestamp, nonce].sort().join ''
shasum = crypto.createHash 'sha1'
shasum.update l
res.contentType = 'text'
if shasum.digest('hex') == signature
logger.debug 'authentication success'
res.send 200, echostr
else
logger.debug 'authentication failed'
res.send 200
echoHandler = (req, res, next) ->
logger.debug "request body #{req.body}"
Q.ninvoke xml2js, 'parseString', req.body
.then (parsed) ->
toUser = parsed.xml['FromUserName'][0]
fromUser = parsed.xml['ToUserName'][0]
createTime = (new Date()).getTime() // 1000
content = "echo #{parsed.xml['Content'][0]}"
ret = "
<xml>
<ToUserName><![CDATA[#{toUser}]]></ToUserName>
<FromUserName><![CDATA[#{fromUser}]]></FromUserName>
<CreateTime>#{createTime}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[#{content}]]></Content>
</xml>"
res.contentType = 'text'
res.send 200, ret
next()
.done()
rpcCall = (tag, payload, sendResponse) ->
if tag == 'echo'
sendResponse "echo #{payload.request}"
else if tag == 'login'
if payload.request.match /[^0-9a-z]/i
sendResponse 'only letters and digits allowed'
else
Q.ninvoke redisConnection, 'hset', 'login', payload.fromUser, payload.request
sendResponse 'OK'
else if tag == 'summary'
Q.ninvoke redisConnection, 'hget', 'login', payload.fromUser
.then (id) ->
logger.debug id
if not id
sendResponse 'please login first'
else
sendResponse "http://myap.ml/?id=#{id}"
.done()
else
sendResponse "invalid tag #{tag}"
rpcHandler = (req, res, next) ->
console.dir req.body
Q.ninvoke xml2js, 'parseString', req.body
.then (parsed) ->
fromUser = parsed.xml['FromUserName'][0]
toUser = parsed.xml['ToUserName'][0]
createTime = (new Date()).getTime() // 1000
sendResponse = (content) ->
ret = "
<xml>
<ToUserName><![CDATA[#{fromUser}]]></ToUserName>
<FromUserName><![CDATA[#{toUser}]]></FromUserName>
<CreateTime>#{createTime}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[#{content}]]></Content>
</xml>"
res.send 200, ret
next()
content = parsed.xml['Content'][0]
separatorIndex = content.indexOf ' '
if separatorIndex == 0
sendResponse 'invalid request'
else
if separatorIndex == -1
separatorIndex = content.length
tag = content[..separatorIndex - 1]
request = content[separatorIndex + 1..]
payload =
toUser: toUser
fromUser: fromUser
createTime: createTime
request: request
rpcCall tag, payload, sendResponse
.done()
exports.authenticationHandler = authenticationHandler
exports.echoHandler = echoHandler
exports.rpcHandler = rpcHandler
|
[
{
"context": "/pothibo.testing.s3.amazonaws.com',\n accessKey: 'AKIAIW6GIE2SUPSM6XLQ',\n policy: 'eyJleHBpcmF0aW9uIjoiMjAyMC0wMS0wMVQw",
"end": 102,
"score": 0.999678373336792,
"start": 82,
"tag": "KEY",
"value": "AKIAIW6GIE2SUPSM6XLQ"
},
{
"context": ",\n accessKey: 'AKIAIW6GIE2S... | test/server/app/assets/javascripts/secret.coffee | 418sec/written | 15 | window.AWS = {
bucket: 'http://pothibo.testing.s3.amazonaws.com',
accessKey: 'AKIAIW6GIE2SUPSM6XLQ',
policy: 'eyJleHBpcmF0aW9uIjoiMjAyMC0wMS0wMVQwMDowMDowMFoiLCJjb25kaXRpb25zIjpbeyJidWNrZXQiOiJwb3RoaWJvLnRlc3RpbmcifSxbInN0YXJ0cy13aXRoIiwiJGtleSIsIiJdLHsiYWNsIjoicHJpdmF0ZSJ9LFsic3RhcnRzLXdpdGgiLCIkQ29udGVudC1UeXBlIiwiIl0sWyJjb250ZW50LWxlbmd0aC1yYW5nZSIsMCw1MjQyODgwXV19',
signature: 'oxZtTxMsEZRER2nNcNqT1YPNaDo='
}
| 24714 | window.AWS = {
bucket: 'http://pothibo.testing.s3.amazonaws.com',
accessKey: '<KEY>',
policy: '<KEY>',
signature: 'oxZtTxMsEZRER2nNcNqT1YPNaDo='
}
| true | window.AWS = {
bucket: 'http://pothibo.testing.s3.amazonaws.com',
accessKey: 'PI:KEY:<KEY>END_PI',
policy: 'PI:KEY:<KEY>END_PI',
signature: 'oxZtTxMsEZRER2nNcNqT1YPNaDo='
}
|
[
{
"context": "ent({\n \"server\": \"production\"\n \"projectToken\": \"serengeti\"\n \"zooUserIDGetter\": checkZooUserID\n \"subjectGe",
"end": 368,
"score": 0.9955518245697021,
"start": 359,
"tag": "PASSWORD",
"value": "serengeti"
}
] | app/lib/geordi_and_experiments_setup.coffee | zooniverse/Serengeti | 8 | ExperimentServerClient = require 'lib/experiments'
Subject = require 'models/subject'
User = require 'Zooniverse/lib/models/user'
GeordiClient = require 'zooniverse-geordi-client'
checkZooUserID = ->
User.current?.zooniverse_id
checkZooSubject = ->
Subject.current?.zooniverseId
Geordi = new GeordiClient({
"server": "production"
"projectToken": "serengeti"
"zooUserIDGetter": checkZooUserID
"subjectGetter": checkZooSubject
})
ExperimentServer = new ExperimentServerClient(Geordi)
Geordi.experimentServerClient = ExperimentServer
module.exports = Geordi
| 137130 | ExperimentServerClient = require 'lib/experiments'
Subject = require 'models/subject'
User = require 'Zooniverse/lib/models/user'
GeordiClient = require 'zooniverse-geordi-client'
checkZooUserID = ->
User.current?.zooniverse_id
checkZooSubject = ->
Subject.current?.zooniverseId
Geordi = new GeordiClient({
"server": "production"
"projectToken": "<PASSWORD>"
"zooUserIDGetter": checkZooUserID
"subjectGetter": checkZooSubject
})
ExperimentServer = new ExperimentServerClient(Geordi)
Geordi.experimentServerClient = ExperimentServer
module.exports = Geordi
| true | ExperimentServerClient = require 'lib/experiments'
Subject = require 'models/subject'
User = require 'Zooniverse/lib/models/user'
GeordiClient = require 'zooniverse-geordi-client'
checkZooUserID = ->
User.current?.zooniverse_id
checkZooSubject = ->
Subject.current?.zooniverseId
Geordi = new GeordiClient({
"server": "production"
"projectToken": "PI:PASSWORD:<PASSWORD>END_PI"
"zooUserIDGetter": checkZooUserID
"subjectGetter": checkZooSubject
})
ExperimentServer = new ExperimentServerClient(Geordi)
Geordi.experimentServerClient = ExperimentServer
module.exports = Geordi
|
[
{
"context": "gs Notifications (assets)\nProject: Waaave\nAuthors: Julien Le Coupanec, Valerian Saliou\nCopyright: 2014, Waaave\n###\n\n__ ",
"end": 95,
"score": 0.9998618364334106,
"start": 77,
"tag": "NAME",
"value": "Julien Le Coupanec"
},
{
"context": "sets)\nProject: Waaave\nAut... | static/src/assets/account/javascripts/account_settings_notifications.coffee | valeriansaliou/waaave-web | 1 | ###
Bundle: Account Settings Notifications (assets)
Project: Waaave
Authors: Julien Le Coupanec, Valerian Saliou
Copyright: 2014, Waaave
###
__ = window
class AccountSettingsNotifications
init: ->
try
# Selectors
@_window_sel = $ window
@_document_sel = $ document
@_body_sel = @_document_sel.find '.body'
@_notification_center_sel = @_body_sel.find '.notification-center'
@_items_sel = @_notification_center_sel.find '.items'
@_load_more_btn_sel = @_notification_center_sel.find '.show-more'
# Variables
@_times_auto_loaded = 0
# States
@_is_fetching = false
catch error
Console.error 'AccountSettingsNotifications.init', error
event_fetch_page: ->
try
self = @
@_load_more_btn_sel.find('a.more').click ->
self._fetch_page()
return false
@_window_sel.scroll ->
if (self._load_more_btn_sel isnt null and self._is_fetching isnt true and self._times_auto_loaded < 2) and
(self._window_sel.scrollTop() >= self._body_sel.height() - self._window_sel.height())
self._times_auto_loaded++
self._fetch_page()
catch error
Console.error 'AccountSettingsNotifications.event_fetch_page', error
_fetch_page: ->
try
self = @
if @_load_more_btn_sel is null
Console.warn 'AccountSettingsNotifications._fetch_page', 'Nothing more to load...'
return false
if @_is_fetching is true
Console.info 'AccountSettingsNotifications._fetch_page', 'Already fetching data!'
return false
@_is_fetching = true
load_more_url = @_load_more_btn_sel.attr 'data-url'
if not load_more_url
Console.warn 'AccountSettingsNotifications._fetch_page', 'Looks like there is nothing to load!'
return false
@_load_more_btn_sel.addClass 'loading'
page_id = LayoutPage.get_id()
$.get(
load_more_url,
(data) ->
if page_id isnt LayoutPage.get_id()
return
data_sel = $ data
if (data_sel.is '.notifications')
data_items_sel = data_sel.find '.items'
data_more_btn_sel = data_sel.find '.show-more'
data_page_end_sel = data_sel.find '.page-end'
if data_items_sel.size()
self._items_sel.append data_items_sel
if data_more_btn_sel.size()
self._load_more_btn_sel.replaceWith data_more_btn_sel
self._load_more_btn_sel = data_more_btn_sel
self.event_fetch_page()
self._load_more_btn_sel.removeClass 'loading'
self._is_fetching = false
else
self._load_more_btn_sel.replaceWith data_page_end_sel
self._load_more_btn_sel = null
else
self._load_more_btn_sel.replaceWith data_page_end_sel
else
Console.error 'AccountSettingsNotifications._fetch_page[async]', "#{data.status}:#{data.message}"
# Notify async system that DOM has been updated
LayoutPage.fire_dom_updated()
)
catch error
Console.error 'AccountSettingsNotifications._fetch_page', error
finally
return false
@AccountSettingsNotifications = new AccountSettingsNotifications
$(document).ready ->
__.AccountSettingsNotifications.init()
__.AccountSettingsNotifications.event_fetch_page()
LayoutRegistry.register_bundle 'AccountSettingsNotifications'
| 206543 | ###
Bundle: Account Settings Notifications (assets)
Project: Waaave
Authors: <NAME>, <NAME>
Copyright: 2014, Waaave
###
__ = window
class AccountSettingsNotifications
init: ->
try
# Selectors
@_window_sel = $ window
@_document_sel = $ document
@_body_sel = @_document_sel.find '.body'
@_notification_center_sel = @_body_sel.find '.notification-center'
@_items_sel = @_notification_center_sel.find '.items'
@_load_more_btn_sel = @_notification_center_sel.find '.show-more'
# Variables
@_times_auto_loaded = 0
# States
@_is_fetching = false
catch error
Console.error 'AccountSettingsNotifications.init', error
event_fetch_page: ->
try
self = @
@_load_more_btn_sel.find('a.more').click ->
self._fetch_page()
return false
@_window_sel.scroll ->
if (self._load_more_btn_sel isnt null and self._is_fetching isnt true and self._times_auto_loaded < 2) and
(self._window_sel.scrollTop() >= self._body_sel.height() - self._window_sel.height())
self._times_auto_loaded++
self._fetch_page()
catch error
Console.error 'AccountSettingsNotifications.event_fetch_page', error
_fetch_page: ->
try
self = @
if @_load_more_btn_sel is null
Console.warn 'AccountSettingsNotifications._fetch_page', 'Nothing more to load...'
return false
if @_is_fetching is true
Console.info 'AccountSettingsNotifications._fetch_page', 'Already fetching data!'
return false
@_is_fetching = true
load_more_url = @_load_more_btn_sel.attr 'data-url'
if not load_more_url
Console.warn 'AccountSettingsNotifications._fetch_page', 'Looks like there is nothing to load!'
return false
@_load_more_btn_sel.addClass 'loading'
page_id = LayoutPage.get_id()
$.get(
load_more_url,
(data) ->
if page_id isnt LayoutPage.get_id()
return
data_sel = $ data
if (data_sel.is '.notifications')
data_items_sel = data_sel.find '.items'
data_more_btn_sel = data_sel.find '.show-more'
data_page_end_sel = data_sel.find '.page-end'
if data_items_sel.size()
self._items_sel.append data_items_sel
if data_more_btn_sel.size()
self._load_more_btn_sel.replaceWith data_more_btn_sel
self._load_more_btn_sel = data_more_btn_sel
self.event_fetch_page()
self._load_more_btn_sel.removeClass 'loading'
self._is_fetching = false
else
self._load_more_btn_sel.replaceWith data_page_end_sel
self._load_more_btn_sel = null
else
self._load_more_btn_sel.replaceWith data_page_end_sel
else
Console.error 'AccountSettingsNotifications._fetch_page[async]', "#{data.status}:#{data.message}"
# Notify async system that DOM has been updated
LayoutPage.fire_dom_updated()
)
catch error
Console.error 'AccountSettingsNotifications._fetch_page', error
finally
return false
@AccountSettingsNotifications = new AccountSettingsNotifications
$(document).ready ->
__.AccountSettingsNotifications.init()
__.AccountSettingsNotifications.event_fetch_page()
LayoutRegistry.register_bundle 'AccountSettingsNotifications'
| true | ###
Bundle: Account Settings Notifications (assets)
Project: Waaave
Authors: PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
Copyright: 2014, Waaave
###
__ = window
class AccountSettingsNotifications
init: ->
try
# Selectors
@_window_sel = $ window
@_document_sel = $ document
@_body_sel = @_document_sel.find '.body'
@_notification_center_sel = @_body_sel.find '.notification-center'
@_items_sel = @_notification_center_sel.find '.items'
@_load_more_btn_sel = @_notification_center_sel.find '.show-more'
# Variables
@_times_auto_loaded = 0
# States
@_is_fetching = false
catch error
Console.error 'AccountSettingsNotifications.init', error
event_fetch_page: ->
try
self = @
@_load_more_btn_sel.find('a.more').click ->
self._fetch_page()
return false
@_window_sel.scroll ->
if (self._load_more_btn_sel isnt null and self._is_fetching isnt true and self._times_auto_loaded < 2) and
(self._window_sel.scrollTop() >= self._body_sel.height() - self._window_sel.height())
self._times_auto_loaded++
self._fetch_page()
catch error
Console.error 'AccountSettingsNotifications.event_fetch_page', error
_fetch_page: ->
try
self = @
if @_load_more_btn_sel is null
Console.warn 'AccountSettingsNotifications._fetch_page', 'Nothing more to load...'
return false
if @_is_fetching is true
Console.info 'AccountSettingsNotifications._fetch_page', 'Already fetching data!'
return false
@_is_fetching = true
load_more_url = @_load_more_btn_sel.attr 'data-url'
if not load_more_url
Console.warn 'AccountSettingsNotifications._fetch_page', 'Looks like there is nothing to load!'
return false
@_load_more_btn_sel.addClass 'loading'
page_id = LayoutPage.get_id()
$.get(
load_more_url,
(data) ->
if page_id isnt LayoutPage.get_id()
return
data_sel = $ data
if (data_sel.is '.notifications')
data_items_sel = data_sel.find '.items'
data_more_btn_sel = data_sel.find '.show-more'
data_page_end_sel = data_sel.find '.page-end'
if data_items_sel.size()
self._items_sel.append data_items_sel
if data_more_btn_sel.size()
self._load_more_btn_sel.replaceWith data_more_btn_sel
self._load_more_btn_sel = data_more_btn_sel
self.event_fetch_page()
self._load_more_btn_sel.removeClass 'loading'
self._is_fetching = false
else
self._load_more_btn_sel.replaceWith data_page_end_sel
self._load_more_btn_sel = null
else
self._load_more_btn_sel.replaceWith data_page_end_sel
else
Console.error 'AccountSettingsNotifications._fetch_page[async]', "#{data.status}:#{data.message}"
# Notify async system that DOM has been updated
LayoutPage.fire_dom_updated()
)
catch error
Console.error 'AccountSettingsNotifications._fetch_page', error
finally
return false
@AccountSettingsNotifications = new AccountSettingsNotifications
$(document).ready ->
__.AccountSettingsNotifications.init()
__.AccountSettingsNotifications.event_fetch_page()
LayoutRegistry.register_bundle 'AccountSettingsNotifications'
|
[
{
"context": "###\nmac-open\nhttps://github.com/weareinteractive/node-mac-open\n\nCopyright (c) 2013 We Are Interact",
"end": 48,
"score": 0.9995918273925781,
"start": 32,
"tag": "USERNAME",
"value": "weareinteractive"
},
{
"context": "weareinteractive/node-mac-open\n\nCopyright (c) ... | Gruntfile.coffee | gndgn/node-mac-open | 5 | ###
mac-open
https://github.com/weareinteractive/node-mac-open
Copyright (c) 2013 We Are Interactive
Licensed under the MIT license.
###
"use strict"
module.exports = (grunt) ->
# Project configuration.
grunt.initConfig
pkg: grunt.file.readJSON "package.json"
coffeelint:
files: ["Gruntfile.coffee", "src/**/*.coffee", "test/**/*.coffee"]
options:
max_line_length:
value: 200
level: "error"
coffee:
lib:
files:
"lib/<%= pkg.name %>.js": "src/<%= pkg.name %>.coffee"
# Unit tests.
mochacov:
options:
bail: true
ui: 'exports'
require: 'coffee-script'
compilers: ['coffee:coffee-script/register']
files: 'test/specs/**/*.coffee'
test:
options:
reporter: 'spec'
coverage:
options:
coveralls: true
htmlcoverage:
options:
reporter: 'html-cov'
output: 'test/coverage.html'
# Deployment
bumper:
options:
push: false
createTag: false
tasks: ["default"]
files: ["package.json"]
updateConfigs: ["pkg"]
# Load npm tasks.
grunt.loadNpmTasks "grunt-mocha-cov"
grunt.loadNpmTasks "grunt-coffeelint"
grunt.loadNpmTasks "grunt-contrib-coffee"
grunt.loadNpmTasks "grunt-bumper"
# Default task.
grunt.registerTask "default", ["coffeelint", "coffee"]
grunt.registerTask "test", ["default", "mochacov:test", "mochacov:htmlcoverage"]
grunt.registerTask "test:travis", ["default", "mochacov:test","mochacov:coverage"]
| 6053 | ###
mac-open
https://github.com/weareinteractive/node-mac-open
Copyright (c) 2013 <NAME>
Licensed under the MIT license.
###
"use strict"
module.exports = (grunt) ->
# Project configuration.
grunt.initConfig
pkg: grunt.file.readJSON "package.json"
coffeelint:
files: ["Gruntfile.coffee", "src/**/*.coffee", "test/**/*.coffee"]
options:
max_line_length:
value: 200
level: "error"
coffee:
lib:
files:
"lib/<%= pkg.name %>.js": "src/<%= pkg.name %>.coffee"
# Unit tests.
mochacov:
options:
bail: true
ui: 'exports'
require: 'coffee-script'
compilers: ['coffee:coffee-script/register']
files: 'test/specs/**/*.coffee'
test:
options:
reporter: 'spec'
coverage:
options:
coveralls: true
htmlcoverage:
options:
reporter: 'html-cov'
output: 'test/coverage.html'
# Deployment
bumper:
options:
push: false
createTag: false
tasks: ["default"]
files: ["package.json"]
updateConfigs: ["pkg"]
# Load npm tasks.
grunt.loadNpmTasks "grunt-mocha-cov"
grunt.loadNpmTasks "grunt-coffeelint"
grunt.loadNpmTasks "grunt-contrib-coffee"
grunt.loadNpmTasks "grunt-bumper"
# Default task.
grunt.registerTask "default", ["coffeelint", "coffee"]
grunt.registerTask "test", ["default", "mochacov:test", "mochacov:htmlcoverage"]
grunt.registerTask "test:travis", ["default", "mochacov:test","mochacov:coverage"]
| true | ###
mac-open
https://github.com/weareinteractive/node-mac-open
Copyright (c) 2013 PI:NAME:<NAME>END_PI
Licensed under the MIT license.
###
"use strict"
module.exports = (grunt) ->
# Project configuration.
grunt.initConfig
pkg: grunt.file.readJSON "package.json"
coffeelint:
files: ["Gruntfile.coffee", "src/**/*.coffee", "test/**/*.coffee"]
options:
max_line_length:
value: 200
level: "error"
coffee:
lib:
files:
"lib/<%= pkg.name %>.js": "src/<%= pkg.name %>.coffee"
# Unit tests.
mochacov:
options:
bail: true
ui: 'exports'
require: 'coffee-script'
compilers: ['coffee:coffee-script/register']
files: 'test/specs/**/*.coffee'
test:
options:
reporter: 'spec'
coverage:
options:
coveralls: true
htmlcoverage:
options:
reporter: 'html-cov'
output: 'test/coverage.html'
# Deployment
bumper:
options:
push: false
createTag: false
tasks: ["default"]
files: ["package.json"]
updateConfigs: ["pkg"]
# Load npm tasks.
grunt.loadNpmTasks "grunt-mocha-cov"
grunt.loadNpmTasks "grunt-coffeelint"
grunt.loadNpmTasks "grunt-contrib-coffee"
grunt.loadNpmTasks "grunt-bumper"
# Default task.
grunt.registerTask "default", ["coffeelint", "coffee"]
grunt.registerTask "test", ["default", "mochacov:test", "mochacov:htmlcoverage"]
grunt.registerTask "test:travis", ["default", "mochacov:test","mochacov:coverage"]
|
[
{
"context": "l\n\n beforeEach ->\n options =\n value : 'Fatih Acet'\n name : 'name'\n\n textarea = new spark.",
"end": 267,
"score": 0.9988500475883484,
"start": 257,
"tag": "NAME",
"value": "Fatih Acet"
}
] | src/tests/components/textarea/test_textareaWithCharCounter.coffee | dashersw/spark | 1 | goog = goog or goog = require: ->
goog.require 'spark.components.TextareaWithCharCounter'
goog.require 'spark.components.Textarea'
describe 'spark.components.TextareaWithCharCounter', ->
textarea = null
beforeEach ->
options =
value : 'Fatih Acet'
name : 'name'
textarea = new spark.components.TextareaWithCharCounter options
afterEach ->
textarea.destroy()
it 'should extends spark.components.Textarea', ->
expect(textarea instanceof spark.components.Textarea).toBeTruthy()
it 'should have default options', ->
if goog.debug
textarea = new spark.components.TextareaWithCharCounter
{charLimit, counterContainer} = textarea.getOptions()
expect(charLimit).toBe 140
expect(counterContainer).toBe document.body
it 'should have char counter', ->
counterView = textarea.getCounterView()
counterEl = counterView.getElement()
expect(counterView).toBeDefined()
expect(counterView instanceof spark.core.View).toBeTruthy()
expect(counterEl.innerHTML).toBe '130'
textarea.setValue 'fatih'
expect(counterEl.innerHTML).toBe '135'
it 'should truncate the content by char limit', ->
textarea = new spark.components.TextareaWithCharCounter
charLimit : 10
textarea.setValue 'hello world this is long'
expect(textarea.getValue()).toBe 'hello worl'
it 'should have hidden counter', ->
textarea = new spark.components.TextareaWithCharCounter
isCounterVisible: no
expect(textarea.getCounterView().hasClass 'hidden').toBeTruthy()
it 'should show incremental count on counter', ->
textarea = new spark.components.TextareaWithCharCounter
showRemainingCount: no
value: 'lorem ipsum dolor'
expect(textarea.getCounterView().getElement().innerHTML).toBe '17'
it 'should set/update char limit', ->
textarea = new spark.components.TextareaWithCharCounter
charLimit: 20
value: 'lorem ipsum dolor'
counterEl = textarea.getCounterView().getElement()
expect(counterEl.innerHTML).toBe '3'
textarea.setCharLimit 10
expect(counterEl.innerHTML).toBe '0'
expect(textarea.getValue()).toBe 'lorem ipsu'
textarea.setCharLimit 50
textarea.setValue 'lorem ipsum dolor sit amet'
expect(counterEl.innerHTML).toBe '24'
expect(textarea.getValue()).toBe 'lorem ipsum dolor sit amet'
| 183963 | goog = goog or goog = require: ->
goog.require 'spark.components.TextareaWithCharCounter'
goog.require 'spark.components.Textarea'
describe 'spark.components.TextareaWithCharCounter', ->
textarea = null
beforeEach ->
options =
value : '<NAME>'
name : 'name'
textarea = new spark.components.TextareaWithCharCounter options
afterEach ->
textarea.destroy()
it 'should extends spark.components.Textarea', ->
expect(textarea instanceof spark.components.Textarea).toBeTruthy()
it 'should have default options', ->
if goog.debug
textarea = new spark.components.TextareaWithCharCounter
{charLimit, counterContainer} = textarea.getOptions()
expect(charLimit).toBe 140
expect(counterContainer).toBe document.body
it 'should have char counter', ->
counterView = textarea.getCounterView()
counterEl = counterView.getElement()
expect(counterView).toBeDefined()
expect(counterView instanceof spark.core.View).toBeTruthy()
expect(counterEl.innerHTML).toBe '130'
textarea.setValue 'fatih'
expect(counterEl.innerHTML).toBe '135'
it 'should truncate the content by char limit', ->
textarea = new spark.components.TextareaWithCharCounter
charLimit : 10
textarea.setValue 'hello world this is long'
expect(textarea.getValue()).toBe 'hello worl'
it 'should have hidden counter', ->
textarea = new spark.components.TextareaWithCharCounter
isCounterVisible: no
expect(textarea.getCounterView().hasClass 'hidden').toBeTruthy()
it 'should show incremental count on counter', ->
textarea = new spark.components.TextareaWithCharCounter
showRemainingCount: no
value: 'lorem ipsum dolor'
expect(textarea.getCounterView().getElement().innerHTML).toBe '17'
it 'should set/update char limit', ->
textarea = new spark.components.TextareaWithCharCounter
charLimit: 20
value: 'lorem ipsum dolor'
counterEl = textarea.getCounterView().getElement()
expect(counterEl.innerHTML).toBe '3'
textarea.setCharLimit 10
expect(counterEl.innerHTML).toBe '0'
expect(textarea.getValue()).toBe 'lorem ipsu'
textarea.setCharLimit 50
textarea.setValue 'lorem ipsum dolor sit amet'
expect(counterEl.innerHTML).toBe '24'
expect(textarea.getValue()).toBe 'lorem ipsum dolor sit amet'
| true | goog = goog or goog = require: ->
goog.require 'spark.components.TextareaWithCharCounter'
goog.require 'spark.components.Textarea'
describe 'spark.components.TextareaWithCharCounter', ->
textarea = null
beforeEach ->
options =
value : 'PI:NAME:<NAME>END_PI'
name : 'name'
textarea = new spark.components.TextareaWithCharCounter options
afterEach ->
textarea.destroy()
it 'should extends spark.components.Textarea', ->
expect(textarea instanceof spark.components.Textarea).toBeTruthy()
it 'should have default options', ->
if goog.debug
textarea = new spark.components.TextareaWithCharCounter
{charLimit, counterContainer} = textarea.getOptions()
expect(charLimit).toBe 140
expect(counterContainer).toBe document.body
it 'should have char counter', ->
counterView = textarea.getCounterView()
counterEl = counterView.getElement()
expect(counterView).toBeDefined()
expect(counterView instanceof spark.core.View).toBeTruthy()
expect(counterEl.innerHTML).toBe '130'
textarea.setValue 'fatih'
expect(counterEl.innerHTML).toBe '135'
it 'should truncate the content by char limit', ->
textarea = new spark.components.TextareaWithCharCounter
charLimit : 10
textarea.setValue 'hello world this is long'
expect(textarea.getValue()).toBe 'hello worl'
it 'should have hidden counter', ->
textarea = new spark.components.TextareaWithCharCounter
isCounterVisible: no
expect(textarea.getCounterView().hasClass 'hidden').toBeTruthy()
it 'should show incremental count on counter', ->
textarea = new spark.components.TextareaWithCharCounter
showRemainingCount: no
value: 'lorem ipsum dolor'
expect(textarea.getCounterView().getElement().innerHTML).toBe '17'
it 'should set/update char limit', ->
textarea = new spark.components.TextareaWithCharCounter
charLimit: 20
value: 'lorem ipsum dolor'
counterEl = textarea.getCounterView().getElement()
expect(counterEl.innerHTML).toBe '3'
textarea.setCharLimit 10
expect(counterEl.innerHTML).toBe '0'
expect(textarea.getValue()).toBe 'lorem ipsu'
textarea.setCharLimit 50
textarea.setValue 'lorem ipsum dolor sit amet'
expect(counterEl.innerHTML).toBe '24'
expect(textarea.getValue()).toBe 'lorem ipsum dolor sit amet'
|
[
{
"context": "js\n\n PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.",
"end": 215,
"score": 0.9998329281806946,
"start": 198,
"tag": "NAME",
"value": "Benjamin Blundell"
},
{
"context": " PXL.js\n ... | src/util/medial_axis.coffee | OniDaito/pxljs | 1 | ###
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
Benjamin Blundell - ben@pxljs.com
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
###
{Vec2,Edge2,Parabola} = require '../math/math'
{edge2Bisector} = require '../math/math_functions'
class MedialComponent
# Start and end are Vec2 points and the @component is either an edge or a
constructor : (@start, @end) ->
@
class MedialComponentEdge extends MedialComponent
constructor : (@edge) ->
@
# a value of 0 - 1 that samples between start and end
sample : (dt) ->
dx = ((@end.x - @start.x) * dt) + @start.x
@edge.sample(dx)
class MedialComponentParabola extends MedialComponent
constructor : (@parabola) ->
@
sample : (dt) ->
dx = ((@end.x - @start.x) * dt) + @start.x
dy = ((@end.y - @start.y) * dt) + @start.y
# Basically find the nearest y value to DY - not sure that is totally correct though :S
[y0,y1] = @parabola.sample(dx)
if y1 != y0
if Math.abs(y0 - dy) < Math.abs(y1-dy)
return y0
else
return y1
y0
class MedialGraph
constructor : ->
@components = []
@right_handed = true
# Compute the voronoi graph for two joined edges
voronoiEdgeEdge : (edge0, edge1) ->
bisector = edge2Bisector edge0, edge1
# As the bisector will only be for edges with angles less than 180, we can assume the shortest
# edge is the one that will be crossed first
# for now, we consider a
short_edge = edge1
long_edge = edge0
if edge0.length() < edge1.length()
short_edge = edge0
long_edge = edge1
[knot_point, influence_point] = @edgeLineInfluence bisector, short_edge, @right_handed
parta = new Edge2 bisector.start, knot_point
@components.push new MedialComponentEdge parta
[a,b,c] = long_edge.equation()
# TODO - how do we know which parabola result to choose?
parabola = new Parabola(influence_point,a,b,c)
cp = @edgeParabolaInfluence(parabola,long_edge,@right_handed)
parabola
# Function that determines where a parabola leaves the area of influence of an edge.
# Takes the line in the form ax + by + c = 0
edgeParabolaInfluence : (parabola, edge, right) ->
[ea,eb,ec] = edge.equation()
psa = eb
psb = -ea
psc = ea * edge.start.x + eb * edge.start.y + ec - eb * edge.start.x + ea * edge.start.y
pea = eb
peb = -ea
pec = ea * edge.end.x + eb * edge.end.y + ec - eb * edge.end.x + ea * edge.end.y
# two lines gives potentially 4 crossing points
[s0,s1] = parabola.lineCrossing(psa,psb,psc)
[e0,e1] = parabola.lineCrossing(pea,peb,pec)
#console.log psa,psb,psc
#console.log parabola.f, parabola.a, parabola.b, parabola.c
console.log s0,s1
console.log e0,e1
spoints = [Vec2.normalize(s0), Vec2.normalize(s1)]
epoints = [Vec2.normalize(e0), Vec2.normalize(e1)]
tt = Vec2.normalize edge.start
rp = []
for point in spoints
if right
if tt.dot(point) > 0
rp.push([point, edge.start])
else if tt.dot(point) <= 0
rp.push([point, edge.start])
for point in epoints
if right
if tt.dot(point) > 0
rp.push([point, edge.end])
else if tt.dot(point) <= 0
rp.push([point, edge.end])
rp
# Function that determines where a line equation leaves the area of influence of an edge
# Takes the line in the form ax + by + c = 0
edgeLineInfluence : (line,edge,right) ->
# Get the equations of the lines perpendicular to edge, passing through the end points
[ea,eb,ec] = edge.equation()
[a,b,c] = line.equation()
psa = eb
psb = -ea
psc = ea * edge.start.x + eb * edge.start.y + ec - eb * edge.start.x + ea * edge.start.y
pea = eb
peb = -ea
pec = ea * edge.end.x + eb * edge.end.y + ec - eb * edge.end.x + ea * edge.end.y
# find the intersection (hopefully they are not parallel lines :S )
# We should have a determinate that is non-zero right?
ys = (psa * c - psc * a) / (a * psb - psa * b)
xs = (-b * ys - c) / a
start_cross = new Vec2(xs,ys)
ye = (pea * c - pec * a) / (a * peb - pea * b)
xe = (-b * ye - c) / a
end_cross = new Vec2(xe,ye)
# We consider only one side of the edge, depending on whether left or right is true
ts = Vec2.normalize start_cross
tt = Vec2.normalize edge.start
ts.normalize()
tt.normalize()
if right
if tt.dot(ts) > 0
return [end_cross, edge.end]
else
return [start_cross, edge.start]
if tt.dot(ts) <= 0
return [start_cross, edge.start]
[end_cross, edge.end]
# ## medialAxis2D
# Given a planar polygon (a list of 2D vertices), compute the the medial axis of the polygon
# as a set of pairs of 2D points (edges)
medialAxis2D = (polygon, top, left, bottom, right) ->
# create pairs / edges
if polygon.length < 3
return []
edges = []
for idx in [0..polygon.length-1]
if idx + 1 < polygon.length
edges.push [ polygon[idx], polygon[idx+1] ]
else
edges.push [ polygon[idx], polygon[0] ]
# find the chains - As we are going clockwise winding, inside is to the right of the vector
# which is a positive cross product with z ( I think!)
chains = []
current_chain = new Array()
for idx in [0..edges.length-1]
e0 = edges[idx]
e1 = edges[idx+1]
if idx + 1 == edges.length
e1 = edges[0]
v0 = Vec3.sub new Vec3(e0[1].x, e0[1].y), new Vec3(e0[0].x, e0[0].y)
v1 = Vec3.sub new Vec3(e1[1].x, e1[1].y), new Vec3(e1[0].x, e1[0].y)
cross = Vec3.cross v0, v1
if cross.z > 0
# Its a reflex angle, therefore a chain
if current_chain.length == 0
current_chain.push e0
current_chain.push [e1[0]] # push the reflex vertex too if chain is greater than one edge
current_chain.push e1
# there is an edge case here whereby the last edge could be in a chain already
# but I suspect that is rare and can be handled anyway
else
# not a chain
if current_chain.length == 0
current_chain.push e0
chains.push current_chain
current_chain = new Array()
voronoi = []
wedges = []
zaxis = new Vec3(0,0,1)
wedge_length =100.0
# we now have the chains so we must compute the voronoi diagram for each chain and combine
for chain in chains
for idx in [0..chain.length-1]
# Wedges denote the area of effect for computing our initial bisectors.
# They are internal and are denoted by a point and a direction vector.
# Each element has two lines that denote a wedge and we want to be inside them
element = chain[idx]
wedge = []
# compute the initial voronoi graph. The wedges for each element
if element.length == 2
# its an edge so two lines perpendicular
v0 = Vec3.sub new Vec3(element[0].x, element[0].y), new Vec3(element[1].x, element[1].y)
cross = Vec3.cross v0, zaxis
cross.normalize()
wedge.push [new Vec2(element[0].x, element[0].y), new Vec2(element[0].x - cross.x, element[0].y - cross.y)]
wedge.push [new Vec2(element[1].x, element[1].y), new Vec2(element[1].x - cross.x, element[1].y - cross.y)]
else
# Its a reflex point so two lines perpendicular to the edges that join it
p = idx - 1
if idx == 0
p = chain.length - 1
n = idx + 1
if idx == chain.length - 1
n = 0
pe = chain[p]
ne = chain[n]
v0 = Vec3.sub new Vec3(pe[0].x, pe[0].y), new Vec3(pe[1].x, pe[1].y)
cross = Vec3.cross v0, zaxis
cross.normalize()
wedge.push [new Vec2(element[0].x, element[0].y), new Vec2(element[0].x - cross.x, element[0].y - cross.y)]
v1 = Vec3.sub new Vec3(ne[0].x, ne[0].y), new Vec3(ne[1].x, ne[1].y)
cross = Vec3.cross v1, zaxis
cross.normalize()
wedge.push [ new Vec2(element[0].x, element[0].y), new Vec2(element[0].x - cross.x, element[0].y - cross.y)]
wedges.push wedge
console.log wedges
# For now, compute the voronoi for two chains
return wedges
module.exports =
MedialGraph : MedialGraph
| 44717 | ###
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
<NAME> - <EMAIL>
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
###
{Vec2,Edge2,Parabola} = require '../math/math'
{edge2Bisector} = require '../math/math_functions'
class MedialComponent
# Start and end are Vec2 points and the @component is either an edge or a
constructor : (@start, @end) ->
@
class MedialComponentEdge extends MedialComponent
constructor : (@edge) ->
@
# a value of 0 - 1 that samples between start and end
sample : (dt) ->
dx = ((@end.x - @start.x) * dt) + @start.x
@edge.sample(dx)
class MedialComponentParabola extends MedialComponent
constructor : (@parabola) ->
@
sample : (dt) ->
dx = ((@end.x - @start.x) * dt) + @start.x
dy = ((@end.y - @start.y) * dt) + @start.y
# Basically find the nearest y value to DY - not sure that is totally correct though :S
[y0,y1] = @parabola.sample(dx)
if y1 != y0
if Math.abs(y0 - dy) < Math.abs(y1-dy)
return y0
else
return y1
y0
class MedialGraph
constructor : ->
@components = []
@right_handed = true
# Compute the voronoi graph for two joined edges
voronoiEdgeEdge : (edge0, edge1) ->
bisector = edge2Bisector edge0, edge1
# As the bisector will only be for edges with angles less than 180, we can assume the shortest
# edge is the one that will be crossed first
# for now, we consider a
short_edge = edge1
long_edge = edge0
if edge0.length() < edge1.length()
short_edge = edge0
long_edge = edge1
[knot_point, influence_point] = @edgeLineInfluence bisector, short_edge, @right_handed
parta = new Edge2 bisector.start, knot_point
@components.push new MedialComponentEdge parta
[a,b,c] = long_edge.equation()
# TODO - how do we know which parabola result to choose?
parabola = new Parabola(influence_point,a,b,c)
cp = @edgeParabolaInfluence(parabola,long_edge,@right_handed)
parabola
# Function that determines where a parabola leaves the area of influence of an edge.
# Takes the line in the form ax + by + c = 0
edgeParabolaInfluence : (parabola, edge, right) ->
[ea,eb,ec] = edge.equation()
psa = eb
psb = -ea
psc = ea * edge.start.x + eb * edge.start.y + ec - eb * edge.start.x + ea * edge.start.y
pea = eb
peb = -ea
pec = ea * edge.end.x + eb * edge.end.y + ec - eb * edge.end.x + ea * edge.end.y
# two lines gives potentially 4 crossing points
[s0,s1] = parabola.lineCrossing(psa,psb,psc)
[e0,e1] = parabola.lineCrossing(pea,peb,pec)
#console.log psa,psb,psc
#console.log parabola.f, parabola.a, parabola.b, parabola.c
console.log s0,s1
console.log e0,e1
spoints = [Vec2.normalize(s0), Vec2.normalize(s1)]
epoints = [Vec2.normalize(e0), Vec2.normalize(e1)]
tt = Vec2.normalize edge.start
rp = []
for point in spoints
if right
if tt.dot(point) > 0
rp.push([point, edge.start])
else if tt.dot(point) <= 0
rp.push([point, edge.start])
for point in epoints
if right
if tt.dot(point) > 0
rp.push([point, edge.end])
else if tt.dot(point) <= 0
rp.push([point, edge.end])
rp
# Function that determines where a line equation leaves the area of influence of an edge
# Takes the line in the form ax + by + c = 0
edgeLineInfluence : (line,edge,right) ->
# Get the equations of the lines perpendicular to edge, passing through the end points
[ea,eb,ec] = edge.equation()
[a,b,c] = line.equation()
psa = eb
psb = -ea
psc = ea * edge.start.x + eb * edge.start.y + ec - eb * edge.start.x + ea * edge.start.y
pea = eb
peb = -ea
pec = ea * edge.end.x + eb * edge.end.y + ec - eb * edge.end.x + ea * edge.end.y
# find the intersection (hopefully they are not parallel lines :S )
# We should have a determinate that is non-zero right?
ys = (psa * c - psc * a) / (a * psb - psa * b)
xs = (-b * ys - c) / a
start_cross = new Vec2(xs,ys)
ye = (pea * c - pec * a) / (a * peb - pea * b)
xe = (-b * ye - c) / a
end_cross = new Vec2(xe,ye)
# We consider only one side of the edge, depending on whether left or right is true
ts = Vec2.normalize start_cross
tt = Vec2.normalize edge.start
ts.normalize()
tt.normalize()
if right
if tt.dot(ts) > 0
return [end_cross, edge.end]
else
return [start_cross, edge.start]
if tt.dot(ts) <= 0
return [start_cross, edge.start]
[end_cross, edge.end]
# ## medialAxis2D
# Given a planar polygon (a list of 2D vertices), compute the the medial axis of the polygon
# as a set of pairs of 2D points (edges)
medialAxis2D = (polygon, top, left, bottom, right) ->
# create pairs / edges
if polygon.length < 3
return []
edges = []
for idx in [0..polygon.length-1]
if idx + 1 < polygon.length
edges.push [ polygon[idx], polygon[idx+1] ]
else
edges.push [ polygon[idx], polygon[0] ]
# find the chains - As we are going clockwise winding, inside is to the right of the vector
# which is a positive cross product with z ( I think!)
chains = []
current_chain = new Array()
for idx in [0..edges.length-1]
e0 = edges[idx]
e1 = edges[idx+1]
if idx + 1 == edges.length
e1 = edges[0]
v0 = Vec3.sub new Vec3(e0[1].x, e0[1].y), new Vec3(e0[0].x, e0[0].y)
v1 = Vec3.sub new Vec3(e1[1].x, e1[1].y), new Vec3(e1[0].x, e1[0].y)
cross = Vec3.cross v0, v1
if cross.z > 0
# Its a reflex angle, therefore a chain
if current_chain.length == 0
current_chain.push e0
current_chain.push [e1[0]] # push the reflex vertex too if chain is greater than one edge
current_chain.push e1
# there is an edge case here whereby the last edge could be in a chain already
# but I suspect that is rare and can be handled anyway
else
# not a chain
if current_chain.length == 0
current_chain.push e0
chains.push current_chain
current_chain = new Array()
voronoi = []
wedges = []
zaxis = new Vec3(0,0,1)
wedge_length =100.0
# we now have the chains so we must compute the voronoi diagram for each chain and combine
for chain in chains
for idx in [0..chain.length-1]
# Wedges denote the area of effect for computing our initial bisectors.
# They are internal and are denoted by a point and a direction vector.
# Each element has two lines that denote a wedge and we want to be inside them
element = chain[idx]
wedge = []
# compute the initial voronoi graph. The wedges for each element
if element.length == 2
# its an edge so two lines perpendicular
v0 = Vec3.sub new Vec3(element[0].x, element[0].y), new Vec3(element[1].x, element[1].y)
cross = Vec3.cross v0, zaxis
cross.normalize()
wedge.push [new Vec2(element[0].x, element[0].y), new Vec2(element[0].x - cross.x, element[0].y - cross.y)]
wedge.push [new Vec2(element[1].x, element[1].y), new Vec2(element[1].x - cross.x, element[1].y - cross.y)]
else
# Its a reflex point so two lines perpendicular to the edges that join it
p = idx - 1
if idx == 0
p = chain.length - 1
n = idx + 1
if idx == chain.length - 1
n = 0
pe = chain[p]
ne = chain[n]
v0 = Vec3.sub new Vec3(pe[0].x, pe[0].y), new Vec3(pe[1].x, pe[1].y)
cross = Vec3.cross v0, zaxis
cross.normalize()
wedge.push [new Vec2(element[0].x, element[0].y), new Vec2(element[0].x - cross.x, element[0].y - cross.y)]
v1 = Vec3.sub new Vec3(ne[0].x, ne[0].y), new Vec3(ne[1].x, ne[1].y)
cross = Vec3.cross v1, zaxis
cross.normalize()
wedge.push [ new Vec2(element[0].x, element[0].y), new Vec2(element[0].x - cross.x, element[0].y - cross.y)]
wedges.push wedge
console.log wedges
# For now, compute the voronoi for two chains
return wedges
module.exports =
MedialGraph : MedialGraph
| true | ###
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
PI:NAME:<NAME>END_PI - PI:EMAIL:<EMAIL>END_PI
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
###
{Vec2,Edge2,Parabola} = require '../math/math'
{edge2Bisector} = require '../math/math_functions'
class MedialComponent
# Start and end are Vec2 points and the @component is either an edge or a
constructor : (@start, @end) ->
@
class MedialComponentEdge extends MedialComponent
constructor : (@edge) ->
@
# a value of 0 - 1 that samples between start and end
sample : (dt) ->
dx = ((@end.x - @start.x) * dt) + @start.x
@edge.sample(dx)
class MedialComponentParabola extends MedialComponent
constructor : (@parabola) ->
@
sample : (dt) ->
dx = ((@end.x - @start.x) * dt) + @start.x
dy = ((@end.y - @start.y) * dt) + @start.y
# Basically find the nearest y value to DY - not sure that is totally correct though :S
[y0,y1] = @parabola.sample(dx)
if y1 != y0
if Math.abs(y0 - dy) < Math.abs(y1-dy)
return y0
else
return y1
y0
class MedialGraph
constructor : ->
@components = []
@right_handed = true
# Compute the voronoi graph for two joined edges
voronoiEdgeEdge : (edge0, edge1) ->
bisector = edge2Bisector edge0, edge1
# As the bisector will only be for edges with angles less than 180, we can assume the shortest
# edge is the one that will be crossed first
# for now, we consider a
short_edge = edge1
long_edge = edge0
if edge0.length() < edge1.length()
short_edge = edge0
long_edge = edge1
[knot_point, influence_point] = @edgeLineInfluence bisector, short_edge, @right_handed
parta = new Edge2 bisector.start, knot_point
@components.push new MedialComponentEdge parta
[a,b,c] = long_edge.equation()
# TODO - how do we know which parabola result to choose?
parabola = new Parabola(influence_point,a,b,c)
cp = @edgeParabolaInfluence(parabola,long_edge,@right_handed)
parabola
# Function that determines where a parabola leaves the area of influence of an edge.
# Takes the line in the form ax + by + c = 0
edgeParabolaInfluence : (parabola, edge, right) ->
[ea,eb,ec] = edge.equation()
psa = eb
psb = -ea
psc = ea * edge.start.x + eb * edge.start.y + ec - eb * edge.start.x + ea * edge.start.y
pea = eb
peb = -ea
pec = ea * edge.end.x + eb * edge.end.y + ec - eb * edge.end.x + ea * edge.end.y
# two lines gives potentially 4 crossing points
[s0,s1] = parabola.lineCrossing(psa,psb,psc)
[e0,e1] = parabola.lineCrossing(pea,peb,pec)
#console.log psa,psb,psc
#console.log parabola.f, parabola.a, parabola.b, parabola.c
console.log s0,s1
console.log e0,e1
spoints = [Vec2.normalize(s0), Vec2.normalize(s1)]
epoints = [Vec2.normalize(e0), Vec2.normalize(e1)]
tt = Vec2.normalize edge.start
rp = []
for point in spoints
if right
if tt.dot(point) > 0
rp.push([point, edge.start])
else if tt.dot(point) <= 0
rp.push([point, edge.start])
for point in epoints
if right
if tt.dot(point) > 0
rp.push([point, edge.end])
else if tt.dot(point) <= 0
rp.push([point, edge.end])
rp
# Function that determines where a line equation leaves the area of influence of an edge
# Takes the line in the form ax + by + c = 0
edgeLineInfluence : (line,edge,right) ->
# Get the equations of the lines perpendicular to edge, passing through the end points
[ea,eb,ec] = edge.equation()
[a,b,c] = line.equation()
psa = eb
psb = -ea
psc = ea * edge.start.x + eb * edge.start.y + ec - eb * edge.start.x + ea * edge.start.y
pea = eb
peb = -ea
pec = ea * edge.end.x + eb * edge.end.y + ec - eb * edge.end.x + ea * edge.end.y
# find the intersection (hopefully they are not parallel lines :S )
# We should have a determinate that is non-zero right?
ys = (psa * c - psc * a) / (a * psb - psa * b)
xs = (-b * ys - c) / a
start_cross = new Vec2(xs,ys)
ye = (pea * c - pec * a) / (a * peb - pea * b)
xe = (-b * ye - c) / a
end_cross = new Vec2(xe,ye)
# We consider only one side of the edge, depending on whether left or right is true
ts = Vec2.normalize start_cross
tt = Vec2.normalize edge.start
ts.normalize()
tt.normalize()
if right
if tt.dot(ts) > 0
return [end_cross, edge.end]
else
return [start_cross, edge.start]
if tt.dot(ts) <= 0
return [start_cross, edge.start]
[end_cross, edge.end]
# ## medialAxis2D
# Given a planar polygon (a list of 2D vertices), compute the the medial axis of the polygon
# as a set of pairs of 2D points (edges)
medialAxis2D = (polygon, top, left, bottom, right) ->
# create pairs / edges
if polygon.length < 3
return []
edges = []
for idx in [0..polygon.length-1]
if idx + 1 < polygon.length
edges.push [ polygon[idx], polygon[idx+1] ]
else
edges.push [ polygon[idx], polygon[0] ]
# find the chains - As we are going clockwise winding, inside is to the right of the vector
# which is a positive cross product with z ( I think!)
chains = []
current_chain = new Array()
for idx in [0..edges.length-1]
e0 = edges[idx]
e1 = edges[idx+1]
if idx + 1 == edges.length
e1 = edges[0]
v0 = Vec3.sub new Vec3(e0[1].x, e0[1].y), new Vec3(e0[0].x, e0[0].y)
v1 = Vec3.sub new Vec3(e1[1].x, e1[1].y), new Vec3(e1[0].x, e1[0].y)
cross = Vec3.cross v0, v1
if cross.z > 0
# Its a reflex angle, therefore a chain
if current_chain.length == 0
current_chain.push e0
current_chain.push [e1[0]] # push the reflex vertex too if chain is greater than one edge
current_chain.push e1
# there is an edge case here whereby the last edge could be in a chain already
# but I suspect that is rare and can be handled anyway
else
# not a chain
if current_chain.length == 0
current_chain.push e0
chains.push current_chain
current_chain = new Array()
voronoi = []
wedges = []
zaxis = new Vec3(0,0,1)
wedge_length =100.0
# we now have the chains so we must compute the voronoi diagram for each chain and combine
for chain in chains
for idx in [0..chain.length-1]
# Wedges denote the area of effect for computing our initial bisectors.
# They are internal and are denoted by a point and a direction vector.
# Each element has two lines that denote a wedge and we want to be inside them
element = chain[idx]
wedge = []
# compute the initial voronoi graph. The wedges for each element
if element.length == 2
# its an edge so two lines perpendicular
v0 = Vec3.sub new Vec3(element[0].x, element[0].y), new Vec3(element[1].x, element[1].y)
cross = Vec3.cross v0, zaxis
cross.normalize()
wedge.push [new Vec2(element[0].x, element[0].y), new Vec2(element[0].x - cross.x, element[0].y - cross.y)]
wedge.push [new Vec2(element[1].x, element[1].y), new Vec2(element[1].x - cross.x, element[1].y - cross.y)]
else
# Its a reflex point so two lines perpendicular to the edges that join it
p = idx - 1
if idx == 0
p = chain.length - 1
n = idx + 1
if idx == chain.length - 1
n = 0
pe = chain[p]
ne = chain[n]
v0 = Vec3.sub new Vec3(pe[0].x, pe[0].y), new Vec3(pe[1].x, pe[1].y)
cross = Vec3.cross v0, zaxis
cross.normalize()
wedge.push [new Vec2(element[0].x, element[0].y), new Vec2(element[0].x - cross.x, element[0].y - cross.y)]
v1 = Vec3.sub new Vec3(ne[0].x, ne[0].y), new Vec3(ne[1].x, ne[1].y)
cross = Vec3.cross v1, zaxis
cross.normalize()
wedge.push [ new Vec2(element[0].x, element[0].y), new Vec2(element[0].x - cross.x, element[0].y - cross.y)]
wedges.push wedge
console.log wedges
# For now, compute the voronoi for two chains
return wedges
module.exports =
MedialGraph : MedialGraph
|
[
{
"context": "re = 0\n return\n\nLocalScoreManager = ->\n @key = \"bestScore\"\n supported = @localStorageSupported()\n @storag",
"end": 884,
"score": 0.9881583452224731,
"start": 875,
"tag": "KEY",
"value": "bestScore"
},
{
"context": "eManager::localStorageSupported = ->\n tes... | lib/atom-2048-view.coffee | void-main/atom-2048 | 7 | {View} = require 'atom-space-pen-views'
AchievementsView = require './achievements-view'
{CompositeDisposable, Emitter} = require 'atom'
Tile = (position, value) ->
@x = position.x
@y = position.y
@value = value or 2
@previousPosition = null
@mergedFrom = null # Tracks tiles that merged together
return
Grid = (size) ->
@size = size
@cells = []
@build()
return
KeyboardInputManager = ->
KeyboardInputManager::disposables = new CompositeDisposable()
KeyboardInputManager::events = {}
KeyboardInputManager::listen()
return
HTMLActuator = ->
@tileContainer = document.querySelector(".tile-container")
@scoreContainer = document.querySelector(".score-container")
@bestContainer = document.querySelector(".best-container")
@messageContainer = document.querySelector(".game-message")
@score = 0
return
LocalScoreManager = ->
@key = "bestScore"
supported = @localStorageSupported()
@storage = (if supported then window.localStorage else window.fakeStorage)
return
GameManager = (size, InputManager, Actuator, ScoreManager) ->
@size = size # Size of the grid
@inputManager = new InputManager
@scoreManager = new ScoreManager
@actuator = new Actuator
@startTiles = 2
@inputManager.on "move", @move.bind(this)
@inputManager.on "restart", @restart.bind(this)
@inputManager.on "keepPlaying", @keepPlaying.bind(this)
@inputManager.on "shake", @shake.bind(this)
@setup()
return
(->
lastTime = 0
vendors = [
"webkit"
"moz"
]
x = 0
while x < vendors.length and not window.requestAnimationFrame
window.requestAnimationFrame = window[vendors[x] + "RequestAnimationFrame"]
window.cancelAnimationFrame = window[vendors[x] + "CancelAnimationFrame"] or window[vendors[x] + "CancelRequestAnimationFrame"]
++x
unless window.requestAnimationFrame
window.requestAnimationFrame = (callback, element) ->
currTime = new Date().getTime()
timeToCall = Math.max(0, 16 - (currTime - lastTime))
id = window.setTimeout(->
callback currTime + timeToCall
return
, timeToCall)
lastTime = currTime + timeToCall
id
unless window.cancelAnimationFrame
window.cancelAnimationFrame = (id) ->
clearTimeout id
return
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()
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
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 = ->
!!@availableCells().length
Grid::cellAvailable = (cell) ->
not @cellOccupied(cell)
Grid::cellOccupied = (cell) ->
!!@cellContent(cell)
Grid::cellContent = (cell) ->
if @withinBounds(cell)
@cells[cell.x][cell.y]
else
null
Grid::insertTile = (tile) ->
@cells[tile.x][tile.y] = tile
return
Grid::removeTile = (tile) ->
@cells[tile.x][tile.y] = null
return
Grid::withinBounds = (position) ->
position.x >= 0 and position.x < @size and position.y >= 0 and position.y < @size
keymap =
75: 0
76: 1
74: 2
72: 3
87: 0
68: 1
83: 2
65: 3
38: 0
39: 1
40: 2
37: 3
KeyboardInputManager::on = (event, callback) ->
KeyboardInputManager::events[event] = [] unless KeyboardInputManager::events[event]
KeyboardInputManager::events[event].push callback
return
KeyboardInputManager::emit = (event, data) ->
callbacks = @events[event]
if callbacks
callbacks.forEach (callback) ->
callback data
return
return
listenerFunc = (event) ->
KeyboardInputManager::listener event
return
KeyboardInputManager::listener = (event) ->
start = new Date().getTime()
modifiers = event.altKey or event.ctrlKey or event.metaKey or event.shiftKey
mapped = keymap[event.which]
unless modifiers
event.preventDefault() unless event.which is 27 # esc key for boss
if mapped isnt `undefined`
@emit "shake"
@emit "move", mapped
@restart.bind(this) event if event.which is 32
return
KeyboardInputManager::listen = ->
self = this
atom.views.getView(atom.workspace).addEventListener "keydown", listenerFunc
# document.addEventListener "keydown", listenerFunc
retry = document.querySelector(".retry-button")
retry.addEventListener "click", @restart.bind(this)
retry.addEventListener "touchend", @restart.bind(this)
keepPlaying = document.querySelector(".keep-playing-button")
keepPlaying.addEventListener "click", @keepPlaying.bind(this)
keepPlaying.addEventListener "touchend", @keepPlaying.bind(this)
touchStartClientX = undefined
touchStartClientY = undefined
gameContainer = document.getElementsByClassName("game-container")[0]
gameContainer.addEventListener "touchstart", (event) ->
return if event.touches.length > 1
touchStartClientX = event.touches[0].clientX
touchStartClientY = event.touches[0].clientY
event.preventDefault()
return
gameContainer.addEventListener "touchmove", (event) ->
event.preventDefault()
return
gameContainer.addEventListener "touchend", (event) ->
return if event.touches.length > 0
dx = event.changedTouches[0].clientX - touchStartClientX
absDx = Math.abs(dx)
dy = event.changedTouches[0].clientY - touchStartClientY
absDy = Math.abs(dy)
self.emit "move", (if absDx > absDy then ((if dx > 0 then 1 else 3)) else ((if dy > 0 then 2 else 0))) if Math.max(absDx, absDy) > 10
return
return
KeyboardInputManager::stopListen = ->
atom.views.getView(atom.workspace).removeEventListener "keydown", listenerFunc
return
KeyboardInputManager::restart = (event) ->
event.preventDefault()
@emit "restart"
return
KeyboardInputManager::keepPlaying = (event) ->
event.preventDefault()
@emit "keepPlaying"
return
HTMLActuator::actuate = (grid, metadata) ->
self = this
window.requestAnimationFrame ->
self.clearContainer self.tileContainer
grid.cells.forEach (column) ->
column.forEach (cell) ->
self.addTile cell if cell
return
return
self.updateScore metadata.score
self.updateBestScore metadata.bestScore
if metadata.terminated
if metadata.over
self.message false
else self.message true if metadata.won
return
return
HTMLActuator::clearContainer = (container) ->
if container
container.removeChild container.firstChild while container.firstChild
return
HTMLActuator::addTile = (tile) ->
self = this
wrapper = document.createElement("div")
inner = document.createElement("div")
position = tile.previousPosition or
x: tile.x
y: tile.y
positionClass = @positionClass(position)
classes = [
"tile"
"tile-" + tile.value
positionClass
]
classes.push "tile-super" if tile.value > 2048
@applyClasses wrapper, classes
inner.classList.add "tile-inner"
inner.textContent = tile.value
if tile.previousPosition
window.requestAnimationFrame ->
classes[2] = self.positionClass(
x: tile.x
y: tile.y
)
self.applyClasses wrapper, classes
return
else if tile.mergedFrom
classes.push "tile-merged"
@applyClasses wrapper, classes
tile.mergedFrom.forEach (merged) ->
self.addTile merged
return
else
classes.push "tile-new"
@applyClasses wrapper, classes
wrapper.appendChild inner
@tileContainer.appendChild wrapper
return
HTMLActuator::applyClasses = (element, classes) ->
element.setAttribute "class", classes.join(" ")
return
HTMLActuator::normalizePosition = (position) ->
x: position.x + 1
y: position.y + 1
HTMLActuator::positionClass = (position) ->
position = @normalizePosition(position)
"tile-position-" + position.x + "-" + position.y
HTMLActuator::updateScore = (score) ->
@clearContainer @scoreContainer
difference = score - @score
@score = score
@scoreContainer.textContent = @score
if difference > 0
addition = document.createElement("div")
addition.classList.add "score-addition"
addition.textContent = "+" + difference
@scoreContainer.appendChild addition
return
HTMLActuator::updateBestScore = (bestScore) ->
@bestContainer.textContent = bestScore
return
HTMLActuator::message = (won) ->
type = (if won then "game-won" else "game-over")
message = (if won then "You win!" else "Game over!")
@messageContainer.classList.add type
@messageContainer.getElementsByTagName("p")[0].textContent = message
return
HTMLActuator::clearMessage = ->
@messageContainer.classList.remove "game-won"
@messageContainer.classList.remove "game-over"
return
HTMLActuator::continueKeep = ->
@clearMessage()
return
window.fakeStorage =
_data: {}
setItem: (id, val) ->
@_data[id] = String(val)
getItem: (id) ->
(if @_data.hasOwnProperty(id) then @_data[id] else `undefined`)
removeItem: (id) ->
delete @_data[id]
clear: ->
@_data = {}
LocalScoreManager::localStorageSupported = ->
testKey = "test"
storage = window.localStorage
try
storage.setItem testKey, "1"
storage.removeItem testKey
return true
catch error
return false
return
LocalScoreManager::get = ->
@storage.getItem(@key) or 0
LocalScoreManager::set = (score) ->
@storage.setItem @key, score
return
# Restart the game
GameManager::restart = ->
@actuator.continueKeep()
@setup()
return
# Keep playing after winning
GameManager::keepPlaying = ->
@keepPlaying = true
@actuator.continueKeep()
return
GameManager::isGameTerminated = ->
if @over or (@won and not @keepPlaying)
true
else
false
# Set up the game
GameManager::setup = ->
@grid = new Grid(@size)
@score = 0
@over = false
@won = false
@keepPlaying = false
# Add the initial tiles
@addStartTiles()
# Update the actuator
@actuate()
return
# Set up the initial tiles to start the game with
GameManager::addStartTiles = ->
i = 0
while i < @startTiles
@addRandomTile()
i++
return
# Adds a tile in a random position
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
# Sends the updated grid to the actuator
GameManager::actuate = ->
@scoreManager.set @score if @scoreManager.get() < @score
@actuator.actuate @grid,
score: @score
over: @over
won: @won
bestScore: @scoreManager.get()
terminated: @isGameTerminated()
return
# Save all tile positions and remove merger info
GameManager::prepareTiles = ->
@grid.eachCell (x, y, tile) ->
if tile
tile.mergedFrom = null
tile.savePosition()
return
return
# Move a tile and its representation
GameManager::moveTile = (tile, cell) ->
@grid.cells[tile.x][tile.y] = null
@grid.cells[cell.x][cell.y] = tile
tile.updatePosition cell
return
# Move tiles on the grid in the specified direction
GameManager::move = (direction) ->
# 0: up, 1: right, 2:down, 3: left
self = this
return if @isGameTerminated() # Don't do anything if the game's over
cell = undefined
tile = undefined
vector = @getVector(direction)
traversals = @buildTraversals(vector)
moved = false
# Save the current tile positions and remove merger information
@prepareTiles()
# Traverse the grid in the right direction and move tiles
traversals.x.forEach (x) ->
traversals.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)
# Only one merger per row traversal?
if next and next.value is tile.value and not next.mergedFrom
merged = new Tile(positions.next, tile.value * 2)
atom.emitter.emit "tileChanged", value: merged.value
merged.mergedFrom = [
tile
next
]
self.grid.insertTile merged
self.grid.removeTile tile
# Converge the two tiles' positions
tile.updatePosition positions.next
# Update the score
self.score += merged.value
atom.emitter.emit "scoreChanged", value: self.score
# The mighty 2048 tile
self.won = true if merged.value is 2048
else
self.moveTile tile, positions.farthest
moved = true unless self.positionsEqual(cell, tile) # The tile moved from its original cell!
return
return
if moved
@addRandomTile()
@over = true unless @movesAvailable() # Game over!
@actuate()
return
# Get the vector representing the chosen direction
GameManager::getVector = (direction) ->
# Vectors representing tile movement
map =
0: # up
x: 0
y: -1
1: # right
x: 1
y: 0
2: # down
x: 0
y: 1
3: # left
x: -1
y: 0
map[direction]
# Build a list of positions to traverse in the right order
GameManager::buildTraversals = (vector) ->
traversals =
x: []
y: []
pos = 0
while pos < @size
traversals.x.push pos
traversals.y.push pos
pos++
# Always traverse from the farthest cell in the chosen direction
traversals.x = traversals.x.reverse() if vector.x is 1
traversals.y = traversals.y.reverse() if vector.y is 1
traversals
GameManager::findFarthestPosition = (cell, vector) ->
previous = undefined
# Progress towards the vector direction until an obstacle is found
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 # Used to check if a merge is required
GameManager::movesAvailable = ->
@grid.cellsAvailable() or @tileMatchesAvailable()
# Check for available matches between tiles (more expensive check)
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 # These two tiles can be merged
direction++
y++
x++
false
GameManager::positionsEqual = (first, second) ->
first.x is second.x and first.y is second.y
GameManager::shake = ()->
if atom.config.get('atom-2048.Enable Power Mode')
topPanels = atom.workspace.getTopPanels()
view = atom.views.getView(topPanels[0])
intensity = 1 + atom.config.get('atom-2048.Power Level') * Math.random()
x = intensity * (if Math.random() > 0.5 then -1 else 1)
y = intensity * (if Math.random() > 0.5 then -1 else 1)
view.style.top = "#{y}px"
view.style.left = "#{x}px"
setTimeout =>
view.style.top = ""
view.style.left = ""
, 75
module.exports =
class Atom2048View extends View
@disposables = null
@emitter = new Emitter
@bossMode = false
@panel = null
@content: ->
@div class: 'atom-2048 overlay from-top', =>
@div class: 'container', =>
@div class: 'heading', =>
@h1 "2048", class: 'title', =>
@div class: 'scores-container', =>
@div 0, class: 'score-container'
@div 0, class: 'best-container'
@div class: 'game-container', =>
@div class: 'game-message', =>
@p " "
@div class: 'lower', =>
@a "Keep going", class: 'keep-playing-button'
@a "Try again", class: 'retry-button'
@div class: 'grid-container', =>
@div class: 'grid-row', =>
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-row', =>
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-row', =>
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-row', =>
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class:'tile-container'
initialize: (serializeState) ->
@bossMode = false
@disposables = new CompositeDisposable
@emitter = new Emitter
@disposables.add atom.commands.add 'atom-workspace', "atom-2048:toggle", => @toggle()
@disposables.add atom.commands.add 'atom-workspace', "atom-2048:bossComing", (e) =>
if @panel?.isVisible()
@bossComing()
else
e.abortKeyBinding()
@disposables.add atom.commands.add 'atom-workspace', "atom-2048:bossAway", => @bossAway()
@emitter.on "atom2048:unlock", @achieve
@emitter.on "tileChanged", @tileUpdated
@emitter.on "scoreChanged", @scoreUpdated
# Returns an object that can be retrieved when package is activated
serialize: ->
# Tear down any state and detach
destroy: ->
@disposables.dispose()
@emitter.dispose()
@detach()
achieve: (event) ->
if atom.packages.isPackageActive("achievements")
atom.emitter.emit "achievement:unlock",
name: event.name
requirement: event.requirement
category: event.category
package: event.packageName
points: event.points
iconURL: event.iconURL
else
achievementsView = new AchievementsView
achievementsView.achieve()
# process tile event
tileUpdated: (event) =>
if event.value is 2048
atom.emitter.emit "atom2048:unlock",
name: "Beat the game!"
requirement: "Congratulations adventurer, not everyone can do this!"
category: "Game Play"
package: "atom-2048"
points: 1600
iconURL: "http://gabrielecirulli.github.io/2048/meta/apple-touch-icon.png"
if event.value is 1024
atom.emitter.emit "atom2048:unlock",
name: "Almost there!"
requirement: "You are half way to win the game!"
category: "Game Play"
package: "atom-2048"
points: 800
iconURL: "http://gabrielecirulli.github.io/2048/meta/apple-touch-icon.png"
if event.value >= 128
atom.emitter.emit "atom2048:unlock",
name: "Got " + event.value
requirement: "First got " + event.value
category: "Game Play"
package: "atom-2048"
points: 100 * event.value / 128
iconURL: "http://gabrielecirulli.github.io/2048/meta/apple-touch-icon.png"
# process score event
scoreUpdated: (event) =>
if event.value >= 50000
atom.emitter.emit "atom2048:unlock",
name: "100K!"
requirement: "YOU ARE MY GOD!!"
category: "Game Play"
package: "atom-2048"
points: 4000
iconURL: "http://gabrielecirulli.github.io/2048/meta/apple-touch-icon.png"
if event.value >= 50000
atom.emitter.emit "atom2048:unlock",
name: "50K!"
requirement: "Are you kidding me??"
category: "Game Play"
package: "atom-2048"
points: 2000
iconURL: "http://gabrielecirulli.github.io/2048/meta/apple-touch-icon.png"
if event.value >= 30000
atom.emitter.emit "atom2048:unlock",
name: "30K!"
requirement: "Too high, too high, don't fall!"
category: "Game Play"
package: "atom-2048"
points: 1000
iconURL: "http://gabrielecirulli.github.io/2048/meta/apple-touch-icon.png"
if event.value >= 10000
atom.emitter.emit "atom2048:unlock",
name: "10K!"
requirement: "No way!"
category: "Game Play"
package: "atom-2048"
points: 500
iconURL: "http://gabrielecirulli.github.io/2048/meta/apple-touch-icon.png"
bossComing: ->
KeyboardInputManager::stopListen()
@bossMode = true
@panel?.hide()
bossAway: ->
if @bossMode and not @panel?.isVisible()
@panel ?= atom.workspace.addTopPanel(item: this)
@panel.show()
KeyboardInputManager::listen()
toggle: ->
if @panel?.isVisible()
KeyboardInputManager::stopListen()
@panel?.hide()
else
window.requestAnimationFrame ->
new GameManager(4, KeyboardInputManager, HTMLActuator, LocalScoreManager)
@panel ?= atom.workspace.addTopPanel(item: this)
@panel.show()
atom.emitter.emit "atom2048:unlock",
name: "Hello, adventurer!"
requirement: "Launch 2048 game in atom"
category: "Game Play"
package: "atom-2048"
points: 100
iconURL: "http://gabrielecirulli.github.io/2048/meta/apple-touch-icon.png"
| 14590 | {View} = require 'atom-space-pen-views'
AchievementsView = require './achievements-view'
{CompositeDisposable, Emitter} = require 'atom'
Tile = (position, value) ->
@x = position.x
@y = position.y
@value = value or 2
@previousPosition = null
@mergedFrom = null # Tracks tiles that merged together
return
Grid = (size) ->
@size = size
@cells = []
@build()
return
KeyboardInputManager = ->
KeyboardInputManager::disposables = new CompositeDisposable()
KeyboardInputManager::events = {}
KeyboardInputManager::listen()
return
HTMLActuator = ->
@tileContainer = document.querySelector(".tile-container")
@scoreContainer = document.querySelector(".score-container")
@bestContainer = document.querySelector(".best-container")
@messageContainer = document.querySelector(".game-message")
@score = 0
return
LocalScoreManager = ->
@key = "<KEY>"
supported = @localStorageSupported()
@storage = (if supported then window.localStorage else window.fakeStorage)
return
GameManager = (size, InputManager, Actuator, ScoreManager) ->
@size = size # Size of the grid
@inputManager = new InputManager
@scoreManager = new ScoreManager
@actuator = new Actuator
@startTiles = 2
@inputManager.on "move", @move.bind(this)
@inputManager.on "restart", @restart.bind(this)
@inputManager.on "keepPlaying", @keepPlaying.bind(this)
@inputManager.on "shake", @shake.bind(this)
@setup()
return
(->
lastTime = 0
vendors = [
"webkit"
"moz"
]
x = 0
while x < vendors.length and not window.requestAnimationFrame
window.requestAnimationFrame = window[vendors[x] + "RequestAnimationFrame"]
window.cancelAnimationFrame = window[vendors[x] + "CancelAnimationFrame"] or window[vendors[x] + "CancelRequestAnimationFrame"]
++x
unless window.requestAnimationFrame
window.requestAnimationFrame = (callback, element) ->
currTime = new Date().getTime()
timeToCall = Math.max(0, 16 - (currTime - lastTime))
id = window.setTimeout(->
callback currTime + timeToCall
return
, timeToCall)
lastTime = currTime + timeToCall
id
unless window.cancelAnimationFrame
window.cancelAnimationFrame = (id) ->
clearTimeout id
return
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()
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
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 = ->
!!@availableCells().length
Grid::cellAvailable = (cell) ->
not @cellOccupied(cell)
Grid::cellOccupied = (cell) ->
!!@cellContent(cell)
Grid::cellContent = (cell) ->
if @withinBounds(cell)
@cells[cell.x][cell.y]
else
null
Grid::insertTile = (tile) ->
@cells[tile.x][tile.y] = tile
return
Grid::removeTile = (tile) ->
@cells[tile.x][tile.y] = null
return
Grid::withinBounds = (position) ->
position.x >= 0 and position.x < @size and position.y >= 0 and position.y < @size
keymap =
75: 0
76: 1
74: 2
72: 3
87: 0
68: 1
83: 2
65: 3
38: 0
39: 1
40: 2
37: 3
KeyboardInputManager::on = (event, callback) ->
KeyboardInputManager::events[event] = [] unless KeyboardInputManager::events[event]
KeyboardInputManager::events[event].push callback
return
KeyboardInputManager::emit = (event, data) ->
callbacks = @events[event]
if callbacks
callbacks.forEach (callback) ->
callback data
return
return
listenerFunc = (event) ->
KeyboardInputManager::listener event
return
KeyboardInputManager::listener = (event) ->
start = new Date().getTime()
modifiers = event.altKey or event.ctrlKey or event.metaKey or event.shiftKey
mapped = keymap[event.which]
unless modifiers
event.preventDefault() unless event.which is 27 # esc key for boss
if mapped isnt `undefined`
@emit "shake"
@emit "move", mapped
@restart.bind(this) event if event.which is 32
return
KeyboardInputManager::listen = ->
self = this
atom.views.getView(atom.workspace).addEventListener "keydown", listenerFunc
# document.addEventListener "keydown", listenerFunc
retry = document.querySelector(".retry-button")
retry.addEventListener "click", @restart.bind(this)
retry.addEventListener "touchend", @restart.bind(this)
keepPlaying = document.querySelector(".keep-playing-button")
keepPlaying.addEventListener "click", @keepPlaying.bind(this)
keepPlaying.addEventListener "touchend", @keepPlaying.bind(this)
touchStartClientX = undefined
touchStartClientY = undefined
gameContainer = document.getElementsByClassName("game-container")[0]
gameContainer.addEventListener "touchstart", (event) ->
return if event.touches.length > 1
touchStartClientX = event.touches[0].clientX
touchStartClientY = event.touches[0].clientY
event.preventDefault()
return
gameContainer.addEventListener "touchmove", (event) ->
event.preventDefault()
return
gameContainer.addEventListener "touchend", (event) ->
return if event.touches.length > 0
dx = event.changedTouches[0].clientX - touchStartClientX
absDx = Math.abs(dx)
dy = event.changedTouches[0].clientY - touchStartClientY
absDy = Math.abs(dy)
self.emit "move", (if absDx > absDy then ((if dx > 0 then 1 else 3)) else ((if dy > 0 then 2 else 0))) if Math.max(absDx, absDy) > 10
return
return
KeyboardInputManager::stopListen = ->
atom.views.getView(atom.workspace).removeEventListener "keydown", listenerFunc
return
KeyboardInputManager::restart = (event) ->
event.preventDefault()
@emit "restart"
return
KeyboardInputManager::keepPlaying = (event) ->
event.preventDefault()
@emit "keepPlaying"
return
HTMLActuator::actuate = (grid, metadata) ->
self = this
window.requestAnimationFrame ->
self.clearContainer self.tileContainer
grid.cells.forEach (column) ->
column.forEach (cell) ->
self.addTile cell if cell
return
return
self.updateScore metadata.score
self.updateBestScore metadata.bestScore
if metadata.terminated
if metadata.over
self.message false
else self.message true if metadata.won
return
return
HTMLActuator::clearContainer = (container) ->
if container
container.removeChild container.firstChild while container.firstChild
return
HTMLActuator::addTile = (tile) ->
self = this
wrapper = document.createElement("div")
inner = document.createElement("div")
position = tile.previousPosition or
x: tile.x
y: tile.y
positionClass = @positionClass(position)
classes = [
"tile"
"tile-" + tile.value
positionClass
]
classes.push "tile-super" if tile.value > 2048
@applyClasses wrapper, classes
inner.classList.add "tile-inner"
inner.textContent = tile.value
if tile.previousPosition
window.requestAnimationFrame ->
classes[2] = self.positionClass(
x: tile.x
y: tile.y
)
self.applyClasses wrapper, classes
return
else if tile.mergedFrom
classes.push "tile-merged"
@applyClasses wrapper, classes
tile.mergedFrom.forEach (merged) ->
self.addTile merged
return
else
classes.push "tile-new"
@applyClasses wrapper, classes
wrapper.appendChild inner
@tileContainer.appendChild wrapper
return
HTMLActuator::applyClasses = (element, classes) ->
element.setAttribute "class", classes.join(" ")
return
HTMLActuator::normalizePosition = (position) ->
x: position.x + 1
y: position.y + 1
HTMLActuator::positionClass = (position) ->
position = @normalizePosition(position)
"tile-position-" + position.x + "-" + position.y
HTMLActuator::updateScore = (score) ->
@clearContainer @scoreContainer
difference = score - @score
@score = score
@scoreContainer.textContent = @score
if difference > 0
addition = document.createElement("div")
addition.classList.add "score-addition"
addition.textContent = "+" + difference
@scoreContainer.appendChild addition
return
HTMLActuator::updateBestScore = (bestScore) ->
@bestContainer.textContent = bestScore
return
HTMLActuator::message = (won) ->
type = (if won then "game-won" else "game-over")
message = (if won then "You win!" else "Game over!")
@messageContainer.classList.add type
@messageContainer.getElementsByTagName("p")[0].textContent = message
return
HTMLActuator::clearMessage = ->
@messageContainer.classList.remove "game-won"
@messageContainer.classList.remove "game-over"
return
HTMLActuator::continueKeep = ->
@clearMessage()
return
window.fakeStorage =
_data: {}
setItem: (id, val) ->
@_data[id] = String(val)
getItem: (id) ->
(if @_data.hasOwnProperty(id) then @_data[id] else `undefined`)
removeItem: (id) ->
delete @_data[id]
clear: ->
@_data = {}
LocalScoreManager::localStorageSupported = ->
testKey = "<KEY>"
storage = window.localStorage
try
storage.setItem testKey, "1"
storage.removeItem testKey
return true
catch error
return false
return
LocalScoreManager::get = ->
@storage.getItem(@key) or 0
LocalScoreManager::set = (score) ->
@storage.setItem @key, score
return
# Restart the game
GameManager::restart = ->
@actuator.continueKeep()
@setup()
return
# Keep playing after winning
GameManager::keepPlaying = ->
@keepPlaying = true
@actuator.continueKeep()
return
GameManager::isGameTerminated = ->
if @over or (@won and not @keepPlaying)
true
else
false
# Set up the game
GameManager::setup = ->
@grid = new Grid(@size)
@score = 0
@over = false
@won = false
@keepPlaying = false
# Add the initial tiles
@addStartTiles()
# Update the actuator
@actuate()
return
# Set up the initial tiles to start the game with
GameManager::addStartTiles = ->
i = 0
while i < @startTiles
@addRandomTile()
i++
return
# Adds a tile in a random position
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
# Sends the updated grid to the actuator
GameManager::actuate = ->
@scoreManager.set @score if @scoreManager.get() < @score
@actuator.actuate @grid,
score: @score
over: @over
won: @won
bestScore: @scoreManager.get()
terminated: @isGameTerminated()
return
# Save all tile positions and remove merger info
GameManager::prepareTiles = ->
@grid.eachCell (x, y, tile) ->
if tile
tile.mergedFrom = null
tile.savePosition()
return
return
# Move a tile and its representation
GameManager::moveTile = (tile, cell) ->
@grid.cells[tile.x][tile.y] = null
@grid.cells[cell.x][cell.y] = tile
tile.updatePosition cell
return
# Move tiles on the grid in the specified direction
GameManager::move = (direction) ->
# 0: up, 1: right, 2:down, 3: left
self = this
return if @isGameTerminated() # Don't do anything if the game's over
cell = undefined
tile = undefined
vector = @getVector(direction)
traversals = @buildTraversals(vector)
moved = false
# Save the current tile positions and remove merger information
@prepareTiles()
# Traverse the grid in the right direction and move tiles
traversals.x.forEach (x) ->
traversals.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)
# Only one merger per row traversal?
if next and next.value is tile.value and not next.mergedFrom
merged = new Tile(positions.next, tile.value * 2)
atom.emitter.emit "tileChanged", value: merged.value
merged.mergedFrom = [
tile
next
]
self.grid.insertTile merged
self.grid.removeTile tile
# Converge the two tiles' positions
tile.updatePosition positions.next
# Update the score
self.score += merged.value
atom.emitter.emit "scoreChanged", value: self.score
# The mighty 2048 tile
self.won = true if merged.value is 2048
else
self.moveTile tile, positions.farthest
moved = true unless self.positionsEqual(cell, tile) # The tile moved from its original cell!
return
return
if moved
@addRandomTile()
@over = true unless @movesAvailable() # Game over!
@actuate()
return
# Get the vector representing the chosen direction
GameManager::getVector = (direction) ->
# Vectors representing tile movement
map =
0: # up
x: 0
y: -1
1: # right
x: 1
y: 0
2: # down
x: 0
y: 1
3: # left
x: -1
y: 0
map[direction]
# Build a list of positions to traverse in the right order
GameManager::buildTraversals = (vector) ->
traversals =
x: []
y: []
pos = 0
while pos < @size
traversals.x.push pos
traversals.y.push pos
pos++
# Always traverse from the farthest cell in the chosen direction
traversals.x = traversals.x.reverse() if vector.x is 1
traversals.y = traversals.y.reverse() if vector.y is 1
traversals
GameManager::findFarthestPosition = (cell, vector) ->
previous = undefined
# Progress towards the vector direction until an obstacle is found
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 # Used to check if a merge is required
GameManager::movesAvailable = ->
@grid.cellsAvailable() or @tileMatchesAvailable()
# Check for available matches between tiles (more expensive check)
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 # These two tiles can be merged
direction++
y++
x++
false
GameManager::positionsEqual = (first, second) ->
first.x is second.x and first.y is second.y
GameManager::shake = ()->
if atom.config.get('atom-2048.Enable Power Mode')
topPanels = atom.workspace.getTopPanels()
view = atom.views.getView(topPanels[0])
intensity = 1 + atom.config.get('atom-2048.Power Level') * Math.random()
x = intensity * (if Math.random() > 0.5 then -1 else 1)
y = intensity * (if Math.random() > 0.5 then -1 else 1)
view.style.top = "#{y}px"
view.style.left = "#{x}px"
setTimeout =>
view.style.top = ""
view.style.left = ""
, 75
module.exports =
class Atom2048View extends View
@disposables = null
@emitter = new Emitter
@bossMode = false
@panel = null
@content: ->
@div class: 'atom-2048 overlay from-top', =>
@div class: 'container', =>
@div class: 'heading', =>
@h1 "2048", class: 'title', =>
@div class: 'scores-container', =>
@div 0, class: 'score-container'
@div 0, class: 'best-container'
@div class: 'game-container', =>
@div class: 'game-message', =>
@p " "
@div class: 'lower', =>
@a "Keep going", class: 'keep-playing-button'
@a "Try again", class: 'retry-button'
@div class: 'grid-container', =>
@div class: 'grid-row', =>
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-row', =>
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-row', =>
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-row', =>
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class:'tile-container'
initialize: (serializeState) ->
@bossMode = false
@disposables = new CompositeDisposable
@emitter = new Emitter
@disposables.add atom.commands.add 'atom-workspace', "atom-2048:toggle", => @toggle()
@disposables.add atom.commands.add 'atom-workspace', "atom-2048:bossComing", (e) =>
if @panel?.isVisible()
@bossComing()
else
e.abortKeyBinding()
@disposables.add atom.commands.add 'atom-workspace', "atom-2048:bossAway", => @bossAway()
@emitter.on "atom2048:unlock", @achieve
@emitter.on "tileChanged", @tileUpdated
@emitter.on "scoreChanged", @scoreUpdated
# Returns an object that can be retrieved when package is activated
serialize: ->
# Tear down any state and detach
destroy: ->
@disposables.dispose()
@emitter.dispose()
@detach()
achieve: (event) ->
if atom.packages.isPackageActive("achievements")
atom.emitter.emit "achievement:unlock",
name: event.name
requirement: event.requirement
category: event.category
package: event.packageName
points: event.points
iconURL: event.iconURL
else
achievementsView = new AchievementsView
achievementsView.achieve()
# process tile event
tileUpdated: (event) =>
if event.value is 2048
atom.emitter.emit "atom2048:unlock",
name: "Beat the game!"
requirement: "Congratulations adventurer, not everyone can do this!"
category: "Game Play"
package: "atom-2048"
points: 1600
iconURL: "http://gabrielecirulli.github.io/2048/meta/apple-touch-icon.png"
if event.value is 1024
atom.emitter.emit "atom2048:unlock",
name: "Almost there!"
requirement: "You are half way to win the game!"
category: "Game Play"
package: "atom-2048"
points: 800
iconURL: "http://gabrielecirulli.github.io/2048/meta/apple-touch-icon.png"
if event.value >= 128
atom.emitter.emit "atom2048:unlock",
name: "Got " + event.value
requirement: "First got " + event.value
category: "Game Play"
package: "atom-2048"
points: 100 * event.value / 128
iconURL: "http://gabrielecirulli.github.io/2048/meta/apple-touch-icon.png"
# process score event
scoreUpdated: (event) =>
if event.value >= 50000
atom.emitter.emit "atom2048:unlock",
name: "100K!"
requirement: "YOU ARE MY GOD!!"
category: "Game Play"
package: "atom-2048"
points: 4000
iconURL: "http://gabrielecirulli.github.io/2048/meta/apple-touch-icon.png"
if event.value >= 50000
atom.emitter.emit "atom2048:unlock",
name: "50K!"
requirement: "Are you kidding me??"
category: "Game Play"
package: "atom-2048"
points: 2000
iconURL: "http://gabrielecirulli.github.io/2048/meta/apple-touch-icon.png"
if event.value >= 30000
atom.emitter.emit "atom2048:unlock",
name: "30K!"
requirement: "Too high, too high, don't fall!"
category: "Game Play"
package: "atom-2048"
points: 1000
iconURL: "http://gabrielecirulli.github.io/2048/meta/apple-touch-icon.png"
if event.value >= 10000
atom.emitter.emit "atom2048:unlock",
name: "10K!"
requirement: "No way!"
category: "Game Play"
package: "atom-2048"
points: 500
iconURL: "http://gabrielecirulli.github.io/2048/meta/apple-touch-icon.png"
bossComing: ->
KeyboardInputManager::stopListen()
@bossMode = true
@panel?.hide()
bossAway: ->
if @bossMode and not @panel?.isVisible()
@panel ?= atom.workspace.addTopPanel(item: this)
@panel.show()
KeyboardInputManager::listen()
toggle: ->
if @panel?.isVisible()
KeyboardInputManager::stopListen()
@panel?.hide()
else
window.requestAnimationFrame ->
new GameManager(4, KeyboardInputManager, HTMLActuator, LocalScoreManager)
@panel ?= atom.workspace.addTopPanel(item: this)
@panel.show()
atom.emitter.emit "atom2048:unlock",
name: "<NAME>, <NAME>!"
requirement: "Launch 2048 game in atom"
category: "Game Play"
package: "atom-2048"
points: 100
iconURL: "http://gabrielecirulli.github.io/2048/meta/apple-touch-icon.png"
| true | {View} = require 'atom-space-pen-views'
AchievementsView = require './achievements-view'
{CompositeDisposable, Emitter} = require 'atom'
Tile = (position, value) ->
@x = position.x
@y = position.y
@value = value or 2
@previousPosition = null
@mergedFrom = null # Tracks tiles that merged together
return
Grid = (size) ->
@size = size
@cells = []
@build()
return
KeyboardInputManager = ->
KeyboardInputManager::disposables = new CompositeDisposable()
KeyboardInputManager::events = {}
KeyboardInputManager::listen()
return
HTMLActuator = ->
@tileContainer = document.querySelector(".tile-container")
@scoreContainer = document.querySelector(".score-container")
@bestContainer = document.querySelector(".best-container")
@messageContainer = document.querySelector(".game-message")
@score = 0
return
LocalScoreManager = ->
@key = "PI:KEY:<KEY>END_PI"
supported = @localStorageSupported()
@storage = (if supported then window.localStorage else window.fakeStorage)
return
GameManager = (size, InputManager, Actuator, ScoreManager) ->
@size = size # Size of the grid
@inputManager = new InputManager
@scoreManager = new ScoreManager
@actuator = new Actuator
@startTiles = 2
@inputManager.on "move", @move.bind(this)
@inputManager.on "restart", @restart.bind(this)
@inputManager.on "keepPlaying", @keepPlaying.bind(this)
@inputManager.on "shake", @shake.bind(this)
@setup()
return
(->
lastTime = 0
vendors = [
"webkit"
"moz"
]
x = 0
while x < vendors.length and not window.requestAnimationFrame
window.requestAnimationFrame = window[vendors[x] + "RequestAnimationFrame"]
window.cancelAnimationFrame = window[vendors[x] + "CancelAnimationFrame"] or window[vendors[x] + "CancelRequestAnimationFrame"]
++x
unless window.requestAnimationFrame
window.requestAnimationFrame = (callback, element) ->
currTime = new Date().getTime()
timeToCall = Math.max(0, 16 - (currTime - lastTime))
id = window.setTimeout(->
callback currTime + timeToCall
return
, timeToCall)
lastTime = currTime + timeToCall
id
unless window.cancelAnimationFrame
window.cancelAnimationFrame = (id) ->
clearTimeout id
return
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()
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
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 = ->
!!@availableCells().length
Grid::cellAvailable = (cell) ->
not @cellOccupied(cell)
Grid::cellOccupied = (cell) ->
!!@cellContent(cell)
Grid::cellContent = (cell) ->
if @withinBounds(cell)
@cells[cell.x][cell.y]
else
null
Grid::insertTile = (tile) ->
@cells[tile.x][tile.y] = tile
return
Grid::removeTile = (tile) ->
@cells[tile.x][tile.y] = null
return
Grid::withinBounds = (position) ->
position.x >= 0 and position.x < @size and position.y >= 0 and position.y < @size
keymap =
75: 0
76: 1
74: 2
72: 3
87: 0
68: 1
83: 2
65: 3
38: 0
39: 1
40: 2
37: 3
KeyboardInputManager::on = (event, callback) ->
KeyboardInputManager::events[event] = [] unless KeyboardInputManager::events[event]
KeyboardInputManager::events[event].push callback
return
KeyboardInputManager::emit = (event, data) ->
callbacks = @events[event]
if callbacks
callbacks.forEach (callback) ->
callback data
return
return
listenerFunc = (event) ->
KeyboardInputManager::listener event
return
KeyboardInputManager::listener = (event) ->
start = new Date().getTime()
modifiers = event.altKey or event.ctrlKey or event.metaKey or event.shiftKey
mapped = keymap[event.which]
unless modifiers
event.preventDefault() unless event.which is 27 # esc key for boss
if mapped isnt `undefined`
@emit "shake"
@emit "move", mapped
@restart.bind(this) event if event.which is 32
return
KeyboardInputManager::listen = ->
self = this
atom.views.getView(atom.workspace).addEventListener "keydown", listenerFunc
# document.addEventListener "keydown", listenerFunc
retry = document.querySelector(".retry-button")
retry.addEventListener "click", @restart.bind(this)
retry.addEventListener "touchend", @restart.bind(this)
keepPlaying = document.querySelector(".keep-playing-button")
keepPlaying.addEventListener "click", @keepPlaying.bind(this)
keepPlaying.addEventListener "touchend", @keepPlaying.bind(this)
touchStartClientX = undefined
touchStartClientY = undefined
gameContainer = document.getElementsByClassName("game-container")[0]
gameContainer.addEventListener "touchstart", (event) ->
return if event.touches.length > 1
touchStartClientX = event.touches[0].clientX
touchStartClientY = event.touches[0].clientY
event.preventDefault()
return
gameContainer.addEventListener "touchmove", (event) ->
event.preventDefault()
return
gameContainer.addEventListener "touchend", (event) ->
return if event.touches.length > 0
dx = event.changedTouches[0].clientX - touchStartClientX
absDx = Math.abs(dx)
dy = event.changedTouches[0].clientY - touchStartClientY
absDy = Math.abs(dy)
self.emit "move", (if absDx > absDy then ((if dx > 0 then 1 else 3)) else ((if dy > 0 then 2 else 0))) if Math.max(absDx, absDy) > 10
return
return
KeyboardInputManager::stopListen = ->
atom.views.getView(atom.workspace).removeEventListener "keydown", listenerFunc
return
KeyboardInputManager::restart = (event) ->
event.preventDefault()
@emit "restart"
return
KeyboardInputManager::keepPlaying = (event) ->
event.preventDefault()
@emit "keepPlaying"
return
HTMLActuator::actuate = (grid, metadata) ->
self = this
window.requestAnimationFrame ->
self.clearContainer self.tileContainer
grid.cells.forEach (column) ->
column.forEach (cell) ->
self.addTile cell if cell
return
return
self.updateScore metadata.score
self.updateBestScore metadata.bestScore
if metadata.terminated
if metadata.over
self.message false
else self.message true if metadata.won
return
return
HTMLActuator::clearContainer = (container) ->
if container
container.removeChild container.firstChild while container.firstChild
return
HTMLActuator::addTile = (tile) ->
self = this
wrapper = document.createElement("div")
inner = document.createElement("div")
position = tile.previousPosition or
x: tile.x
y: tile.y
positionClass = @positionClass(position)
classes = [
"tile"
"tile-" + tile.value
positionClass
]
classes.push "tile-super" if tile.value > 2048
@applyClasses wrapper, classes
inner.classList.add "tile-inner"
inner.textContent = tile.value
if tile.previousPosition
window.requestAnimationFrame ->
classes[2] = self.positionClass(
x: tile.x
y: tile.y
)
self.applyClasses wrapper, classes
return
else if tile.mergedFrom
classes.push "tile-merged"
@applyClasses wrapper, classes
tile.mergedFrom.forEach (merged) ->
self.addTile merged
return
else
classes.push "tile-new"
@applyClasses wrapper, classes
wrapper.appendChild inner
@tileContainer.appendChild wrapper
return
HTMLActuator::applyClasses = (element, classes) ->
element.setAttribute "class", classes.join(" ")
return
HTMLActuator::normalizePosition = (position) ->
x: position.x + 1
y: position.y + 1
HTMLActuator::positionClass = (position) ->
position = @normalizePosition(position)
"tile-position-" + position.x + "-" + position.y
HTMLActuator::updateScore = (score) ->
@clearContainer @scoreContainer
difference = score - @score
@score = score
@scoreContainer.textContent = @score
if difference > 0
addition = document.createElement("div")
addition.classList.add "score-addition"
addition.textContent = "+" + difference
@scoreContainer.appendChild addition
return
HTMLActuator::updateBestScore = (bestScore) ->
@bestContainer.textContent = bestScore
return
HTMLActuator::message = (won) ->
type = (if won then "game-won" else "game-over")
message = (if won then "You win!" else "Game over!")
@messageContainer.classList.add type
@messageContainer.getElementsByTagName("p")[0].textContent = message
return
HTMLActuator::clearMessage = ->
@messageContainer.classList.remove "game-won"
@messageContainer.classList.remove "game-over"
return
HTMLActuator::continueKeep = ->
@clearMessage()
return
window.fakeStorage =
_data: {}
setItem: (id, val) ->
@_data[id] = String(val)
getItem: (id) ->
(if @_data.hasOwnProperty(id) then @_data[id] else `undefined`)
removeItem: (id) ->
delete @_data[id]
clear: ->
@_data = {}
LocalScoreManager::localStorageSupported = ->
testKey = "PI:KEY:<KEY>END_PI"
storage = window.localStorage
try
storage.setItem testKey, "1"
storage.removeItem testKey
return true
catch error
return false
return
LocalScoreManager::get = ->
@storage.getItem(@key) or 0
LocalScoreManager::set = (score) ->
@storage.setItem @key, score
return
# Restart the game
GameManager::restart = ->
@actuator.continueKeep()
@setup()
return
# Keep playing after winning
GameManager::keepPlaying = ->
@keepPlaying = true
@actuator.continueKeep()
return
GameManager::isGameTerminated = ->
if @over or (@won and not @keepPlaying)
true
else
false
# Set up the game
GameManager::setup = ->
@grid = new Grid(@size)
@score = 0
@over = false
@won = false
@keepPlaying = false
# Add the initial tiles
@addStartTiles()
# Update the actuator
@actuate()
return
# Set up the initial tiles to start the game with
GameManager::addStartTiles = ->
i = 0
while i < @startTiles
@addRandomTile()
i++
return
# Adds a tile in a random position
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
# Sends the updated grid to the actuator
GameManager::actuate = ->
@scoreManager.set @score if @scoreManager.get() < @score
@actuator.actuate @grid,
score: @score
over: @over
won: @won
bestScore: @scoreManager.get()
terminated: @isGameTerminated()
return
# Save all tile positions and remove merger info
GameManager::prepareTiles = ->
@grid.eachCell (x, y, tile) ->
if tile
tile.mergedFrom = null
tile.savePosition()
return
return
# Move a tile and its representation
GameManager::moveTile = (tile, cell) ->
@grid.cells[tile.x][tile.y] = null
@grid.cells[cell.x][cell.y] = tile
tile.updatePosition cell
return
# Move tiles on the grid in the specified direction
GameManager::move = (direction) ->
# 0: up, 1: right, 2:down, 3: left
self = this
return if @isGameTerminated() # Don't do anything if the game's over
cell = undefined
tile = undefined
vector = @getVector(direction)
traversals = @buildTraversals(vector)
moved = false
# Save the current tile positions and remove merger information
@prepareTiles()
# Traverse the grid in the right direction and move tiles
traversals.x.forEach (x) ->
traversals.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)
# Only one merger per row traversal?
if next and next.value is tile.value and not next.mergedFrom
merged = new Tile(positions.next, tile.value * 2)
atom.emitter.emit "tileChanged", value: merged.value
merged.mergedFrom = [
tile
next
]
self.grid.insertTile merged
self.grid.removeTile tile
# Converge the two tiles' positions
tile.updatePosition positions.next
# Update the score
self.score += merged.value
atom.emitter.emit "scoreChanged", value: self.score
# The mighty 2048 tile
self.won = true if merged.value is 2048
else
self.moveTile tile, positions.farthest
moved = true unless self.positionsEqual(cell, tile) # The tile moved from its original cell!
return
return
if moved
@addRandomTile()
@over = true unless @movesAvailable() # Game over!
@actuate()
return
# Get the vector representing the chosen direction
GameManager::getVector = (direction) ->
# Vectors representing tile movement
map =
0: # up
x: 0
y: -1
1: # right
x: 1
y: 0
2: # down
x: 0
y: 1
3: # left
x: -1
y: 0
map[direction]
# Build a list of positions to traverse in the right order
GameManager::buildTraversals = (vector) ->
traversals =
x: []
y: []
pos = 0
while pos < @size
traversals.x.push pos
traversals.y.push pos
pos++
# Always traverse from the farthest cell in the chosen direction
traversals.x = traversals.x.reverse() if vector.x is 1
traversals.y = traversals.y.reverse() if vector.y is 1
traversals
GameManager::findFarthestPosition = (cell, vector) ->
previous = undefined
# Progress towards the vector direction until an obstacle is found
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 # Used to check if a merge is required
GameManager::movesAvailable = ->
@grid.cellsAvailable() or @tileMatchesAvailable()
# Check for available matches between tiles (more expensive check)
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 # These two tiles can be merged
direction++
y++
x++
false
GameManager::positionsEqual = (first, second) ->
first.x is second.x and first.y is second.y
GameManager::shake = ()->
if atom.config.get('atom-2048.Enable Power Mode')
topPanels = atom.workspace.getTopPanels()
view = atom.views.getView(topPanels[0])
intensity = 1 + atom.config.get('atom-2048.Power Level') * Math.random()
x = intensity * (if Math.random() > 0.5 then -1 else 1)
y = intensity * (if Math.random() > 0.5 then -1 else 1)
view.style.top = "#{y}px"
view.style.left = "#{x}px"
setTimeout =>
view.style.top = ""
view.style.left = ""
, 75
module.exports =
class Atom2048View extends View
@disposables = null
@emitter = new Emitter
@bossMode = false
@panel = null
@content: ->
@div class: 'atom-2048 overlay from-top', =>
@div class: 'container', =>
@div class: 'heading', =>
@h1 "2048", class: 'title', =>
@div class: 'scores-container', =>
@div 0, class: 'score-container'
@div 0, class: 'best-container'
@div class: 'game-container', =>
@div class: 'game-message', =>
@p " "
@div class: 'lower', =>
@a "Keep going", class: 'keep-playing-button'
@a "Try again", class: 'retry-button'
@div class: 'grid-container', =>
@div class: 'grid-row', =>
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-row', =>
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-row', =>
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-row', =>
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class: 'grid-cell'
@div class:'tile-container'
initialize: (serializeState) ->
@bossMode = false
@disposables = new CompositeDisposable
@emitter = new Emitter
@disposables.add atom.commands.add 'atom-workspace', "atom-2048:toggle", => @toggle()
@disposables.add atom.commands.add 'atom-workspace', "atom-2048:bossComing", (e) =>
if @panel?.isVisible()
@bossComing()
else
e.abortKeyBinding()
@disposables.add atom.commands.add 'atom-workspace', "atom-2048:bossAway", => @bossAway()
@emitter.on "atom2048:unlock", @achieve
@emitter.on "tileChanged", @tileUpdated
@emitter.on "scoreChanged", @scoreUpdated
# Returns an object that can be retrieved when package is activated
serialize: ->
# Tear down any state and detach
destroy: ->
@disposables.dispose()
@emitter.dispose()
@detach()
achieve: (event) ->
if atom.packages.isPackageActive("achievements")
atom.emitter.emit "achievement:unlock",
name: event.name
requirement: event.requirement
category: event.category
package: event.packageName
points: event.points
iconURL: event.iconURL
else
achievementsView = new AchievementsView
achievementsView.achieve()
# process tile event
tileUpdated: (event) =>
if event.value is 2048
atom.emitter.emit "atom2048:unlock",
name: "Beat the game!"
requirement: "Congratulations adventurer, not everyone can do this!"
category: "Game Play"
package: "atom-2048"
points: 1600
iconURL: "http://gabrielecirulli.github.io/2048/meta/apple-touch-icon.png"
if event.value is 1024
atom.emitter.emit "atom2048:unlock",
name: "Almost there!"
requirement: "You are half way to win the game!"
category: "Game Play"
package: "atom-2048"
points: 800
iconURL: "http://gabrielecirulli.github.io/2048/meta/apple-touch-icon.png"
if event.value >= 128
atom.emitter.emit "atom2048:unlock",
name: "Got " + event.value
requirement: "First got " + event.value
category: "Game Play"
package: "atom-2048"
points: 100 * event.value / 128
iconURL: "http://gabrielecirulli.github.io/2048/meta/apple-touch-icon.png"
# process score event
scoreUpdated: (event) =>
if event.value >= 50000
atom.emitter.emit "atom2048:unlock",
name: "100K!"
requirement: "YOU ARE MY GOD!!"
category: "Game Play"
package: "atom-2048"
points: 4000
iconURL: "http://gabrielecirulli.github.io/2048/meta/apple-touch-icon.png"
if event.value >= 50000
atom.emitter.emit "atom2048:unlock",
name: "50K!"
requirement: "Are you kidding me??"
category: "Game Play"
package: "atom-2048"
points: 2000
iconURL: "http://gabrielecirulli.github.io/2048/meta/apple-touch-icon.png"
if event.value >= 30000
atom.emitter.emit "atom2048:unlock",
name: "30K!"
requirement: "Too high, too high, don't fall!"
category: "Game Play"
package: "atom-2048"
points: 1000
iconURL: "http://gabrielecirulli.github.io/2048/meta/apple-touch-icon.png"
if event.value >= 10000
atom.emitter.emit "atom2048:unlock",
name: "10K!"
requirement: "No way!"
category: "Game Play"
package: "atom-2048"
points: 500
iconURL: "http://gabrielecirulli.github.io/2048/meta/apple-touch-icon.png"
bossComing: ->
KeyboardInputManager::stopListen()
@bossMode = true
@panel?.hide()
bossAway: ->
if @bossMode and not @panel?.isVisible()
@panel ?= atom.workspace.addTopPanel(item: this)
@panel.show()
KeyboardInputManager::listen()
toggle: ->
if @panel?.isVisible()
KeyboardInputManager::stopListen()
@panel?.hide()
else
window.requestAnimationFrame ->
new GameManager(4, KeyboardInputManager, HTMLActuator, LocalScoreManager)
@panel ?= atom.workspace.addTopPanel(item: this)
@panel.show()
atom.emitter.emit "atom2048:unlock",
name: "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI!"
requirement: "Launch 2048 game in atom"
category: "Game Play"
package: "atom-2048"
points: 100
iconURL: "http://gabrielecirulli.github.io/2048/meta/apple-touch-icon.png"
|
[
{
"context": "xtends LayerInfo\n @shouldParse: (key) -> key is 'lyid'\n\n parse: ->\n @id = @file.readInt()",
"end": 130,
"score": 0.9671165943145752,
"start": 126,
"tag": "KEY",
"value": "lyid"
}
] | lib/psd/layer_info/layer_id.coffee | LoginovIlya/psd.js | 2,218 | LayerInfo = require '../layer_info.coffee'
module.exports = class LayerId extends LayerInfo
@shouldParse: (key) -> key is 'lyid'
parse: ->
@id = @file.readInt() | 139893 | LayerInfo = require '../layer_info.coffee'
module.exports = class LayerId extends LayerInfo
@shouldParse: (key) -> key is '<KEY>'
parse: ->
@id = @file.readInt() | true | LayerInfo = require '../layer_info.coffee'
module.exports = class LayerId extends LayerInfo
@shouldParse: (key) -> key is 'PI:KEY:<KEY>END_PI'
parse: ->
@id = @file.readInt() |
[
{
"context": " elements to contain accessible content.\n# @author Lisa Ring & Niklas Holmberg\n###\n\n# ------------------------",
"end": 119,
"score": 0.9998742938041687,
"start": 110,
"tag": "NAME",
"value": "Lisa Ring"
},
{
"context": " contain accessible content.\n# @author Lisa ... | src/tests/rules/anchor-has-content.coffee | danielbayley/eslint-plugin-coffee | 21 | ### eslint-env jest ###
###*
# @fileoverview Enforce anchor elements to contain accessible content.
# @author Lisa Ring & Niklas Holmberg
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{RuleTester} = require 'eslint'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require 'eslint-plugin-jsx-a11y/lib/rules/anchor-has-content'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
expectedError =
message:
'Anchors must have content and the content must be accessible by a screen reader.'
type: 'JSXOpeningElement'
ruleTester.run 'anchor-has-content', rule,
valid: [
code: '<div />'
,
code: '<a>Foo</a>'
,
code: '<a><Bar /></a>'
,
code: '<a>{foo}</a>'
,
code: '<a>{foo.bar}</a>'
,
code: '<a dangerouslySetInnerHTML={{ __html: "foo" }} />'
,
code: '<a children={children} />'
].map parserOptionsMapper
invalid: [
code: '<a />', errors: [expectedError]
,
code: '<a><Bar aria-hidden /></a>', errors: [expectedError]
,
code: '<a>{undefined}</a>', errors: [expectedError]
].map parserOptionsMapper
| 195129 | ### eslint-env jest ###
###*
# @fileoverview Enforce anchor elements to contain accessible content.
# @author <NAME> & <NAME>
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{RuleTester} = require 'eslint'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require 'eslint-plugin-jsx-a11y/lib/rules/anchor-has-content'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
expectedError =
message:
'Anchors must have content and the content must be accessible by a screen reader.'
type: 'JSXOpeningElement'
ruleTester.run 'anchor-has-content', rule,
valid: [
code: '<div />'
,
code: '<a>Foo</a>'
,
code: '<a><Bar /></a>'
,
code: '<a>{foo}</a>'
,
code: '<a>{foo.bar}</a>'
,
code: '<a dangerouslySetInnerHTML={{ __html: "foo" }} />'
,
code: '<a children={children} />'
].map parserOptionsMapper
invalid: [
code: '<a />', errors: [expectedError]
,
code: '<a><Bar aria-hidden /></a>', errors: [expectedError]
,
code: '<a>{undefined}</a>', errors: [expectedError]
].map parserOptionsMapper
| true | ### eslint-env jest ###
###*
# @fileoverview Enforce anchor elements to contain accessible content.
# @author PI:NAME:<NAME>END_PI & PI:NAME:<NAME>END_PI
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{RuleTester} = require 'eslint'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require 'eslint-plugin-jsx-a11y/lib/rules/anchor-has-content'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
expectedError =
message:
'Anchors must have content and the content must be accessible by a screen reader.'
type: 'JSXOpeningElement'
ruleTester.run 'anchor-has-content', rule,
valid: [
code: '<div />'
,
code: '<a>Foo</a>'
,
code: '<a><Bar /></a>'
,
code: '<a>{foo}</a>'
,
code: '<a>{foo.bar}</a>'
,
code: '<a dangerouslySetInnerHTML={{ __html: "foo" }} />'
,
code: '<a children={children} />'
].map parserOptionsMapper
invalid: [
code: '<a />', errors: [expectedError]
,
code: '<a><Bar aria-hidden /></a>', errors: [expectedError]
,
code: '<a>{undefined}</a>', errors: [expectedError]
].map parserOptionsMapper
|
[
{
"context": "###\n@authors\nNicolas Laplante - https://plus.google.com/108189012221374960701\nN",
"end": 29,
"score": 0.9998888969421387,
"start": 13,
"tag": "NAME",
"value": "Nicolas Laplante"
},
{
"context": "e - https://plus.google.com/108189012221374960701\nNicholas McCready - h... | public/bower_components/angular-google-maps/src/coffee/directives/polygons.coffee | arslannaseem/notasoft | 1 | ###
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
Rick Huizinga - https://plus.google.com/+RickHuizinga
###
angular.module('uiGmapgoogle-maps').directive 'uiGmapPolygons', ['uiGmapPolygons', (Polygons) -> new Polygons()]
| 226030 | ###
@authors
<NAME> - https://plus.google.com/108189012221374960701
<NAME> - https://twitter.com/nmccready
<NAME> - https://plus.google.com/+RickHuizinga
###
angular.module('uiGmapgoogle-maps').directive 'uiGmapPolygons', ['uiGmapPolygons', (Polygons) -> new Polygons()]
| true | ###
@authors
PI:NAME:<NAME>END_PI - https://plus.google.com/108189012221374960701
PI:NAME:<NAME>END_PI - https://twitter.com/nmccready
PI:NAME:<NAME>END_PI - https://plus.google.com/+RickHuizinga
###
angular.module('uiGmapgoogle-maps').directive 'uiGmapPolygons', ['uiGmapPolygons', (Polygons) -> new Polygons()]
|
[
{
"context": "ookie has github_api_key value', ->\n\n token = 'TEST_TOKEN'\n beforeEach ->\n cookies.put 'github_api_",
"end": 772,
"score": 0.7463067173957825,
"start": 762,
"tag": "PASSWORD",
"value": "TEST_TOKEN"
}
] | test/spec/services/setgithubapikeytodefaultauthorizationheader.coffee | JumpeiArashi/blog.arashike.com | 0 | 'use strict'
describe 'Service: setGithubApiKeyToDefaultAuthorizationHeader', ->
beforeEach () ->
module 'arashike-blog'
service = undefined
cookies = undefined
http = undefined
beforeEach ->
inject (_setGithubApiKeyToDefaultAuthorizationHeader_, _$cookies_, _$http_) ->
service = _setGithubApiKeyToDefaultAuthorizationHeader_
cookies = _$cookies_
http = _$http_
afterEach ->
http.defaults.headers.common.Authorization = undefined
context 'when cookie has no github_api_key value', ->
it "doesn't set default Authorization header", ->
service()
expect http.defaults.headers.common.Authorization
.to.be.equal undefined
context 'when cookie has github_api_key value', ->
token = 'TEST_TOKEN'
beforeEach ->
cookies.put 'github_api_key', token
afterEach ->
cookies.remove 'github_api_key'
it "sets \"#{token}\" to default Authorization token", ->
service()
expect http.defaults.headers.common.Authorization
.to.be.equal "token #{token}"
| 30058 | 'use strict'
describe 'Service: setGithubApiKeyToDefaultAuthorizationHeader', ->
beforeEach () ->
module 'arashike-blog'
service = undefined
cookies = undefined
http = undefined
beforeEach ->
inject (_setGithubApiKeyToDefaultAuthorizationHeader_, _$cookies_, _$http_) ->
service = _setGithubApiKeyToDefaultAuthorizationHeader_
cookies = _$cookies_
http = _$http_
afterEach ->
http.defaults.headers.common.Authorization = undefined
context 'when cookie has no github_api_key value', ->
it "doesn't set default Authorization header", ->
service()
expect http.defaults.headers.common.Authorization
.to.be.equal undefined
context 'when cookie has github_api_key value', ->
token = '<PASSWORD>'
beforeEach ->
cookies.put 'github_api_key', token
afterEach ->
cookies.remove 'github_api_key'
it "sets \"#{token}\" to default Authorization token", ->
service()
expect http.defaults.headers.common.Authorization
.to.be.equal "token #{token}"
| true | 'use strict'
describe 'Service: setGithubApiKeyToDefaultAuthorizationHeader', ->
beforeEach () ->
module 'arashike-blog'
service = undefined
cookies = undefined
http = undefined
beforeEach ->
inject (_setGithubApiKeyToDefaultAuthorizationHeader_, _$cookies_, _$http_) ->
service = _setGithubApiKeyToDefaultAuthorizationHeader_
cookies = _$cookies_
http = _$http_
afterEach ->
http.defaults.headers.common.Authorization = undefined
context 'when cookie has no github_api_key value', ->
it "doesn't set default Authorization header", ->
service()
expect http.defaults.headers.common.Authorization
.to.be.equal undefined
context 'when cookie has github_api_key value', ->
token = 'PI:PASSWORD:<PASSWORD>END_PI'
beforeEach ->
cookies.put 'github_api_key', token
afterEach ->
cookies.remove 'github_api_key'
it "sets \"#{token}\" to default Authorization token", ->
service()
expect http.defaults.headers.common.Authorization
.to.be.equal "token #{token}"
|
[
{
"context": "iv id=\"mapContent\"><h1 id=\"firstHeading\">4K Studio Karol Flont</h1><p>Może jakiś opis?</p></div>'\n\n infowindo",
"end": 718,
"score": 0.8989925980567932,
"start": 707,
"tag": "NAME",
"value": "Karol Flont"
}
] | source/assets/js/maps.js.coffee | dolphideo/4k-studio | 0 | class Maps
constructor: (options) ->
@setOptions options
@googleMaps()
googleMaps: ->
map = undefined
position = new google.maps.LatLng(52.21108, 21.01273)
pinIcon = new google.maps.MarkerImage(
'../assets/images/dolphin-icon.png'
null,
null,
null,
new google.maps.Size(40, 40))
mapOptions =
center: position
zoom: 14
map = new google.maps.Map(document.getElementById("map"), mapOptions)
marker = new google.maps.Marker
position: position
map: map
title: '4K Studio'
icon: pinIcon
animation: google.maps.Animation.DROP
contentString = '<div id="mapContent"><h1 id="firstHeading">4K Studio Karol Flont</h1><p>Może jakiś opis?</p></div>'
infowindow = new google.maps.InfoWindow
content: contentString
google.maps.event.addListener marker, 'click', ->
infowindow.open map, marker
setOptions: (options) ->
@options = @merge {}, @defaults, options
this
merge: (target, extensions...) ->
for extension in extensions
for own property of extension
target[property] = extension[property]
target
$ -> new Maps if $('#ekipa-i-kontakt').length | 32200 | class Maps
constructor: (options) ->
@setOptions options
@googleMaps()
googleMaps: ->
map = undefined
position = new google.maps.LatLng(52.21108, 21.01273)
pinIcon = new google.maps.MarkerImage(
'../assets/images/dolphin-icon.png'
null,
null,
null,
new google.maps.Size(40, 40))
mapOptions =
center: position
zoom: 14
map = new google.maps.Map(document.getElementById("map"), mapOptions)
marker = new google.maps.Marker
position: position
map: map
title: '4K Studio'
icon: pinIcon
animation: google.maps.Animation.DROP
contentString = '<div id="mapContent"><h1 id="firstHeading">4K Studio <NAME></h1><p>Może jakiś opis?</p></div>'
infowindow = new google.maps.InfoWindow
content: contentString
google.maps.event.addListener marker, 'click', ->
infowindow.open map, marker
setOptions: (options) ->
@options = @merge {}, @defaults, options
this
merge: (target, extensions...) ->
for extension in extensions
for own property of extension
target[property] = extension[property]
target
$ -> new Maps if $('#ekipa-i-kontakt').length | true | class Maps
constructor: (options) ->
@setOptions options
@googleMaps()
googleMaps: ->
map = undefined
position = new google.maps.LatLng(52.21108, 21.01273)
pinIcon = new google.maps.MarkerImage(
'../assets/images/dolphin-icon.png'
null,
null,
null,
new google.maps.Size(40, 40))
mapOptions =
center: position
zoom: 14
map = new google.maps.Map(document.getElementById("map"), mapOptions)
marker = new google.maps.Marker
position: position
map: map
title: '4K Studio'
icon: pinIcon
animation: google.maps.Animation.DROP
contentString = '<div id="mapContent"><h1 id="firstHeading">4K Studio PI:NAME:<NAME>END_PI</h1><p>Może jakiś opis?</p></div>'
infowindow = new google.maps.InfoWindow
content: contentString
google.maps.event.addListener marker, 'click', ->
infowindow.open map, marker
setOptions: (options) ->
@options = @merge {}, @defaults, options
this
merge: (target, extensions...) ->
for extension in extensions
for own property of extension
target[property] = extension[property]
target
$ -> new Maps if $('#ekipa-i-kontakt').length |
[
{
"context": ": 'Redis host'.white\n default: '127.0.0.1'\n prompt.start()\n prompt.ge",
"end": 2349,
"score": 0.9786251187324524,
"start": 2341,
"tag": "IP_ADDRESS",
"value": "27.0.0.1"
}
] | src/app/commands/init.coffee | gerardtoko/fantomas | 0 | fs = require 'fs'
nconf = require 'nconf'
prompt = require 'prompt'
path = require 'path'
colors = require 'colors'
Q = require 'Q'
U = require './../helpers/utils'
config = path.resolve './config/locale.json'
exports.command = (program, messages, regexs) ->
program
.command 'init'
.description 'Init configuration'
.option '-T, --test', 'Active test hook'
.option '-C, --nocolors', 'Disable colors'
.action (options) ->
colors.mode = 'none' if options.nocolors
config = path.resolve('./config/locale_test.json') if options.test
nconf.argv().env().file {file: config}
Q()
.then ->
deferred = Q.defer()
prompt.message = ''
prompt.delimiter = ''
schema =
properties:
storage:
pattern: regexs.storage
description: 'Storage (memory, s3, redis)'.white
message: messages.storage
default: 'memory'
required: false
prompt.start()
prompt.get schema, deferred.makeNodeResolver()
deferred.promise
.then (options) ->
deferred = Q.defer()
if options
schema =
properties:
port:
pattern: regexs.port
description: 'Port'.white
message: messages.port
type: 'number'
default: 3000
sitemaps:
description: 'Sitemaps separate by comma'.white
default: 'sitemap.xml'
generateAPIKey:
pattern: /^(yes|no)$/
description: 'Generate API Key ? (yes, no)'.white
message: 'answer must be yes or no'
default: 'yes'
nconf.set 'storage', options.storage
if options.storage is 'memory'
prompt.start()
prompt.get schema, deferred.makeNodeResolver()
if options.storage is 'redis'
schemaRedis =
properties:
port:
pattern: regexs.port
description: 'Redis port'.white
type: 'number'
default: 6379
host:
pattern: regexs.redisHost
description: 'Redis host'.white
default: '127.0.0.1'
prompt.start()
prompt.get schemaRedis, (err, options) ->
if options
nconf.set 'redisPort', options.port
nconf.set 'redisHost', options.host
prompt.start()
prompt.get schema, deferred.makeNodeResolver()
else
deferred.reject()
if options.storage is 's3'
schemaRedis =
properties:
s3KeyId:
description: 'S3 accessKeyId'.white
require: true
s3SecretKey:
description: 'S3 secretAccessKey'.white
require: true
s3Region:
description: 'S3 region'.white
require: true
s3Bucket:
description: 'S3 bucket'.white
require: true
prompt.start()
prompt.get schemaRedis, (err, options) ->
if options
nconf.set 's3KeyId', options.port
nconf.set 's3SecretKey', options.host
nconf.set 's3Region', options.port
nconf.set 's3Bucket', options.host
prompt.start()
prompt.get schema, deferred.makeNodeResolver()
else
deferred.reject()
else
deferred.reject()
deferred.promise
.then (options) ->
deferred = Q.defer()
if options
nconf.set 'port', options.port
nconf.set 'sitemaps', options.sitemaps.split ','
if options.generateAPIKey is 'yes'
deferred.resolve do U.hash
else
Q()
.then ->
_deferred = Q.defer()
prompt.start()
schema =
properties:
APIKey:
description: 'Entry API Key'.white
message: 'You must add the apiKey'
hidden: true
required: true
prompt.get schema, _deferred.makeNodeResolver()
_deferred.promise
.then (options) ->
if options
deferred.resolve(options.APIKey)
.fail (err) ->
deferred.reject()
.done()
else
deferred.reject()
deferred.promise
.then (APIKey) ->
deferred = Q.defer()
nconf.set 'apiKey', APIKey
nconf.save deferred.makeNodeResolver()
deferred.promise
.then ->
deferred = Q.defer()
fs.readFile config, deferred.makeNodeResolver()
deferred.promise
.then (data) ->
console.log 'Config file was created!'.green
conf = JSON.parse data.toString()
console.log U.format('{0}: {1}', [k.white, v]) for k, v of conf
.fail (err) ->
console.log err.message.red if err
process.exit 1
.done() | 164417 | fs = require 'fs'
nconf = require 'nconf'
prompt = require 'prompt'
path = require 'path'
colors = require 'colors'
Q = require 'Q'
U = require './../helpers/utils'
config = path.resolve './config/locale.json'
exports.command = (program, messages, regexs) ->
program
.command 'init'
.description 'Init configuration'
.option '-T, --test', 'Active test hook'
.option '-C, --nocolors', 'Disable colors'
.action (options) ->
colors.mode = 'none' if options.nocolors
config = path.resolve('./config/locale_test.json') if options.test
nconf.argv().env().file {file: config}
Q()
.then ->
deferred = Q.defer()
prompt.message = ''
prompt.delimiter = ''
schema =
properties:
storage:
pattern: regexs.storage
description: 'Storage (memory, s3, redis)'.white
message: messages.storage
default: 'memory'
required: false
prompt.start()
prompt.get schema, deferred.makeNodeResolver()
deferred.promise
.then (options) ->
deferred = Q.defer()
if options
schema =
properties:
port:
pattern: regexs.port
description: 'Port'.white
message: messages.port
type: 'number'
default: 3000
sitemaps:
description: 'Sitemaps separate by comma'.white
default: 'sitemap.xml'
generateAPIKey:
pattern: /^(yes|no)$/
description: 'Generate API Key ? (yes, no)'.white
message: 'answer must be yes or no'
default: 'yes'
nconf.set 'storage', options.storage
if options.storage is 'memory'
prompt.start()
prompt.get schema, deferred.makeNodeResolver()
if options.storage is 'redis'
schemaRedis =
properties:
port:
pattern: regexs.port
description: 'Redis port'.white
type: 'number'
default: 6379
host:
pattern: regexs.redisHost
description: 'Redis host'.white
default: '1172.16.31.10'
prompt.start()
prompt.get schemaRedis, (err, options) ->
if options
nconf.set 'redisPort', options.port
nconf.set 'redisHost', options.host
prompt.start()
prompt.get schema, deferred.makeNodeResolver()
else
deferred.reject()
if options.storage is 's3'
schemaRedis =
properties:
s3KeyId:
description: 'S3 accessKeyId'.white
require: true
s3SecretKey:
description: 'S3 secretAccessKey'.white
require: true
s3Region:
description: 'S3 region'.white
require: true
s3Bucket:
description: 'S3 bucket'.white
require: true
prompt.start()
prompt.get schemaRedis, (err, options) ->
if options
nconf.set 's3KeyId', options.port
nconf.set 's3SecretKey', options.host
nconf.set 's3Region', options.port
nconf.set 's3Bucket', options.host
prompt.start()
prompt.get schema, deferred.makeNodeResolver()
else
deferred.reject()
else
deferred.reject()
deferred.promise
.then (options) ->
deferred = Q.defer()
if options
nconf.set 'port', options.port
nconf.set 'sitemaps', options.sitemaps.split ','
if options.generateAPIKey is 'yes'
deferred.resolve do U.hash
else
Q()
.then ->
_deferred = Q.defer()
prompt.start()
schema =
properties:
APIKey:
description: 'Entry API Key'.white
message: 'You must add the apiKey'
hidden: true
required: true
prompt.get schema, _deferred.makeNodeResolver()
_deferred.promise
.then (options) ->
if options
deferred.resolve(options.APIKey)
.fail (err) ->
deferred.reject()
.done()
else
deferred.reject()
deferred.promise
.then (APIKey) ->
deferred = Q.defer()
nconf.set 'apiKey', APIKey
nconf.save deferred.makeNodeResolver()
deferred.promise
.then ->
deferred = Q.defer()
fs.readFile config, deferred.makeNodeResolver()
deferred.promise
.then (data) ->
console.log 'Config file was created!'.green
conf = JSON.parse data.toString()
console.log U.format('{0}: {1}', [k.white, v]) for k, v of conf
.fail (err) ->
console.log err.message.red if err
process.exit 1
.done() | true | fs = require 'fs'
nconf = require 'nconf'
prompt = require 'prompt'
path = require 'path'
colors = require 'colors'
Q = require 'Q'
U = require './../helpers/utils'
config = path.resolve './config/locale.json'
exports.command = (program, messages, regexs) ->
program
.command 'init'
.description 'Init configuration'
.option '-T, --test', 'Active test hook'
.option '-C, --nocolors', 'Disable colors'
.action (options) ->
colors.mode = 'none' if options.nocolors
config = path.resolve('./config/locale_test.json') if options.test
nconf.argv().env().file {file: config}
Q()
.then ->
deferred = Q.defer()
prompt.message = ''
prompt.delimiter = ''
schema =
properties:
storage:
pattern: regexs.storage
description: 'Storage (memory, s3, redis)'.white
message: messages.storage
default: 'memory'
required: false
prompt.start()
prompt.get schema, deferred.makeNodeResolver()
deferred.promise
.then (options) ->
deferred = Q.defer()
if options
schema =
properties:
port:
pattern: regexs.port
description: 'Port'.white
message: messages.port
type: 'number'
default: 3000
sitemaps:
description: 'Sitemaps separate by comma'.white
default: 'sitemap.xml'
generateAPIKey:
pattern: /^(yes|no)$/
description: 'Generate API Key ? (yes, no)'.white
message: 'answer must be yes or no'
default: 'yes'
nconf.set 'storage', options.storage
if options.storage is 'memory'
prompt.start()
prompt.get schema, deferred.makeNodeResolver()
if options.storage is 'redis'
schemaRedis =
properties:
port:
pattern: regexs.port
description: 'Redis port'.white
type: 'number'
default: 6379
host:
pattern: regexs.redisHost
description: 'Redis host'.white
default: '1PI:IP_ADDRESS:172.16.31.10END_PI'
prompt.start()
prompt.get schemaRedis, (err, options) ->
if options
nconf.set 'redisPort', options.port
nconf.set 'redisHost', options.host
prompt.start()
prompt.get schema, deferred.makeNodeResolver()
else
deferred.reject()
if options.storage is 's3'
schemaRedis =
properties:
s3KeyId:
description: 'S3 accessKeyId'.white
require: true
s3SecretKey:
description: 'S3 secretAccessKey'.white
require: true
s3Region:
description: 'S3 region'.white
require: true
s3Bucket:
description: 'S3 bucket'.white
require: true
prompt.start()
prompt.get schemaRedis, (err, options) ->
if options
nconf.set 's3KeyId', options.port
nconf.set 's3SecretKey', options.host
nconf.set 's3Region', options.port
nconf.set 's3Bucket', options.host
prompt.start()
prompt.get schema, deferred.makeNodeResolver()
else
deferred.reject()
else
deferred.reject()
deferred.promise
.then (options) ->
deferred = Q.defer()
if options
nconf.set 'port', options.port
nconf.set 'sitemaps', options.sitemaps.split ','
if options.generateAPIKey is 'yes'
deferred.resolve do U.hash
else
Q()
.then ->
_deferred = Q.defer()
prompt.start()
schema =
properties:
APIKey:
description: 'Entry API Key'.white
message: 'You must add the apiKey'
hidden: true
required: true
prompt.get schema, _deferred.makeNodeResolver()
_deferred.promise
.then (options) ->
if options
deferred.resolve(options.APIKey)
.fail (err) ->
deferred.reject()
.done()
else
deferred.reject()
deferred.promise
.then (APIKey) ->
deferred = Q.defer()
nconf.set 'apiKey', APIKey
nconf.save deferred.makeNodeResolver()
deferred.promise
.then ->
deferred = Q.defer()
fs.readFile config, deferred.makeNodeResolver()
deferred.promise
.then (data) ->
console.log 'Config file was created!'.green
conf = JSON.parse data.toString()
console.log U.format('{0}: {1}', [k.white, v]) for k, v of conf
.fail (err) ->
console.log err.message.red if err
process.exit 1
.done() |
[
{
"context": " {\n clientID: \"APP_ID\",\n clientSecret: \"APP_SECRET\",\n callbackURL: \"http://localhost:300",
"end": 1845,
"score": 0.8507148027420044,
"start": 1842,
"tag": "KEY",
"value": "APP"
}
] | src/config/config.coffee | yi/coffee-nodejs-passport-boilerplate | 1 |
path = require('path')
rootPath = path.normalize(__dirname + '/../..')
console.log "[config::rootPath] #{rootPath}"
templatePath = path.normalize(__dirname + '/../app/mailer/templates')
notifier =
APN: false,
email: false, # true
actions: ['comment'],
tplPath: templatePath,
postmarkKey: 'POSTMARK_KEY',
parseAppId: 'PARSE_APP_ID',
parseApiKey: 'PARSE_MASTER_KEY'
module.exports = {
development: {
db: 'mongodb://localhost/noobjs_dev',
root: rootPath,
notifier: notifier,
app: {
name: 'Nodejs Passport Boilerplate Demo'
},
facebook: {
clientID: "APP_ID",
clientSecret: "APP_SECRET",
callbackURL: "http://localhost:3000/auth/facebook/callback"
},
twitter: {
clientID: "CONSUMER_KEY",
clientSecret: "CONSUMER_SECRET",
callbackURL: "http://localhost:3000/auth/twitter/callback"
},
github: {
clientID: 'APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/github/callback'
},
google: {
clientID: "APP_ID",
clientSecret: "APP_SECRET",
callbackURL: "http://localhost:3000/auth/google/callback"
},
},
test: {
db: 'mongodb://localhost/noobjs_test',
root: rootPath,
notifier: notifier,
app: {
name: 'Nodejs Express Mongoose Demo'
},
facebook: {
clientID: "APP_ID",
clientSecret: "APP_SECRET",
callbackURL: "http://localhost:3000/auth/facebook/callback"
},
twitter: {
clientID: "CONSUMER_KEY",
clientSecret: "CONSUMER_SECRET",
callbackURL: "http://localhost:3000/auth/twitter/callback"
},
github: {
clientID: 'APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/github/callback'
},
google: {
clientID: "APP_ID",
clientSecret: "APP_SECRET",
callbackURL: "http://localhost:3000/auth/google/callback"
}
},
production: {}
}
| 129450 |
path = require('path')
rootPath = path.normalize(__dirname + '/../..')
console.log "[config::rootPath] #{rootPath}"
templatePath = path.normalize(__dirname + '/../app/mailer/templates')
notifier =
APN: false,
email: false, # true
actions: ['comment'],
tplPath: templatePath,
postmarkKey: 'POSTMARK_KEY',
parseAppId: 'PARSE_APP_ID',
parseApiKey: 'PARSE_MASTER_KEY'
module.exports = {
development: {
db: 'mongodb://localhost/noobjs_dev',
root: rootPath,
notifier: notifier,
app: {
name: 'Nodejs Passport Boilerplate Demo'
},
facebook: {
clientID: "APP_ID",
clientSecret: "APP_SECRET",
callbackURL: "http://localhost:3000/auth/facebook/callback"
},
twitter: {
clientID: "CONSUMER_KEY",
clientSecret: "CONSUMER_SECRET",
callbackURL: "http://localhost:3000/auth/twitter/callback"
},
github: {
clientID: 'APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/github/callback'
},
google: {
clientID: "APP_ID",
clientSecret: "APP_SECRET",
callbackURL: "http://localhost:3000/auth/google/callback"
},
},
test: {
db: 'mongodb://localhost/noobjs_test',
root: rootPath,
notifier: notifier,
app: {
name: 'Nodejs Express Mongoose Demo'
},
facebook: {
clientID: "APP_ID",
clientSecret: "APP_SECRET",
callbackURL: "http://localhost:3000/auth/facebook/callback"
},
twitter: {
clientID: "CONSUMER_KEY",
clientSecret: "CONSUMER_SECRET",
callbackURL: "http://localhost:3000/auth/twitter/callback"
},
github: {
clientID: 'APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/github/callback'
},
google: {
clientID: "APP_ID",
clientSecret: "<KEY>_SECRET",
callbackURL: "http://localhost:3000/auth/google/callback"
}
},
production: {}
}
| true |
path = require('path')
rootPath = path.normalize(__dirname + '/../..')
console.log "[config::rootPath] #{rootPath}"
templatePath = path.normalize(__dirname + '/../app/mailer/templates')
notifier =
APN: false,
email: false, # true
actions: ['comment'],
tplPath: templatePath,
postmarkKey: 'POSTMARK_KEY',
parseAppId: 'PARSE_APP_ID',
parseApiKey: 'PARSE_MASTER_KEY'
module.exports = {
development: {
db: 'mongodb://localhost/noobjs_dev',
root: rootPath,
notifier: notifier,
app: {
name: 'Nodejs Passport Boilerplate Demo'
},
facebook: {
clientID: "APP_ID",
clientSecret: "APP_SECRET",
callbackURL: "http://localhost:3000/auth/facebook/callback"
},
twitter: {
clientID: "CONSUMER_KEY",
clientSecret: "CONSUMER_SECRET",
callbackURL: "http://localhost:3000/auth/twitter/callback"
},
github: {
clientID: 'APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/github/callback'
},
google: {
clientID: "APP_ID",
clientSecret: "APP_SECRET",
callbackURL: "http://localhost:3000/auth/google/callback"
},
},
test: {
db: 'mongodb://localhost/noobjs_test',
root: rootPath,
notifier: notifier,
app: {
name: 'Nodejs Express Mongoose Demo'
},
facebook: {
clientID: "APP_ID",
clientSecret: "APP_SECRET",
callbackURL: "http://localhost:3000/auth/facebook/callback"
},
twitter: {
clientID: "CONSUMER_KEY",
clientSecret: "CONSUMER_SECRET",
callbackURL: "http://localhost:3000/auth/twitter/callback"
},
github: {
clientID: 'APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/github/callback'
},
google: {
clientID: "APP_ID",
clientSecret: "PI:KEY:<KEY>END_PI_SECRET",
callbackURL: "http://localhost:3000/auth/google/callback"
}
},
production: {}
}
|
[
{
"context": "###\n *\n * Responsive Navigation by Gary Hepting\n *\n * Open source under the MIT License.\n *\n * ",
"end": 48,
"score": 0.9998644590377808,
"start": 36,
"tag": "NAME",
"value": "Gary Hepting"
},
{
"context": "rce under the MIT License.\n *\n * Copyright © 2013 G... | src/coffee/components/navigation.coffee | katophelix/PristinePooch | 357 | ###
*
* Responsive Navigation by Gary Hepting
*
* Open source under the MIT License.
*
* Copyright © 2013 Gary Hepting. All rights reserved.
*
###
responsiveNavigationIndex = 0
window.delayMenuClose = ''
window.delayNavigationClose = ''
class ResponsiveNavigation
constructor: (el) ->
@index = responsiveNavigationIndex++
@el = $(el)
@init()
init: ->
@defaultLabel()
@setupMarkers()
unless @el.hasClass('nocollapse')
@hamburgerHelper()
defaultLabel: ->
unless @el.hasClass('nocollapse')
@el.attr('title', 'Menu') if @el.attr('title') == undefined
setupMarkers: ->
@el.find('ul').each ->
if $(@).find('li').length
$(@).attr('role', 'menu')
@el.find('> ul').attr('role', 'menubar') unless $(@el).hasClass('vertical')
@el.find('li').each ->
if $(@).find('ul').length
$(@).attr('role', 'menu')
hamburgerHelper: ->
@el.prepend('<button class="hamburger"></button>')
$ ->
mouseBindings = -> # needs more <3
$('body').on 'mouseenter', '.nav:not(.vertical) li[role="menu"]', (e) ->
$('.nav:not(.vertical)').not(@).each ->
unless $(@).find('button.hamburger').is(':visible')
$(@).find('ul[aria-expanded="true"]').attr('aria-expanded', 'false')
unless $(@).parents('.nav').find('button.hamburger').is(':visible')
clearTimeout(window.delayMenuClose)
expandedSiblings = $(@).siblings().find('ul[aria-expanded="true"]')
expandedSiblings.attr('aria-expanded', 'false')
targetMenu = $(e.target).parents('li[role="menu"]').children('ul')
targetMenu.attr('aria-expanded', 'true')
$('body').on 'mouseleave', '.nav:not(.vertical) li[role="menu"]', (e) ->
unless $(@).parents('.nav').find('button.hamburger').is(':visible')
window.delayMenuClose = setTimeout( =>
$(@).find('ul[aria-expanded="true"]').attr('aria-expanded', 'false')
, 500)
touchBindings = ->
$('body').on 'click', '.nav li[role="menu"] > a,
.nav li[role="menu"] > button', (e) ->
list = $(@).siblings('ul')
menu = $(@).parent('[role="menu"]')
if list.attr('aria-expanded') != 'true'
list.attr('aria-expanded', 'true')
else
list.attr('aria-expanded', 'false')
list.find('[aria-expanded="true"]').attr('aria-expanded', 'false')
if menu.attr('aria-pressed') != 'true'
menu.attr('aria-pressed', 'true')
else
menu.attr('aria-pressed', 'false')
menu.find('[aria-pressed="true"]').attr('aria-pressed', 'false')
menu.find('[aria-expanded="true"]').attr('aria-expanded', 'false')
e.preventDefault()
$('body').on 'click', '.nav button.hamburger', (e) ->
list = $(@).siblings('ul')
if list.attr('aria-expanded') != 'true'
list.attr('aria-expanded', 'true')
else
list.attr('aria-expanded', 'false')
list.find('[aria-pressed="true"]').attr('aria-pressed', 'false')
list.find('[aria-expanded="true"]').attr('aria-expanded', 'false')
e.preventDefault()
responsiveNavigationElements = []
$('.nav').each ->
responsiveNavigationElements.push( new ResponsiveNavigation(@) )
# initialize bindings
touchBindings()
unless Modernizr.touch
mouseBindings()
| 139168 | ###
*
* Responsive Navigation by <NAME>
*
* Open source under the MIT License.
*
* Copyright © 2013 <NAME>. All rights reserved.
*
###
responsiveNavigationIndex = 0
window.delayMenuClose = ''
window.delayNavigationClose = ''
class ResponsiveNavigation
constructor: (el) ->
@index = responsiveNavigationIndex++
@el = $(el)
@init()
init: ->
@defaultLabel()
@setupMarkers()
unless @el.hasClass('nocollapse')
@hamburgerHelper()
defaultLabel: ->
unless @el.hasClass('nocollapse')
@el.attr('title', 'Menu') if @el.attr('title') == undefined
setupMarkers: ->
@el.find('ul').each ->
if $(@).find('li').length
$(@).attr('role', 'menu')
@el.find('> ul').attr('role', 'menubar') unless $(@el).hasClass('vertical')
@el.find('li').each ->
if $(@).find('ul').length
$(@).attr('role', 'menu')
hamburgerHelper: ->
@el.prepend('<button class="hamburger"></button>')
$ ->
mouseBindings = -> # needs more <3
$('body').on 'mouseenter', '.nav:not(.vertical) li[role="menu"]', (e) ->
$('.nav:not(.vertical)').not(@).each ->
unless $(@).find('button.hamburger').is(':visible')
$(@).find('ul[aria-expanded="true"]').attr('aria-expanded', 'false')
unless $(@).parents('.nav').find('button.hamburger').is(':visible')
clearTimeout(window.delayMenuClose)
expandedSiblings = $(@).siblings().find('ul[aria-expanded="true"]')
expandedSiblings.attr('aria-expanded', 'false')
targetMenu = $(e.target).parents('li[role="menu"]').children('ul')
targetMenu.attr('aria-expanded', 'true')
$('body').on 'mouseleave', '.nav:not(.vertical) li[role="menu"]', (e) ->
unless $(@).parents('.nav').find('button.hamburger').is(':visible')
window.delayMenuClose = setTimeout( =>
$(@).find('ul[aria-expanded="true"]').attr('aria-expanded', 'false')
, 500)
touchBindings = ->
$('body').on 'click', '.nav li[role="menu"] > a,
.nav li[role="menu"] > button', (e) ->
list = $(@).siblings('ul')
menu = $(@).parent('[role="menu"]')
if list.attr('aria-expanded') != 'true'
list.attr('aria-expanded', 'true')
else
list.attr('aria-expanded', 'false')
list.find('[aria-expanded="true"]').attr('aria-expanded', 'false')
if menu.attr('aria-pressed') != 'true'
menu.attr('aria-pressed', 'true')
else
menu.attr('aria-pressed', 'false')
menu.find('[aria-pressed="true"]').attr('aria-pressed', 'false')
menu.find('[aria-expanded="true"]').attr('aria-expanded', 'false')
e.preventDefault()
$('body').on 'click', '.nav button.hamburger', (e) ->
list = $(@).siblings('ul')
if list.attr('aria-expanded') != 'true'
list.attr('aria-expanded', 'true')
else
list.attr('aria-expanded', 'false')
list.find('[aria-pressed="true"]').attr('aria-pressed', 'false')
list.find('[aria-expanded="true"]').attr('aria-expanded', 'false')
e.preventDefault()
responsiveNavigationElements = []
$('.nav').each ->
responsiveNavigationElements.push( new ResponsiveNavigation(@) )
# initialize bindings
touchBindings()
unless Modernizr.touch
mouseBindings()
| true | ###
*
* Responsive Navigation by PI:NAME:<NAME>END_PI
*
* Open source under the MIT License.
*
* Copyright © 2013 PI:NAME:<NAME>END_PI. All rights reserved.
*
###
responsiveNavigationIndex = 0
window.delayMenuClose = ''
window.delayNavigationClose = ''
class ResponsiveNavigation
constructor: (el) ->
@index = responsiveNavigationIndex++
@el = $(el)
@init()
init: ->
@defaultLabel()
@setupMarkers()
unless @el.hasClass('nocollapse')
@hamburgerHelper()
defaultLabel: ->
unless @el.hasClass('nocollapse')
@el.attr('title', 'Menu') if @el.attr('title') == undefined
setupMarkers: ->
@el.find('ul').each ->
if $(@).find('li').length
$(@).attr('role', 'menu')
@el.find('> ul').attr('role', 'menubar') unless $(@el).hasClass('vertical')
@el.find('li').each ->
if $(@).find('ul').length
$(@).attr('role', 'menu')
hamburgerHelper: ->
@el.prepend('<button class="hamburger"></button>')
$ ->
mouseBindings = -> # needs more <3
$('body').on 'mouseenter', '.nav:not(.vertical) li[role="menu"]', (e) ->
$('.nav:not(.vertical)').not(@).each ->
unless $(@).find('button.hamburger').is(':visible')
$(@).find('ul[aria-expanded="true"]').attr('aria-expanded', 'false')
unless $(@).parents('.nav').find('button.hamburger').is(':visible')
clearTimeout(window.delayMenuClose)
expandedSiblings = $(@).siblings().find('ul[aria-expanded="true"]')
expandedSiblings.attr('aria-expanded', 'false')
targetMenu = $(e.target).parents('li[role="menu"]').children('ul')
targetMenu.attr('aria-expanded', 'true')
$('body').on 'mouseleave', '.nav:not(.vertical) li[role="menu"]', (e) ->
unless $(@).parents('.nav').find('button.hamburger').is(':visible')
window.delayMenuClose = setTimeout( =>
$(@).find('ul[aria-expanded="true"]').attr('aria-expanded', 'false')
, 500)
touchBindings = ->
$('body').on 'click', '.nav li[role="menu"] > a,
.nav li[role="menu"] > button', (e) ->
list = $(@).siblings('ul')
menu = $(@).parent('[role="menu"]')
if list.attr('aria-expanded') != 'true'
list.attr('aria-expanded', 'true')
else
list.attr('aria-expanded', 'false')
list.find('[aria-expanded="true"]').attr('aria-expanded', 'false')
if menu.attr('aria-pressed') != 'true'
menu.attr('aria-pressed', 'true')
else
menu.attr('aria-pressed', 'false')
menu.find('[aria-pressed="true"]').attr('aria-pressed', 'false')
menu.find('[aria-expanded="true"]').attr('aria-expanded', 'false')
e.preventDefault()
$('body').on 'click', '.nav button.hamburger', (e) ->
list = $(@).siblings('ul')
if list.attr('aria-expanded') != 'true'
list.attr('aria-expanded', 'true')
else
list.attr('aria-expanded', 'false')
list.find('[aria-pressed="true"]').attr('aria-pressed', 'false')
list.find('[aria-expanded="true"]').attr('aria-expanded', 'false')
e.preventDefault()
responsiveNavigationElements = []
$('.nav').each ->
responsiveNavigationElements.push( new ResponsiveNavigation(@) )
# initialize bindings
touchBindings()
unless Modernizr.touch
mouseBindings()
|
[
{
"context": "il = Package.email.Email\n\t\t\t\tEmail.send\n\t\t\t\t\tto: 'support@steedos.com'\n\t\t\t\t\tfrom: Accounts.emailTemplates.from\n\t\t\t\t\tsub",
"end": 792,
"score": 0.9999284148216248,
"start": 773,
"tag": "EMAIL",
"value": "support@steedos.com"
}
] | creator/packages/steedos-base/server/methods/billing_settleup.coffee | yicone/steedos-platform | 42 | Meteor.methods
billing_settleup: (accounting_month, space_id="")->
check(accounting_month, String)
check(space_id, String)
user = db.users.findOne({_id: this.userId}, {fields: {is_cloudadmin: 1}})
if not user.is_cloudadmin
return
console.time 'billing'
spaces = []
if space_id
spaces = db.spaces.find({_id: space_id, is_paid: true}, {fields: {_id: 1}})
else
spaces = db.spaces.find({is_paid: true}, {fields: {_id: 1}})
result = []
spaces.forEach (s) ->
try
billingManager.caculate_by_accounting_month(accounting_month, s._id)
catch err
e = {}
e._id = s._id
e.name = s.name
e.err = err
result.push e
if result.length > 0
console.error result
try
Email = Package.email.Email
Email.send
to: 'support@steedos.com'
from: Accounts.emailTemplates.from
subject: 'billing settleup result'
text: JSON.stringify('result': result)
catch err
console.error err
console.timeEnd 'billing' | 215986 | Meteor.methods
billing_settleup: (accounting_month, space_id="")->
check(accounting_month, String)
check(space_id, String)
user = db.users.findOne({_id: this.userId}, {fields: {is_cloudadmin: 1}})
if not user.is_cloudadmin
return
console.time 'billing'
spaces = []
if space_id
spaces = db.spaces.find({_id: space_id, is_paid: true}, {fields: {_id: 1}})
else
spaces = db.spaces.find({is_paid: true}, {fields: {_id: 1}})
result = []
spaces.forEach (s) ->
try
billingManager.caculate_by_accounting_month(accounting_month, s._id)
catch err
e = {}
e._id = s._id
e.name = s.name
e.err = err
result.push e
if result.length > 0
console.error result
try
Email = Package.email.Email
Email.send
to: '<EMAIL>'
from: Accounts.emailTemplates.from
subject: 'billing settleup result'
text: JSON.stringify('result': result)
catch err
console.error err
console.timeEnd 'billing' | true | Meteor.methods
billing_settleup: (accounting_month, space_id="")->
check(accounting_month, String)
check(space_id, String)
user = db.users.findOne({_id: this.userId}, {fields: {is_cloudadmin: 1}})
if not user.is_cloudadmin
return
console.time 'billing'
spaces = []
if space_id
spaces = db.spaces.find({_id: space_id, is_paid: true}, {fields: {_id: 1}})
else
spaces = db.spaces.find({is_paid: true}, {fields: {_id: 1}})
result = []
spaces.forEach (s) ->
try
billingManager.caculate_by_accounting_month(accounting_month, s._id)
catch err
e = {}
e._id = s._id
e.name = s.name
e.err = err
result.push e
if result.length > 0
console.error result
try
Email = Package.email.Email
Email.send
to: 'PI:EMAIL:<EMAIL>END_PI'
from: Accounts.emailTemplates.from
subject: 'billing settleup result'
text: JSON.stringify('result': result)
catch err
console.error err
console.timeEnd 'billing' |
[
{
"context": "### @license\nWishlist\nhttps://github.com/zhanzhenzhen/wishlist\nCopyright 2015 Zhenzhen Zhan\nReleased un",
"end": 53,
"score": 0.9988524317741394,
"start": 41,
"tag": "USERNAME",
"value": "zhanzhenzhen"
},
{
"context": "://github.com/zhanzhenzhen/wishlist\nCopyright ... | src/1.license.coffee | zhanzhenzhen/wishlist | 0 | ### @license
Wishlist
https://github.com/zhanzhenzhen/wishlist
Copyright 2015 Zhenzhen Zhan
Released under the MIT license
###
| 207135 | ### @license
Wishlist
https://github.com/zhanzhenzhen/wishlist
Copyright 2015 <NAME>
Released under the MIT license
###
| true | ### @license
Wishlist
https://github.com/zhanzhenzhen/wishlist
Copyright 2015 PI:NAME:<NAME>END_PI
Released under the MIT license
###
|
[
{
"context": ".SetIndex',\n setup: ->\n @zeke = Batman name: 'Zeke'\n @mary = Batman name: 'Mary'\n @fred = Batm",
"end": 74,
"score": 0.9990407824516296,
"start": 70,
"tag": "NAME",
"value": "Zeke"
},
{
"context": "e = Batman name: 'Zeke'\n @mary = Batman name: 'Mary'\n... | tests/batman/set/set_index_test.coffee | nickjs/batman | 1 | QUnit.module 'Batman.SetIndex',
setup: ->
@zeke = Batman name: 'Zeke'
@mary = Batman name: 'Mary'
@fred = Batman name: 'Fred'
@jill = Batman name: 'Jill'
@byZeke = Batman author: @zeke
@byMary = Batman author: @mary
@byFred = Batman author: @fred
@anotherByFred = Batman author: @fred
@base = new Batman.Set(@byMary, @byFred, @byZeke, @anotherByFred)
@authorNameIndex = new Batman.SetIndex(@base, 'author.name')
# not yet in the set:
@byJill = Batman author: @jill
@anotherByZeke = Batman author: @zeke
test "new Batman.SetIndex(set, key) constructs an index on the set for that keypath", ->
equal @authorNameIndex.base, @base
equal @authorNameIndex.key, 'author.name'
test "new Batman.SetIndex(set, key) with unobservable items will observe the set but not the items", ->
set = new Batman.Set("foo", "bar", "ba")
setSpy = spyOn(set, 'observe')
fooSpy = spyOn(@zeke, 'observe')
barSpy = spyOn(@mary, 'observe')
baSpy = spyOn(@mary, 'observe')
simpleIndex = new Batman.SetIndex(set, 'length')
deepEqual simpleIndex.get(3).toArray(), ["foo", "bar"]
ok setSpy.called, "the set should be observed"
ok !fooSpy.called, "the items should not be observed"
ok !barSpy.called, "the items should not be observed"
ok !baSpy.called, "the items should not be observed"
test "new Batman.SetIndex(set, key) with a Batman.SimpleSet indexes the items but doesn't observe anything", ->
set = new Batman.SimpleSet(@zeke, @mary)
setSpy = spyOn(set, 'observe')
zekeSpy = spyOn(@zeke, 'observe')
marySpy = spyOn(@mary, 'observe')
simpleIndex = new Batman.SetIndex(set, 'name')
deepEqual simpleIndex.get('Zeke').toArray(), [@zeke]
ok !setSpy.called, "the set should not be observed"
ok !zekeSpy.called, "the items should not be observed"
ok !marySpy.called, "the items should not be observed"
test "get(value) returns a Batman.Set of items indexed on that value for the index's key", ->
allByFred = @authorNameIndex.get("Fred")
equal allByFred.length, 2
ok allByFred.has(@byFred)
ok allByFred.has(@anotherByFred)
test "the result set from get(value) should be updated to remove items which are removed from the underlying set", ->
allByFred = @authorNameIndex.get("Fred")
allByFred.observe 'itemsWereRemoved', observer = createSpy()
@base.remove(@anotherByFred)
equal observer.lastCallArguments.length, 1
ok observer.lastCallArguments[0] is @anotherByFred
equal allByFred.has(@anotherByFred), false
test "the result set from get(value) should be updated to add matching items when they are added to the underlying set", ->
allByZeke = @authorNameIndex.get("Zeke")
allByZeke.observe 'itemsWereAdded', observer = createSpy()
@base.add @anotherByZeke
equal observer.lastCallArguments.length, 1
ok observer.lastCallArguments[0] is @anotherByZeke
equal allByZeke.has(@anotherByZeke), true
test "the result set from get(value) should not be updated to add items which don't match the value", ->
allByFred = @authorNameIndex.get("Fred")
allByFred.observe 'itemsWereAdded', observer = createSpy()
@base.add @anotherByZeke
equal observer.called, false
equal allByFred.has(@anotherByZeke), false
test "adding items with as-yet-unused index keys should add them to the appropriate result sets", ->
@base.add @byJill
allByJill = @authorNameIndex.get("Jill")
equal allByJill.length, 1
ok allByJill.has(@byJill)
test "setting a new value of the indexed property on one of the items triggers an update", ->
allByFred = @authorNameIndex.get("Fred")
allByMary = @authorNameIndex.get("Mary")
@byFred.set('author', @mary)
equal allByFred.has(@byFred), false
equal allByMary.has(@byFred), true
test "setting a new value of the indexed property on an item which has been removed should not trigger an update", ->
allByMary = @authorNameIndex.get("Mary")
@base.remove(@byFred)
@byFred.set('author', @mary)
equal allByMary.has(@byFred), false
test "items with undefined values for the indexed key are grouped together as with any other value, and don't collide with null values", ->
noAuthor = Batman()
anotherNoAuthor = Batman()
nullAuthor = Batman
author: Batman
name: null
@base.add noAuthor
@base.add anotherNoAuthor
allByNobody = @authorNameIndex.get(undefined)
equal allByNobody.length, 2
equal allByNobody.has(noAuthor), true
equal allByNobody.has(anotherNoAuthor), true
equal allByNobody.has(Batman()), false
test "stopObserving() forgets all observers", ->
@authorNameIndex.stopObserving()
@base.add @byJill
equal @authorNameIndex.get("Jill").length, 0
@base.remove @byZeke
equal @authorNameIndex.get("Zeke").length, 1
@byFred.set('author', @mary)
equal @authorNameIndex.get("Fred").has(@byFred), true
equal @authorNameIndex.get("Mary").has(@byFred), false
| 61322 | QUnit.module 'Batman.SetIndex',
setup: ->
@zeke = Batman name: '<NAME>'
@mary = Batman name: '<NAME>'
@fred = Batman name: '<NAME>'
@jill = Batman name: '<NAME>'
@byZeke = Batman author: @zeke
@byMary = Batman author: @mary
@byFred = Batman author: @fred
@anotherByFred = Batman author: @fred
@base = new Batman.Set(@byMary, @byFred, @byZeke, @anotherByFred)
@authorNameIndex = new Batman.SetIndex(@base, 'author.name')
# not yet in the set:
@byJill = Batman author: @jill
@anotherByZeke = Batman author: @zeke
test "new Batman.SetIndex(set, key) constructs an index on the set for that keypath", ->
equal @authorNameIndex.base, @base
equal @authorNameIndex.key, 'author.name'
test "new Batman.SetIndex(set, key) with unobservable items will observe the set but not the items", ->
set = new Batman.Set("foo", "bar", "ba")
setSpy = spyOn(set, 'observe')
fooSpy = spyOn(@zeke, 'observe')
barSpy = spyOn(@mary, 'observe')
baSpy = spyOn(@mary, 'observe')
simpleIndex = new Batman.SetIndex(set, 'length')
deepEqual simpleIndex.get(3).toArray(), ["foo", "bar"]
ok setSpy.called, "the set should be observed"
ok !fooSpy.called, "the items should not be observed"
ok !barSpy.called, "the items should not be observed"
ok !baSpy.called, "the items should not be observed"
test "new Batman.SetIndex(set, key) with a Batman.SimpleSet indexes the items but doesn't observe anything", ->
set = new Batman.SimpleSet(@zeke, @mary)
setSpy = spyOn(set, 'observe')
zekeSpy = spyOn(@zeke, 'observe')
marySpy = spyOn(@mary, 'observe')
simpleIndex = new Batman.SetIndex(set, 'name')
deepEqual simpleIndex.get('Zeke').toArray(), [@zeke]
ok !setSpy.called, "the set should not be observed"
ok !zekeSpy.called, "the items should not be observed"
ok !marySpy.called, "the items should not be observed"
test "get(value) returns a Batman.Set of items indexed on that value for the index's key", ->
allByFred = @authorNameIndex.get("<NAME>")
equal allByFred.length, 2
ok allByFred.has(@byFred)
ok allByFred.has(@anotherByFred)
test "the result set from get(value) should be updated to remove items which are removed from the underlying set", ->
allByFred = @authorNameIndex.get("<NAME>")
allByFred.observe 'itemsWereRemoved', observer = createSpy()
@base.remove(@anotherByFred)
equal observer.lastCallArguments.length, 1
ok observer.lastCallArguments[0] is @anotherByFred
equal allByFred.has(@anotherByFred), false
test "the result set from get(value) should be updated to add matching items when they are added to the underlying set", ->
allByZeke = @authorNameIndex.get("<NAME>")
allByZeke.observe 'itemsWereAdded', observer = createSpy()
@base.add @anotherByZeke
equal observer.lastCallArguments.length, 1
ok observer.lastCallArguments[0] is @anotherByZeke
equal allByZeke.has(@anotherByZeke), true
test "the result set from get(value) should not be updated to add items which don't match the value", ->
allByFred = @authorNameIndex.get("<NAME>")
allByFred.observe 'itemsWereAdded', observer = createSpy()
@base.add @anotherByZeke
equal observer.called, false
equal allByFred.has(@anotherByZeke), false
test "adding items with as-yet-unused index keys should add them to the appropriate result sets", ->
@base.add @byJill
allByJill = @authorNameIndex.get("<NAME>")
equal allByJill.length, 1
ok allByJill.has(@byJill)
test "setting a new value of the indexed property on one of the items triggers an update", ->
allByFred = @authorNameIndex.get("<NAME>")
allByMary = @authorNameIndex.get("<NAME>")
@byFred.set('author', @mary)
equal allByFred.has(@byFred), false
equal allByMary.has(@byFred), true
test "setting a new value of the indexed property on an item which has been removed should not trigger an update", ->
allByMary = @authorNameIndex.get("<NAME>")
@base.remove(@byFred)
@byFred.set('author', @mary)
equal allByMary.has(@byFred), false
test "items with undefined values for the indexed key are grouped together as with any other value, and don't collide with null values", ->
noAuthor = Batman()
anotherNoAuthor = Batman()
nullAuthor = Batman
author: <NAME>
name: null
@base.add noAuthor
@base.add anotherNoAuthor
allByNobody = @authorNameIndex.get(undefined)
equal allByNobody.length, 2
equal allByNobody.has(noAuthor), true
equal allByNobody.has(anotherNoAuthor), true
equal allByNobody.has(Batman()), false
test "stopObserving() forgets all observers", ->
@authorNameIndex.stopObserving()
@base.add @byJill
equal @authorNameIndex.get("<NAME>").length, 0
@base.remove @byZeke
equal @authorNameIndex.get("<NAME>").length, 1
@byFred.set('author', @mary)
equal @authorNameIndex.get("Fred").has(@byFred), true
equal @authorNameIndex.get("<NAME>").has(@byFred), false
| true | QUnit.module 'Batman.SetIndex',
setup: ->
@zeke = Batman name: 'PI:NAME:<NAME>END_PI'
@mary = Batman name: 'PI:NAME:<NAME>END_PI'
@fred = Batman name: 'PI:NAME:<NAME>END_PI'
@jill = Batman name: 'PI:NAME:<NAME>END_PI'
@byZeke = Batman author: @zeke
@byMary = Batman author: @mary
@byFred = Batman author: @fred
@anotherByFred = Batman author: @fred
@base = new Batman.Set(@byMary, @byFred, @byZeke, @anotherByFred)
@authorNameIndex = new Batman.SetIndex(@base, 'author.name')
# not yet in the set:
@byJill = Batman author: @jill
@anotherByZeke = Batman author: @zeke
test "new Batman.SetIndex(set, key) constructs an index on the set for that keypath", ->
equal @authorNameIndex.base, @base
equal @authorNameIndex.key, 'author.name'
test "new Batman.SetIndex(set, key) with unobservable items will observe the set but not the items", ->
set = new Batman.Set("foo", "bar", "ba")
setSpy = spyOn(set, 'observe')
fooSpy = spyOn(@zeke, 'observe')
barSpy = spyOn(@mary, 'observe')
baSpy = spyOn(@mary, 'observe')
simpleIndex = new Batman.SetIndex(set, 'length')
deepEqual simpleIndex.get(3).toArray(), ["foo", "bar"]
ok setSpy.called, "the set should be observed"
ok !fooSpy.called, "the items should not be observed"
ok !barSpy.called, "the items should not be observed"
ok !baSpy.called, "the items should not be observed"
test "new Batman.SetIndex(set, key) with a Batman.SimpleSet indexes the items but doesn't observe anything", ->
set = new Batman.SimpleSet(@zeke, @mary)
setSpy = spyOn(set, 'observe')
zekeSpy = spyOn(@zeke, 'observe')
marySpy = spyOn(@mary, 'observe')
simpleIndex = new Batman.SetIndex(set, 'name')
deepEqual simpleIndex.get('Zeke').toArray(), [@zeke]
ok !setSpy.called, "the set should not be observed"
ok !zekeSpy.called, "the items should not be observed"
ok !marySpy.called, "the items should not be observed"
test "get(value) returns a Batman.Set of items indexed on that value for the index's key", ->
allByFred = @authorNameIndex.get("PI:NAME:<NAME>END_PI")
equal allByFred.length, 2
ok allByFred.has(@byFred)
ok allByFred.has(@anotherByFred)
test "the result set from get(value) should be updated to remove items which are removed from the underlying set", ->
allByFred = @authorNameIndex.get("PI:NAME:<NAME>END_PI")
allByFred.observe 'itemsWereRemoved', observer = createSpy()
@base.remove(@anotherByFred)
equal observer.lastCallArguments.length, 1
ok observer.lastCallArguments[0] is @anotherByFred
equal allByFred.has(@anotherByFred), false
test "the result set from get(value) should be updated to add matching items when they are added to the underlying set", ->
allByZeke = @authorNameIndex.get("PI:NAME:<NAME>END_PI")
allByZeke.observe 'itemsWereAdded', observer = createSpy()
@base.add @anotherByZeke
equal observer.lastCallArguments.length, 1
ok observer.lastCallArguments[0] is @anotherByZeke
equal allByZeke.has(@anotherByZeke), true
test "the result set from get(value) should not be updated to add items which don't match the value", ->
allByFred = @authorNameIndex.get("PI:NAME:<NAME>END_PI")
allByFred.observe 'itemsWereAdded', observer = createSpy()
@base.add @anotherByZeke
equal observer.called, false
equal allByFred.has(@anotherByZeke), false
test "adding items with as-yet-unused index keys should add them to the appropriate result sets", ->
@base.add @byJill
allByJill = @authorNameIndex.get("PI:NAME:<NAME>END_PI")
equal allByJill.length, 1
ok allByJill.has(@byJill)
test "setting a new value of the indexed property on one of the items triggers an update", ->
allByFred = @authorNameIndex.get("PI:NAME:<NAME>END_PI")
allByMary = @authorNameIndex.get("PI:NAME:<NAME>END_PI")
@byFred.set('author', @mary)
equal allByFred.has(@byFred), false
equal allByMary.has(@byFred), true
test "setting a new value of the indexed property on an item which has been removed should not trigger an update", ->
allByMary = @authorNameIndex.get("PI:NAME:<NAME>END_PI")
@base.remove(@byFred)
@byFred.set('author', @mary)
equal allByMary.has(@byFred), false
test "items with undefined values for the indexed key are grouped together as with any other value, and don't collide with null values", ->
noAuthor = Batman()
anotherNoAuthor = Batman()
nullAuthor = Batman
author: PI:NAME:<NAME>END_PI
name: null
@base.add noAuthor
@base.add anotherNoAuthor
allByNobody = @authorNameIndex.get(undefined)
equal allByNobody.length, 2
equal allByNobody.has(noAuthor), true
equal allByNobody.has(anotherNoAuthor), true
equal allByNobody.has(Batman()), false
test "stopObserving() forgets all observers", ->
@authorNameIndex.stopObserving()
@base.add @byJill
equal @authorNameIndex.get("PI:NAME:<NAME>END_PI").length, 0
@base.remove @byZeke
equal @authorNameIndex.get("PI:NAME:<NAME>END_PI").length, 1
@byFred.set('author', @mary)
equal @authorNameIndex.get("Fred").has(@byFred), true
equal @authorNameIndex.get("PI:NAME:<NAME>END_PI").has(@byFred), false
|
[
{
"context": "\n# See https://github.com/OAButton/discussion/issues/1516\n\nimport crypto from 'crypt",
"end": 34,
"score": 0.9996805787086487,
"start": 26,
"tag": "USERNAME",
"value": "OAButton"
},
{
"context": " id: af.issn\n meta:\n creator: ['joe+doaj@openaccess... | noddy/service/v2/permissions.coffee | oaworks/API | 2 |
# See https://github.com/OAButton/discussion/issues/1516
import crypto from 'crypto'
import moment from 'moment'
API.add 'service/oab/permissions',
get: () ->
if this.queryParams?.q? or this.queryParams.source? or _.isEmpty this.queryParams
return oab_permissions.search this.queryParams
else
return API.service.oab.permission this.queryParams, this.queryParams.content, this.queryParams.url, this.queryParams.confirmed, this.queryParams.uid, this.queryParams.meta
post: () ->
if not this.request.files? and typeof this.request.body is 'object' and (this.request.body.q? or this.request.body.source?)
this.bodyParams[k] ?= this.queryParams[k] for k of this.queryParams
return oab_permissions.search this.bodyParams
else
return API.service.oab.permission this.queryParams, this.request.files ? this.request.body, undefined, this.queryParams.confirmed ? this.bodyParams?.confirmed, this.queryParams.uid, this.queryParams.meta
API.add 'service/oab/permissions/:issnorpub',
get: () ->
if typeof this.urlParams.issnorpub is 'string' and this.urlParams.issnorpub.indexOf('-') isnt -1 and this.urlParams.issnorpub.indexOf('10.') isnt 0 and this.urlParams.issnorpub.length < 10
this.queryParams.issn ?= this.urlParams.issnorpub
else if this.urlParams.issnorpub.indexOf('10.') isnt 0
this.queryParams.publisher ?= this.urlParams.issnorpub # but this could be a ror too... any way to tell?
return API.service.oab.permission this.queryParams
API.add 'service/oab/permissions/:doi/:doi2',
get: () ->
this.queryParams.doi ?= this.urlParams.doi + '/' + this.urlParams.doi2
return API.service.oab.permission this.queryParams
API.add 'service/oab/permissions/:doi/:doi2/:doi3',
get: () ->
this.queryParams.doi ?= this.urlParams.doi + '/' + this.urlParams.doi2 + '/' + this.urlParams.doi3
return API.service.oab.permission this.queryParams
API.add 'service/oab/permissions/journal',
get: () -> return oab_permissions.search this.queryParams, restrict: [exists: field: 'journal']
post: () -> return oab_permissions.search this.bodyParams, restrict: [exists: field: 'journal']
API.add 'service/oab/permissions/journal/:issnorid',
get: () ->
if this.urlParams.issnorid.indexOf('-') is -1 and j = oab_permissions.get this.urlParams.issnorid
return j
else if j = oab_permissions.find journal: this.urlParams.issnorid
return j
else if this.urlParams.issnorid.indexOf('-') isnt -1
return API.service.oab.permission {issn: this.urlParams.issnorid, doi: this.queryParams.doi}
API.add 'service/oab/permissions/publisher',
get: () -> return oab_permissions.search this.queryParams, restrict: [exists: field: 'publisher']
post: () -> return oab_permissions.search this.bodyParams, restrict: [exists: field: 'publisher']
API.add 'service/oab/permissions/publisher/:norid',
get: () ->
if p = oab_permissions.get this.urlParams.norid
return p
else if p = oab_permissions.find 'issuer.id': this.urlParams.norid
return p
else
return API.service.oab.permission {publisher: this.urlParams.norid, doi: this.queryParams.doi, issn: this.queryParams.issn}
API.add 'service/oab/permissions/affiliation',
get: () -> return oab_permissions.search this.queryParams, restrict: [exists: field: 'affiliation']
post: () -> return oab_permissions.search this.bodyParams, restrict: [exists: field: 'affiliation']
API.add 'service/oab/permissions/affiliation/:rororid', # could also be a two letter country code, which is in the same affiliation field as the ROR
get: () ->
if a = oab_permissions.get this.urlParams.rororid
return a
else if a = oab_permissions.find 'issuer.id': this.urlParams.rororid
return a
else
return API.service.oab.permission {affiliation: this.urlParams.rororid, publisher: this.queryParams.publisher, doi: this.queryParams.doi, issn: this.queryParams.issn}
API.add 'service/oab/permissions/import',
get:
roleRequired: if API.settings.dev then undefined else 'openaccessbutton.admin'
action: () ->
Meteor.setTimeout (() => API.service.oab.permission.import this.queryParams.reload, undefined, this.queryParams.stale), 1
return true
API.add 'service/oab/permissions/test', get: () -> return API.service.oab.permission.test this.queryParams.email
API.service.oab.permission = (meta={}, file, url, confirmed, roruid, getmeta) ->
overall_policy_restriction = false
cr = false
haddoi = false
_prep = (rec) ->
if haddoi and rec.embargo_months and (meta.published or meta.year)
em = moment meta.published ? meta.year + '-01-01'
em = em.add rec.embargo_months, 'months'
#if em.isAfter moment() # changed 09112020 by JM request to always add embargo_end if we can calculate it, even if it is in the past.
rec.embargo_end = em.format "YYYY-MM-DD"
delete rec.embargo_end if rec.embargo_end is ''
rec.copyright_name = if rec.copyright_owner is 'publisher' then (if typeof rec.issuer.parent_policy is 'string' then rec.issuer.parent_policy else if typeof rec.issuer.id is 'string' then rec.issuer.id else rec.issuer.id[0]) else if rec.copyright_owner in ['journal','affiliation'] then (meta.journal ? '') else if (rec.copyright_owner and rec.copyright_owner.toLowerCase().indexOf('author') isnt -1) and meta.author? and meta.author.length and (meta.author[0].name or meta.author[0].family) then (meta.author[0].name ? meta.author[0].family) + (if meta.author.length > 1 then ' et al' else '') else ''
if rec.copyright_name in ['publisher','journal'] and (cr or meta.doi or rec.provenance?.example)
if cr is false
cr = API.use.crossref.works.doi meta.doi ? rec.provenance.example
if cr?.assertion? and cr.assertion.length
for a in cr.assertion
if a.name.toLowerCase() is 'copyright'
try rec.copyright_name = a.value
try rec.copyright_name = a.value.replace('\u00a9 ','').replace(/[0-9]/g,'').trim()
rec.copyright_year = meta.year if haddoi and rec.copyright_year is '' and meta.year
delete rec.copyright_year if rec.copyright_year is ''
#for ds in ['copyright_name','copyright_year']
# delete rec[ds] if rec[ds] is ''
if haddoi and rec.deposit_statement? and rec.deposit_statement.indexOf('<<') isnt -1
fst = ''
for pt in rec.deposit_statement.split '<<'
if fst is '' and pt.indexOf('>>') is -1
fst += pt
else
eph = pt.split '>>'
ph = eph[0].toLowerCase()
swaps =
'journal title': 'journal'
'vol': 'volume'
'date of publication': 'published'
'(c)': 'year'
'article title': 'title'
'copyright name': 'copyright_name'
ph = swaps[ph] if swaps[ph]?
if ph is 'author'
try fst += (meta.author[0].name ? meta.author[0].family) + (if meta.author.length > 1 then ' et al' else '')
else
fst += meta[ph] ? rec[ph] ? ''
try fst += eph[1]
rec.deposit_statement = fst
if rec._id?
rec.meta ?= {}
rec.meta.source = 'https://' + (if API.settings.dev then 'dev.api.cottagelabs.com/service/oab/permissions/' else 'api.openaccessbutton.org/permissions/') + (if rec.issuer.type then rec.issuer.type + '/' else '') + rec._id
if typeof rec.issuer?.has_policy is 'string' and rec.issuer.has_policy.toLowerCase().trim() in ['not publisher','takedown']
# find out if this should be enacted if it is the case for any permission, or only the best permission
overall_policy_restriction = rec.issuer.has_policy
delete rec[d] for d in ['_id','permission_required','createdAt','updatedAt','created_date','updated_date']
try delete rec.issuer.updatedAt
return rec
_score = (rec) ->
score = if rec.can_archive then 1000 else 0
score += 1000 if rec.provenance?.oa_evidence is 'In DOAJ'
if rec.requirements?
# TODO what about cases where the requirement is met?
# and HOW is requirement met? we search ROR against issuer, but how does that match with author affiliation?
# should we even be searching for permissions by ROR, or only using it to calculate the ones we find by some other means?
# and if it is not met then is can_archive worth anything?
score -= 10
else
score += if rec.version is 'publishedVersion' then 200 else if rec.version is 'acceptedVersion' then 100 else 0
score -= 5 if rec.licences? and rec.licences.length
score += if rec.issuer?.type is 'journal' then 5 else if rec.issuer?.type is 'publisher' then 4 else if rec.issuer?.type is 'university' then 3 else if rec.issuer?.type in 'article' then 2 else 0
score -= 25 if rec.embargo_months and rec.embargo_months >= 36 and (not rec.embargo_end or moment(rec.embargo_end,"YYYY-MM-DD").isBefore(moment()))
return score
inp = {}
if typeof meta is 'string'
meta = if meta.indexOf('10.') is 0 then {doi: meta} else {issn: meta}
delete meta.meta if meta.meta? # just used to pass in a false to getmeta
if meta.metadata? # if passed a catalogue object
inp = meta
meta = meta.metadata
if meta.affiliation
meta.ror = meta.affiliation
delete meta.affiliation
if meta.journal and meta.journal.indexOf(' ') is -1
meta.issn = meta.journal
delete meta.journal
if meta.publisher and meta.publisher.indexOf(' ') is -1 and meta.publisher.indexOf(',') is -1 and not oab_permissions.find 'issuer.type.exact:"publisher" AND issuer.id:"' + meta.publisher + '"'
# it is possible this may actually be a ror, so switch to ror just in case - if it still matches nothing, no loss
meta.ror = meta.publisher
delete meta.publisher
issns = if _.isArray(meta.issn) then meta.issn else [] # only if directly passed a list of ISSNs for the same article, accept them as the ISSNs list to use
meta.issn = meta.issn.split(',') if typeof meta.issn is 'string' and meta.issn.indexOf(',') isnt -1
meta.ror = meta.ror.split(',') if typeof meta.ror is 'string' and meta.ror.indexOf(',') isnt -1
if not meta.ror
uc = if typeof roruid is 'object' then roruid else if typeof roruid is 'string' then API.service.oab.deposit.config(roruid) else undefined
if (typeof uc is 'object' and uc.ror?) or typeof roruid is 'string'
meta.ror = uc?.ror ? roruid
if _.isEmpty(meta) or (meta.issn and JSON.stringify(meta.issn).indexOf('-') is -1) or (meta.doi and (typeof meta.doi isnt 'string' or meta.doi.indexOf('10.') isnt 0 or meta.doi.indexOf('/') is -1))
return body: 'No valid DOI, ISSN, or ROR provided', statusCode: 404
# NOTE later will want to find affiliations related to the authors of the paper, but for now only act on affiliation provided as a ror
# we now always try to get the metadata because joe wants to serve a 501 if the doi is not a journal article
_getmeta = () ->
psm = JSON.parse JSON.stringify meta
delete psm.ror
if not _.isEmpty psm
rsm = API.service.oab.metadata {metadata: ['crossref_type','issn','publisher','published','year','author','ror']}, psm
for mk of rsm
meta[mk] ?= rsm[mk]
_getmeta() if getmeta isnt false and meta.doi and (not meta.publisher or not meta.issn)
meta.published = meta.year + '-01-01' if not meta.published and meta.year
haddoi = meta.doi?
af = false
if meta.issn
meta.issn = [meta.issn] if typeof meta.issn is 'string'
if not issns.length # they're already meta.issn in this case anyway
for inisn in meta.issn
issns.push(inisn) if inisn not in issns # check just in case
if not issns.length or not meta.publisher or not meta.doi
if af = academic_journal.find 'issn.exact:"' + issns.join('" OR issn.exact:"') + '"'
meta.publisher ?= af.publisher
for an in (if typeof af.issn is 'string' then [af.issn] else af.issn)
issns.push(an) if an not in issns # check again
meta.doi ?= af.doi
try
meta.doi ?= API.use.crossref.journals.doi issns
catch # temporary until wider crossref update completed
meta.doi ?= API.use.crossref.journals.dois.example issns
_getmeta() if not haddoi and meta.doi
if haddoi and meta.crossref_type not in ['journal-article']
return
body: 'DOI is not a journal article'
status: 501
if meta.publisher and meta.publisher.indexOf('(') isnt -1 and meta.publisher.lastIndexOf(')') > (meta.publisher.length*.7)
# could be a publisher name with the acronym at the end, like Public Library of Science (PLoS)
# so get rid of the acronym because that is not included in the publisher name in crossref and other sources
meta.publisher = meta.publisher.substring(0, meta.publisher.lastIndexOf('(')).trim()
try
meta.citation = '['
meta.citation += meta.title + '. ' if meta.title
meta.citation += meta.journal + ' ' if meta.journal
meta.citation += meta.volume + (if meta.issue then ', ' else ' ') if meta.volume
meta.citation += meta.issue + ' ' if meta.issue
meta.citation += 'p' + (meta.page ? meta.pages) if meta.page? or meta.pages?
if meta.year or meta.published
meta.citation += ' (' + (meta.year ? meta.published).split('-')[0] + ')'
meta.citation = meta.citation.trim()
meta.citation += ']'
perms = best_permission: undefined, all_permissions: [], file: undefined
rors = []
if meta.ror?
meta.ror = [meta.ror] if typeof meta.ror is 'string'
rs = oab_permissions.search 'issuer.id.exact:"' + meta.ror.join('" OR issuer.id.exact:"') + '"'
if not rs?.hits?.total
# look up the ROR in wikidata - if found, get the qid from the P17 country snak, look up that country qid
# get the P297 ISO 3166-1 alpha-2 code, search affiliations for that
if rwd = wikidata_record.find 'snaks.property.exact:"P6782" AND snaks.property.exact:"P17" AND (snaks.value.exact:"' + meta.ror.join(" OR snaks.value.exact:") + '")'
snkd = false
for snak in rwd.snaks
if snkd
break
else if snak.property is 'P17'
if cwd = wikidata_record.get snak.qid
for sn in cwd.snaks
if sn.property is 'P297'
snkd = true
rs = oab_permissions.search 'issuer.id.exact:"' + sn.value + '"'
break
for rr in rs?.hits?.hits ? []
tr = _prep rr._source
tr.score = _score tr
rors.push tr
if issns.length or meta.publisher
qr = if issns.length then 'issuer.id.exact:"' + issns.join('" OR issuer.id.exact:"') + '"' else ''
if meta.publisher
qr += ' OR ' if qr isnt ''
qr += 'issuer.id:"' + meta.publisher + '"' # how exact/fuzzy can this be
ps = oab_permissions.search qr
if ps?.hits?.hits? and ps.hits.hits.length
for p in ps.hits.hits
rp = _prep p._source
rp.score = _score rp
perms.all_permissions.push rp
if perms.all_permissions.length is 0 and meta.publisher and not meta.doi and not issns.length
af = academic_journal.find 'publisher:"' + meta.publisher + '"'
if not af?
fz = academic_journal.find 'publisher:"' + meta.publisher.split(' ').join(' AND publisher:"') + '"'
if fz.publisher is meta.publisher
af = fz
else
lvs = API.tdm.levenshtein fz.publisher, meta.publisher, true
longest = if lvs.length.a > lvs.length.b then lvs.length.a else lvs.length.b
af = fz if lvs.distance < 5 or longest/lvs.distance > 10
if typeof af is 'object' and af.is_oa
pisoa = academic_journal.count('publisher:"' + af.publisher + '"') is academic_journal.count('publisher:"' + af.publisher + '" AND is_oa:true')
af = false if not af.is_oa or not pisoa
if typeof af is 'object' and af.is_oa isnt false
af.is_oa = true if not af.is_oa? and ('doaj' in af.src or af.wikidata_in_doaj)
if af.is_oa
altoa =
can_archive: true
version: 'publishedVersion'
versions: ['publishedVersion']
licence: undefined
licence_terms: ""
licences: []
locations: ['institutional repository']
embargo_months: undefined
issuer:
type: 'journal'
has_policy: 'yes'
id: af.issn
meta:
creator: ['joe+doaj@openaccessbutton.org']
contributors: ['joe+doaj@openaccessbutton.org']
monitoring: 'Automatic'
try altoa.licence = af.license[0].type # could have doaj licence info
altoa.licence ?= af.licence # wikidata licence
if 'doaj' in af.src or af.wikidata_in_doaj
altoa.embargo_months = 0
altoa.provenance = {oa_evidence: 'In DOAJ'}
if typeof altoa.licence is 'string'
altoa.licence = altoa.licence.toLowerCase().trim()
if altoa.licence.indexOf('cc') is 0
altoa.licence = altoa.licence.replace(/ /g, '-')
else if altoa.licence.indexOf('creative') isnt -1
altoa.licence = if altoa.licence.indexOf('0') isnt -1 or altoa.licence.indexOf('zero') isnt -1 then 'cc0' else if altoa.licence.indexOf('share') isnt -1 then 'ccbysa' else if altoa.licence.indexOf('derivative') isnt -1 then 'ccbynd' else 'ccby'
else
delete altoa.licence
else
delete altoa.licence
if altoa.licence
altoa.licences = [{type: altoa.licence, terms: ""}]
altoa.score = _score altoa
perms.all_permissions.push altoa
if haddoi and meta.doi and oadoi = API.use.oadoi.doi meta.doi, false
# use oadoi for specific doi
if oadoi?.best_oa_location?.license and oadoi.best_oa_location.license.indexOf('cc') isnt -1
doa =
can_archive: true
version: oadoi.best_oa_location.version
versions: []
licence: oadoi.best_oa_location.license
licence_terms: ""
licences: []
locations: ['institutional repository']
issuer:
type: 'article'
has_policy: 'yes'
id: meta.doi
meta:
creator: ['support@unpaywall.org']
contributors: ['support@unpaywall.org']
monitoring: 'Automatic'
updated: oadoi.best_oa_location.updated
provenance:
oa_evidence: oadoi.best_oa_location.evidence
if typeof doa.licence is 'string'
doa.licences = [{type: doa.licence, terms: ""}]
if doa.version
doa.versions = if doa.version in ['submittedVersion','preprint'] then ['submittedVersion'] else if doa.version in ['acceptedVersion','postprint'] then ['submittedVersion', 'acceptedVersion'] else ['submittedVersion', 'acceptedVersion', 'publishedVersion']
doa.score = _score doa
perms.all_permissions.push doa
# sort rors by score, and sort alts by score, then combine
if perms.all_permissions.length
perms.all_permissions = _.sortBy(perms.all_permissions, 'score').reverse()
# note if enforcement_from is after published date, don't apply the permission. If no date, the permission applies to everything
for wp in perms.all_permissions
if not wp.provenance?.enforcement_from
perms.best_permission = JSON.parse JSON.stringify wp
break
else if not meta.published or moment(meta.published,'YYYY-MM-DD').isAfter(moment(wp.provenance.enforcement_from,'DD/MM/YYYY'))
perms.best_permission = JSON.parse JSON.stringify wp
break
if rors.length
rors = _.sortBy(rors, 'score').reverse()
for ro in rors
perms.all_permissions.push ro
if not perms.best_permission?.author_affiliation_requirement?
if perms.best_permission?
if not ro.provenance?.enforcement_from or not meta.published or moment(meta.published,'YYYY-MM-DD').isAfter(moment(ro.provenance.enforcement_from,'DD/MM/YYYY'))
pb = JSON.parse JSON.stringify perms.best_permission
for key in ['licences', 'versions', 'locations']
for vl in (ro[key] ? [])
pb[key] ?= []
pb[key].push(vl) if vl not in pb[key]
for l in pb.licences ? []
pb.licence = l.type if not pb.licence? or l.type.length < pb.licence.length
pb.version = if 'publishedVersion' in pb.versions or 'publisher pdf' in pb.versions then 'publishedVersion' else if 'acceptedVersion' in pb.versions or 'postprint' in pb.versions then 'acceptedVersion' else 'submittedVersion'
if pb.embargo_end
if ro.embargo_end
if moment(ro.embargo_end,"YYYY-MM-DD").isBefore(moment(pb.embargo_end,"YYYY-MM-DD"))
pb.embargo_end = ro.embargo_end
if pb.embargo_months and ro.embargo_months? and ro.embargo_months < pb.embargo_months
pb.embargo_months = ro.embargo_months
pb.can_archive = true if ro.can_archive is true
pb.requirements ?= {}
pb.requirements.author_affiliation_requirement = if not meta.ror? then ro.issuer.id else if typeof meta.ror is 'string' then meta.ror else meta.ror[0]
pb.issuer.affiliation = ro.issuer
pb.meta ?= {}
pb.meta.affiliation = ro.meta
pb.provenance ?= {}
pb.provenance.affiliation = ro.provenance
pb.score = parseInt(pb.score) + parseInt(ro.score)
perms.best_permission = pb
perms.all_permissions.push pb
if file? or url?
# TODO file usage on new permissions API is still to be re-written
# is it possible file will already have been processed, if so can this step be shortened or avoided?
perms.file = API.service.oab.permission.file file, url, confirmed, meta
try perms.lantern = API.service.lantern.licence('https://doi.org/' + meta.doi) if not perms.file?.licence and meta.doi? and 'doi.org' not in url
if perms.file.archivable? and perms.file.archivable isnt true and perms.lantern?.licence? and perms.lantern.licence.toLowerCase().indexOf('cc') is 0
perms.file.licence = perms.lantern.licence
perms.file.licence_evidence = {string_match: perms.lantern.match}
perms.file.archivable = true
perms.file.archivable_reason = 'We think that the splash page the DOI resolves to contains a ' + perms.lantern.licence + ' licence statement which confirms this article can be archived'
if perms.file.archivable and not perms.file.licence?
if perms.best_permission.licence
perms.file.licence = perms.best_permission.licence
else if perms.best_permission?.deposit_statement? and perms.best_permission.deposit_statement.toLowerCase().indexOf('cc') is 0
perms.file.licence = perms.best_permission.deposit_statement
perms.best_permission.licence ?= perms.file.licence if perms.file.licence
if perms.file.same_paper and not perms.file.archivable and perms.file.version?
if perms.best_permission?.version? and perms.file.version is perms.best_permission.version
perms.file.archivable = true
perms.file.archivable_reason = 'We believe this is a ' + perms.file.version + ' and our permission system says that version can be shared'
else
perms.file.archivable_reason ?= 'We believe this file is a ' + perms.file.version + ' version and our permission system does not list that as an archivable version'
if overall_policy_restriction
msgs =
'not publisher': 'Please find another DOI for this article as this is provided as this doesn’t allow us to find required information like who published it'
return
body: if typeof overall_policy_restriction isnt 'string' then overall_policy_restriction else msgs[overall_policy_restriction.toLowerCase()] ? overall_policy_restriction
status: 501
else
return perms
# https://docs.google.com/spreadsheets/d/1qBb0RV1XgO3xOQMdHJBAf3HCJlUgsXqDVauWAtxde4A/edit
API.service.oab.permission.import = (reload=false, src, stale=1000) ->
# unfortunately for now there appears to be no way to uniquely identify a record
# so if ANY show last updated in the last day, reload them all
reload = true
since = Date.now()-86400010 # 1 day and 10ms ago, just to give a little overlap
keys =
versionsarchivable: 'versions'
permissionsrequestcontactemail: 'permissions_contact'
archivinglocationsallowed: 'locations'
license: 'licence'
licencesallowed: 'licences'
'post-printembargo': 'embargo_months'
depositstatementrequired: 'deposit_statement'
copyrightowner: 'copyright_owner' # can be journal, publisher, affiliation or author
publicnotes: 'notes'
authoraffiliationrolerequirement: 'requirements.role'
authoraffiliationrequirement: 'requirements.affiliation'
authoraffiliationdepartmentrequirement: 'requirements.departmental_affiliation'
iffundedby: 'requirements.funder'
fundingproportionrequired: 'requirements.funding_proportion'
subjectcoverage: 'requirements.subject'
has_policy: 'issuer.has_policy'
permissiontype: 'issuer.type'
parentpolicy: 'issuer.parent_policy'
contributedby: 'meta.contributors'
recordlastupdated: 'meta.updated'
reviewers: 'meta.reviewer'
addedby: 'meta.creator'
monitoringtype: 'meta.monitoring'
policyfulltext: 'provenance.archiving_policy'
policylandingpage: 'provenance.archiving_policy_splash'
publishingagreement: 'provenance.sample_publishing_agreement'
publishingagreementsplash: 'provenance.sample_publishing_splash'
rights: 'provenance.author_rights'
embargolist: 'provenance.embargo_list'
policyfaq: 'provenance.faq'
miscsource: 'provenance.misc_source'
enforcementdate: 'provenance.enforcement_from'
example: 'provenance.example'
src ?= API.settings.service?.openaccessbutton?.permissions?.sheet
records = API.use.google.sheets.feed src, stale # get a new sheet if over an hour old
ready = []
for rec in records
nr =
can_archive: false
version: undefined
versions: undefined
licence: undefined
licence_terms: undefined
licences: undefined
locations: undefined
embargo_months: undefined
embargo_end: undefined
deposit_statement: undefined
permission_required: undefined
permissions_contact: undefined
copyright_owner: undefined
copyright_name: undefined
copyright_year: undefined
notes: undefined
requirements: undefined
issuer: {}
meta: {}
provenance: undefined
try
rec.recordlastupdated = rec.recordlastupdated.trim()
if rec.recordlastupdated.indexOf(',') isnt -1
nd = false
for dt in rec.recordlastupdated.split ','
nd = dt.trim() if nd is false or moment(dt.trim(),'DD/MM/YYYY').isAfter(moment(nd,'DD/MM/YYYY'))
rec.recordlastupdated = nd if nd isnt false
nr.meta.updated = rec.recordlastupdated
nr.meta.updatedAt = moment(nr.meta.updated, 'DD/MM/YYYY').valueOf() if nr.meta.updated?
if reload or not nr.meta.updatedAt? or nr.meta.updatedAt > since
# the google feed import will lowercase these key names and remove whitespace, question marks, brackets too, but not dashes
nr.issuer.id = if rec.id.indexOf(',') isnt -1 then rec.id.split(',') else rec.id
if typeof nr.issuer.id isnt 'string'
cids = []
inaj = false
for nid in nr.issuer.id
nid = nid.trim()
if nr.issuer.type is 'journal' and nid.indexOf('-') isnt -1 and nid.indexOf(' ') is -1
nid = nid.toUpperCase()
if af = academic_journal.find 'issn.exact:"' + nid + '"'
inaj = true
for an in af.issn
cids.push(an) if an not in cids
cids.push(nid) if nid not in cids
nr.issuer.id = cids
nr.permission_required = rec.has_policy? and rec.has_policy.toLowerCase().indexOf('permission required') isnt -1
for k of rec
if keys[k] and rec[k]? and rec[k].length isnt 0
nk = keys[k]
nv = undefined
if k is 'post-printembargo' # Post-Print Embargo - empty or number of months like 0, 12, 24
try
kn = parseInt rec[k].trim()
nv = kn if typeof kn is 'number' and not isNaN kn and kn isnt 0
nr.embargo_end = '' if nv? # just to allow neat output later - can't be calculated until compared to a particular article
else if k in ['journal', 'versionsarchivable', 'archivinglocationsallowed', 'licencesallowed', 'policyfulltext', 'contributedby', 'addedby', 'reviewers', 'iffundedby']
nv = []
for s in rcs = rec[k].trim().split ','
st = s.trim()
if k is 'licencesallowed'
if st.toLowerCase() isnt 'unclear'
lc = type: st.toLowerCase()
try lc.terms = rec.licenceterms.split(',')[rcs.indexOf(s)].trim() # these don't seem to exist any more...
nv.push lc
else
if k is 'versionsarchivable'
st = st.toLowerCase()
st = 'submittedVersion' if st is 'preprint'
st = 'acceptedVersion' if st is 'postprint'
st = 'publishedVersion' if st is 'publisher pdf'
nv.push(if k in ['archivinglocationsallowed'] then st.toLowerCase() else st) if st.length and st not in nv
else if k not in ['recordlastupdated']
nv = rec[k].trim()
nv = nv.toLowerCase() if typeof nv is 'string' and (nv.toLowerCase() in ['yes','no'] or k in ['haspolicy','permissiontype','copyrightowner'])
nv = '' if k in ['copyrightowner','license'] and nv is 'unclear'
if nv?
if nk.indexOf('.') isnt -1
nps = nk.split '.'
nr[nps[0]] ?= {}
nr[nps[0]][[nps[1]]] = nv
else
nr[nk] = nv
# Archived Full Text Link - a URL to a web archive link of the full text policy link (ever multiple?)
# Record First Added - date like 12/07/2017
# Post-publication Pre-print Update Allowed - string like No, Yes, could be empty (turn these to booleans?)
# Can Authors Opt Out - seems to be all empty, could presumably be Yes or No
nr.licences ?= []
if not nr.licence
for l in nr.licences
if not nr.licence? or l.type.length < nr.licence.length
nr.licence = l.type
nr.licence_terms = l.terms
nr.versions ?= []
if nr.versions.length
nr.can_archive = true
nr.version = if 'acceptedVersion' in nr.versions or 'postprint' in nr.versions then 'acceptedVersion' else if 'publishedVersion' in nr.versions or 'publisher pdf' in nr.versions then 'publishedVersion' else 'submittedVersion'
nr.copyright_owner ?= nr.issuer?.type ? ''
nr.copyright_name ?= ''
nr.copyright_year ?= '' # the year of publication, to be added at result stage
ready.push(nr) if not _.isEmpty nr
# TODO if there is a provenance.example DOI look up the metadata for it and find the journal ISSN.
# then have a search for ISSN be able to find that. Otherwise, we have coverage by publisher that
# contains no journal info, so no way to go from ISSN to the stored record
if ready.length
if reload
# ideally want a unique ID per record so would only have to update the changed ones
# but as that is not yet possible, have to just dump and reload all
oab_permissions.remove '*'
oab_permissions.insert ready
API.mail.send
service: 'openaccessbutton'
from: 'natalia.norori@openaccessbutton.org'
to: ['mark@cottagelabs.com','joe@openaccessbutton.org']
subject: 'OAB permissions import check complete' + if API.settings.dev then ' (dev)' else ''
text: 'Found ' + records.length + ' in sheet, imported ' + ready.length + ' records'
return ready.length
# run import every day on the main machine
_oab_permissions_import = () ->
if API.settings.cluster?.ip? and API.status.ip() not in API.settings.cluster.ip
API.log 'Setting up an OAB permissions import to run every day if not triggered by request on ' + API.status.ip()
Meteor.setInterval (() -> API.service.oab.permission.import()), 86400000
Meteor.setTimeout _oab_permissions_import, 24000
API.service.oab.permission.file = (file, url, confirmed, meta={}) ->
f = {archivable: undefined, archivable_reason: undefined, version: 'unknown', same_paper: undefined, licence: undefined}
# handle different sorts of file passing
if typeof file is 'string'
file = data: file
if _.isArray file
file = if file.length then file[0] else undefined
if not file? and url?
file = API.http.getFile url
if file?
file.name ?= file.filename
try f.name = file.name
try f.format = if file.name? and file.name.indexOf('.') isnt -1 then file.name.substr(file.name.lastIndexOf('.')+1) else 'html'
if file.data
if f.format is 'pdf'
try content = API.convert.pdf2txt file.data
if not content? and f.format? and API.convert[f.format+'2txt']?
try content = API.convert[f.format+'2txt'] file.data
if not content?
content = API.convert.file2txt file.data, {name: file.name}
if not content?
fd = file.data
if typeof file.data isnt 'string'
try fd = file.data.toString()
try
if fd.indexOf('<html') is 0
content = API.convert.html2txt fd
else if file.data.indexOf('<xml') is 0
content = API.convert.xml2txt fd
try content ?= file.data
try content = content.toString()
if not content? and not confirmed
if file? or url?
f.error = file.error ? 'Could not extract any content'
else
_clean = (str) -> return str.toLowerCase().replace(/[^a-z0-9\/\.]+/g, "").replace(/\s\s+/g, ' ').trim()
contentsmall = if content.length < 20000 then content else content.substring(0,6000) + content.substring(content.length-6000,content.length)
lowercontentsmall = contentsmall.toLowerCase()
lowercontentstart = _clean(if lowercontentsmall.length < 6000 then lowercontentsmall else lowercontentsmall.substring(0,6000))
f.name ?= meta.title
try f.checksum = crypto.createHash('md5').update(content, 'utf8').digest('base64')
f.same_paper_evidence = {} # check if the file meets our expectations
try f.same_paper_evidence.words_count = content.split(' ').length # will need to be at least 500 words
try f.same_paper_evidence.words_more_than_threshold = if f.same_paper_evidence.words_count > 500 then true else false
try f.same_paper_evidence.doi_match = if meta.doi and lowercontentstart.indexOf(_clean meta.doi) isnt -1 then true else false # should have the doi in it near the front
#if content and not f.same_paper_evidence.doi_match and not meta.title?
# meta = API.service.oab.metadata undefined, meta, content # get at least title again if not already tried to get it, and could not find doi in the file
try f.same_paper_evidence.title_match = if meta.title and lowercontentstart.replace(/\./g,'').indexOf(_clean meta.title.replace(/ /g,'').replace(/\./g,'')) isnt -1 then true else false
if meta.author?
try
authorsfound = 0
f.same_paper_evidence.author_match = false
# get the surnames out if possible, or author name strings, and find at least one in the doc if there are three or less, or find at least two otherwise
meta.author = {name: meta.author} if typeof meta.author is 'string'
meta.author = [meta.author] if not _.isArray meta.author
for a in meta.author
if f.same_paper_evidence.author_match is true
break
else
try
an = (a.last ? a.lastname ? a.family ? a.surname ? a.name).trim().split(',')[0].split(' ')[0]
af = (a.first ? a.firstname ? a.given ? a.name).trim().split(',')[0].split(' ')[0]
inc = lowercontentstart.indexOf _clean an
if an.length > 2 and af.length > 0 and inc isnt -1 and lowercontentstart.substring(inc-20,inc+an.length+20).indexOf(_clean af) isnt -1
authorsfound += 1
if (meta.author.length < 3 and authorsfound is 1) or (meta.author.length > 2 and authorsfound > 1)
f.same_paper_evidence.author_match = true
break
if f.format?
for ft in ['doc','tex','pdf','htm','xml','txt','rtf','odf','odt','page']
if f.format.indexOf(ft) isnt -1
f.same_paper_evidence.document_format = true
break
f.same_paper = if f.same_paper_evidence.words_more_than_threshold and (f.same_paper_evidence.doi_match or f.same_paper_evidence.title_match or f.same_paper_evidence.author_match) and f.same_paper_evidence.document_format then true else false
if f.same_paper_evidence.words_count < 150 and f.format is 'pdf'
# there was likely a pdf file reading failure due to bad PDF formatting
f.same_paper_evidence.words_count = 0
f.archivable_reason = 'We could not find any text in the provided PDF. It is possible the PDF is a scan in which case text is only contained within images which we do not yet extract. Or, the PDF may have errors in it\'s structure which stops us being able to machine-read it'
f.version_evidence = score: 0, strings_checked: 0, strings_matched: []
try
# dev https://docs.google.com/spreadsheets/d/1XA29lqVPCJ2FQ6siLywahxBTLFaDCZKaN5qUeoTuApg/edit#gid=0
# live https://docs.google.com/spreadsheets/d/10DNDmOG19shNnuw6cwtCpK-sBnexRCCtD4WnxJx_DPQ/edit#gid=0
for l in API.use.google.sheets.feed (if API.settings.dev then '1XA29lqVPCJ2FQ6siLywahxBTLFaDCZKaN5qUeoTuApg' else '10DNDmOG19shNnuw6cwtCpK-sBnexRCCtD4WnxJx_DPQ')
try
f.version_evidence.strings_checked += 1
wts = l.whattosearch
if wts.indexOf('<<') isnt -1 and wts.indexOf('>>') isnt -1
wtm = wts.split('<<')[1].split('>>')[0]
wts = wts.replace('<<'+wtm+'>>',meta[wtm.toLowerCase()]) if meta[wtm.toLowerCase()]?
matched = false
if l.howtosearch is 'string'
#wtsc = _clean wts
#matched = if (l.wheretosearch is 'file' and _clean(lowercontentsmall).indexOf(wtsc) isnt -1) or (l.wheretosearch isnt 'file' and ((meta.title? and _clean(meta.title).indexOf(wtsc) isnt -1) or (f.name? and _clean(f.name).indexOf(wtsc) isnt -1))) then true else false
matched = if (l.wheretosearch is 'file' and contentsmall.indexOf(wts) isnt -1) or (l.wheretosearch isnt 'file' and ((meta.title? and meta.title.indexOf(wts) isnt -1) or (f.name? and f.name.indexOf(wts) isnt -1))) then true else false
else
# could change this to be explicit and not use lowercasing, if wanting more exactness
re = new RegExp wts, 'gium'
matched = if (l.wheretosearch is 'file' and lowercontentsmall.match(re) isnt null) or (l.wheretosearch isnt 'file' and ((meta.title? and meta.title.match(re) isnt null) or (f.name? and f.name.match(re) isnt null))) then true else false
if matched
sc = l.score ? l.score_value
if typeof sc is 'string'
try sc = parseInt sc
sc = 1 if typeof sc isnt 'number'
if l.whatitindicates is 'publisher pdf' then f.version_evidence.score += sc else f.version_evidence.score -= sc
f.version_evidence.strings_matched.push {indicates: l.whatitindicates, found: l.howtosearch + ' ' + wts, in: l.wheretosearch, score_value: sc}
f.version = 'publishedVersion' if f.version_evidence.score > 0
f.version = 'acceptedVersion' if f.version_evidence.score < 0
if f.version is 'unknown' and f.version_evidence.strings_checked > 0 #and f.format? and f.format isnt 'pdf'
f.version = 'acceptedVersion'
try
ls = API.service.lantern.licence undefined, undefined, lowercontentsmall # check lantern for licence info in the file content
if ls?.licence?
f.licence = ls.licence
f.licence_evidence = {string_match: ls.match}
f.lantern = ls
f.archivable = false
if confirmed
f.archivable = true
if confirmed is f.checksum
f.archivable_reason = 'The administrator has confirmed that this file is a version that can be archived.'
f.admin_confirms = true
else
f.archivable_reason = 'The depositor says that this file is a version that can be archived'
f.depositor_says = true
else if f.same_paper
if f.format isnt 'pdf'
f.archivable = true
f.archivable_reason = 'Since the file is not a PDF, we assume it is a Postprint.'
if not f.archivable and f.licence? and f.licence.toLowerCase().indexOf('cc') is 0
f.archivable = true
f.archivable_reason = 'It appears this file contains a ' + f.lantern.licence + ' licence statement. Under this licence the article can be archived'
if not f.archivable
if f.version is 'publishedVersion'
f.archivable_reason = 'The file given is a Publisher PDF, and only postprints are allowed'
else
f.archivable_reason = 'We cannot confirm if it is an archivable version or not'
else
f.archivable_reason ?= if not f.same_paper_evidence.words_more_than_threshold then 'The file is less than 500 words, and so does not appear to be a full article' else if not f.same_paper_evidence.document_format then 'File is an unexpected format ' + f.format else if not meta.doi and not meta.title then 'We have insufficient metadata to validate file is for the correct paper ' else 'File does not contain expected metadata such as DOI or title'
return f
API.service.oab.permission.test = (email) ->
res = {tests: 0, same: 0, results: {}}
for test in ts = API.use.google.sheets.feed '1vuzkrvbd2U3stLBGXMIHE_mtZ5J3YUhyRZEf08mNtM8', 0
break if res.tests > 2
if test.doi and test.doi.startsWith('10.') and test.responseurl
console.log res.tests
res.tests += 1
res.results[test.doi] = {}
try
perms = API.service.oab.permission(doi: test.doi.split('?')[0], ror: (if test.doi.indexOf('?') isnt -1 then test.doi.split('?')[1].split('=')[1] else undefined)).best_permission
catch
perms = {}
try
ricks = HTTP.call('GET', test.responseurl).data.authoritative_permission.application
catch
ricks = {}
if perms? and ricks?
diffs = {}
for k in ['can_archive']
if not perms[k]? or not ricks[k]? or perms[k] isnt ricks[k]
diffs[k] = [perms[k],ricks[k]]
if _.isEmpty diffs
res.same += 1
res.results[test.doi].same = true
else
res.results[test.doi].same = false
res.results[test.doi].diffs = diffs
res.results[test.doi].perms = perms
res.results[test.doi].ricks = ricks
API.mail.send
service: 'openaccessbutton'
from: 'natalia.norori@openaccessbutton.org'
to: email ? 'alert@cottagelabs.com'
subject: 'OAB permissions test complete'
text: JSON.stringify res, '', 2
return res | 222735 |
# See https://github.com/OAButton/discussion/issues/1516
import crypto from 'crypto'
import moment from 'moment'
API.add 'service/oab/permissions',
get: () ->
if this.queryParams?.q? or this.queryParams.source? or _.isEmpty this.queryParams
return oab_permissions.search this.queryParams
else
return API.service.oab.permission this.queryParams, this.queryParams.content, this.queryParams.url, this.queryParams.confirmed, this.queryParams.uid, this.queryParams.meta
post: () ->
if not this.request.files? and typeof this.request.body is 'object' and (this.request.body.q? or this.request.body.source?)
this.bodyParams[k] ?= this.queryParams[k] for k of this.queryParams
return oab_permissions.search this.bodyParams
else
return API.service.oab.permission this.queryParams, this.request.files ? this.request.body, undefined, this.queryParams.confirmed ? this.bodyParams?.confirmed, this.queryParams.uid, this.queryParams.meta
API.add 'service/oab/permissions/:issnorpub',
get: () ->
if typeof this.urlParams.issnorpub is 'string' and this.urlParams.issnorpub.indexOf('-') isnt -1 and this.urlParams.issnorpub.indexOf('10.') isnt 0 and this.urlParams.issnorpub.length < 10
this.queryParams.issn ?= this.urlParams.issnorpub
else if this.urlParams.issnorpub.indexOf('10.') isnt 0
this.queryParams.publisher ?= this.urlParams.issnorpub # but this could be a ror too... any way to tell?
return API.service.oab.permission this.queryParams
API.add 'service/oab/permissions/:doi/:doi2',
get: () ->
this.queryParams.doi ?= this.urlParams.doi + '/' + this.urlParams.doi2
return API.service.oab.permission this.queryParams
API.add 'service/oab/permissions/:doi/:doi2/:doi3',
get: () ->
this.queryParams.doi ?= this.urlParams.doi + '/' + this.urlParams.doi2 + '/' + this.urlParams.doi3
return API.service.oab.permission this.queryParams
API.add 'service/oab/permissions/journal',
get: () -> return oab_permissions.search this.queryParams, restrict: [exists: field: 'journal']
post: () -> return oab_permissions.search this.bodyParams, restrict: [exists: field: 'journal']
API.add 'service/oab/permissions/journal/:issnorid',
get: () ->
if this.urlParams.issnorid.indexOf('-') is -1 and j = oab_permissions.get this.urlParams.issnorid
return j
else if j = oab_permissions.find journal: this.urlParams.issnorid
return j
else if this.urlParams.issnorid.indexOf('-') isnt -1
return API.service.oab.permission {issn: this.urlParams.issnorid, doi: this.queryParams.doi}
API.add 'service/oab/permissions/publisher',
get: () -> return oab_permissions.search this.queryParams, restrict: [exists: field: 'publisher']
post: () -> return oab_permissions.search this.bodyParams, restrict: [exists: field: 'publisher']
API.add 'service/oab/permissions/publisher/:norid',
get: () ->
if p = oab_permissions.get this.urlParams.norid
return p
else if p = oab_permissions.find 'issuer.id': this.urlParams.norid
return p
else
return API.service.oab.permission {publisher: this.urlParams.norid, doi: this.queryParams.doi, issn: this.queryParams.issn}
API.add 'service/oab/permissions/affiliation',
get: () -> return oab_permissions.search this.queryParams, restrict: [exists: field: 'affiliation']
post: () -> return oab_permissions.search this.bodyParams, restrict: [exists: field: 'affiliation']
API.add 'service/oab/permissions/affiliation/:rororid', # could also be a two letter country code, which is in the same affiliation field as the ROR
get: () ->
if a = oab_permissions.get this.urlParams.rororid
return a
else if a = oab_permissions.find 'issuer.id': this.urlParams.rororid
return a
else
return API.service.oab.permission {affiliation: this.urlParams.rororid, publisher: this.queryParams.publisher, doi: this.queryParams.doi, issn: this.queryParams.issn}
API.add 'service/oab/permissions/import',
get:
roleRequired: if API.settings.dev then undefined else 'openaccessbutton.admin'
action: () ->
Meteor.setTimeout (() => API.service.oab.permission.import this.queryParams.reload, undefined, this.queryParams.stale), 1
return true
API.add 'service/oab/permissions/test', get: () -> return API.service.oab.permission.test this.queryParams.email
API.service.oab.permission = (meta={}, file, url, confirmed, roruid, getmeta) ->
overall_policy_restriction = false
cr = false
haddoi = false
_prep = (rec) ->
if haddoi and rec.embargo_months and (meta.published or meta.year)
em = moment meta.published ? meta.year + '-01-01'
em = em.add rec.embargo_months, 'months'
#if em.isAfter moment() # changed 09112020 by JM request to always add embargo_end if we can calculate it, even if it is in the past.
rec.embargo_end = em.format "YYYY-MM-DD"
delete rec.embargo_end if rec.embargo_end is ''
rec.copyright_name = if rec.copyright_owner is 'publisher' then (if typeof rec.issuer.parent_policy is 'string' then rec.issuer.parent_policy else if typeof rec.issuer.id is 'string' then rec.issuer.id else rec.issuer.id[0]) else if rec.copyright_owner in ['journal','affiliation'] then (meta.journal ? '') else if (rec.copyright_owner and rec.copyright_owner.toLowerCase().indexOf('author') isnt -1) and meta.author? and meta.author.length and (meta.author[0].name or meta.author[0].family) then (meta.author[0].name ? meta.author[0].family) + (if meta.author.length > 1 then ' et al' else '') else ''
if rec.copyright_name in ['publisher','journal'] and (cr or meta.doi or rec.provenance?.example)
if cr is false
cr = API.use.crossref.works.doi meta.doi ? rec.provenance.example
if cr?.assertion? and cr.assertion.length
for a in cr.assertion
if a.name.toLowerCase() is 'copyright'
try rec.copyright_name = a.value
try rec.copyright_name = a.value.replace('\u00a9 ','').replace(/[0-9]/g,'').trim()
rec.copyright_year = meta.year if haddoi and rec.copyright_year is '' and meta.year
delete rec.copyright_year if rec.copyright_year is ''
#for ds in ['copyright_name','copyright_year']
# delete rec[ds] if rec[ds] is ''
if haddoi and rec.deposit_statement? and rec.deposit_statement.indexOf('<<') isnt -1
fst = ''
for pt in rec.deposit_statement.split '<<'
if fst is '' and pt.indexOf('>>') is -1
fst += pt
else
eph = pt.split '>>'
ph = eph[0].toLowerCase()
swaps =
'journal title': 'journal'
'vol': 'volume'
'date of publication': 'published'
'(c)': 'year'
'article title': 'title'
'copyright name': 'copyright_name'
ph = swaps[ph] if swaps[ph]?
if ph is 'author'
try fst += (meta.author[0].name ? meta.author[0].family) + (if meta.author.length > 1 then ' et al' else '')
else
fst += meta[ph] ? rec[ph] ? ''
try fst += eph[1]
rec.deposit_statement = fst
if rec._id?
rec.meta ?= {}
rec.meta.source = 'https://' + (if API.settings.dev then 'dev.api.cottagelabs.com/service/oab/permissions/' else 'api.openaccessbutton.org/permissions/') + (if rec.issuer.type then rec.issuer.type + '/' else '') + rec._id
if typeof rec.issuer?.has_policy is 'string' and rec.issuer.has_policy.toLowerCase().trim() in ['not publisher','takedown']
# find out if this should be enacted if it is the case for any permission, or only the best permission
overall_policy_restriction = rec.issuer.has_policy
delete rec[d] for d in ['_id','permission_required','createdAt','updatedAt','created_date','updated_date']
try delete rec.issuer.updatedAt
return rec
_score = (rec) ->
score = if rec.can_archive then 1000 else 0
score += 1000 if rec.provenance?.oa_evidence is 'In DOAJ'
if rec.requirements?
# TODO what about cases where the requirement is met?
# and HOW is requirement met? we search ROR against issuer, but how does that match with author affiliation?
# should we even be searching for permissions by ROR, or only using it to calculate the ones we find by some other means?
# and if it is not met then is can_archive worth anything?
score -= 10
else
score += if rec.version is 'publishedVersion' then 200 else if rec.version is 'acceptedVersion' then 100 else 0
score -= 5 if rec.licences? and rec.licences.length
score += if rec.issuer?.type is 'journal' then 5 else if rec.issuer?.type is 'publisher' then 4 else if rec.issuer?.type is 'university' then 3 else if rec.issuer?.type in 'article' then 2 else 0
score -= 25 if rec.embargo_months and rec.embargo_months >= 36 and (not rec.embargo_end or moment(rec.embargo_end,"YYYY-MM-DD").isBefore(moment()))
return score
inp = {}
if typeof meta is 'string'
meta = if meta.indexOf('10.') is 0 then {doi: meta} else {issn: meta}
delete meta.meta if meta.meta? # just used to pass in a false to getmeta
if meta.metadata? # if passed a catalogue object
inp = meta
meta = meta.metadata
if meta.affiliation
meta.ror = meta.affiliation
delete meta.affiliation
if meta.journal and meta.journal.indexOf(' ') is -1
meta.issn = meta.journal
delete meta.journal
if meta.publisher and meta.publisher.indexOf(' ') is -1 and meta.publisher.indexOf(',') is -1 and not oab_permissions.find 'issuer.type.exact:"publisher" AND issuer.id:"' + meta.publisher + '"'
# it is possible this may actually be a ror, so switch to ror just in case - if it still matches nothing, no loss
meta.ror = meta.publisher
delete meta.publisher
issns = if _.isArray(meta.issn) then meta.issn else [] # only if directly passed a list of ISSNs for the same article, accept them as the ISSNs list to use
meta.issn = meta.issn.split(',') if typeof meta.issn is 'string' and meta.issn.indexOf(',') isnt -1
meta.ror = meta.ror.split(',') if typeof meta.ror is 'string' and meta.ror.indexOf(',') isnt -1
if not meta.ror
uc = if typeof roruid is 'object' then roruid else if typeof roruid is 'string' then API.service.oab.deposit.config(roruid) else undefined
if (typeof uc is 'object' and uc.ror?) or typeof roruid is 'string'
meta.ror = uc?.ror ? roruid
if _.isEmpty(meta) or (meta.issn and JSON.stringify(meta.issn).indexOf('-') is -1) or (meta.doi and (typeof meta.doi isnt 'string' or meta.doi.indexOf('10.') isnt 0 or meta.doi.indexOf('/') is -1))
return body: 'No valid DOI, ISSN, or ROR provided', statusCode: 404
# NOTE later will want to find affiliations related to the authors of the paper, but for now only act on affiliation provided as a ror
# we now always try to get the metadata because joe wants to serve a 501 if the doi is not a journal article
_getmeta = () ->
psm = JSON.parse JSON.stringify meta
delete psm.ror
if not _.isEmpty psm
rsm = API.service.oab.metadata {metadata: ['crossref_type','issn','publisher','published','year','author','ror']}, psm
for mk of rsm
meta[mk] ?= rsm[mk]
_getmeta() if getmeta isnt false and meta.doi and (not meta.publisher or not meta.issn)
meta.published = meta.year + '-01-01' if not meta.published and meta.year
haddoi = meta.doi?
af = false
if meta.issn
meta.issn = [meta.issn] if typeof meta.issn is 'string'
if not issns.length # they're already meta.issn in this case anyway
for inisn in meta.issn
issns.push(inisn) if inisn not in issns # check just in case
if not issns.length or not meta.publisher or not meta.doi
if af = academic_journal.find 'issn.exact:"' + issns.join('" OR issn.exact:"') + '"'
meta.publisher ?= af.publisher
for an in (if typeof af.issn is 'string' then [af.issn] else af.issn)
issns.push(an) if an not in issns # check again
meta.doi ?= af.doi
try
meta.doi ?= API.use.crossref.journals.doi issns
catch # temporary until wider crossref update completed
meta.doi ?= API.use.crossref.journals.dois.example issns
_getmeta() if not haddoi and meta.doi
if haddoi and meta.crossref_type not in ['journal-article']
return
body: 'DOI is not a journal article'
status: 501
if meta.publisher and meta.publisher.indexOf('(') isnt -1 and meta.publisher.lastIndexOf(')') > (meta.publisher.length*.7)
# could be a publisher name with the acronym at the end, like Public Library of Science (PLoS)
# so get rid of the acronym because that is not included in the publisher name in crossref and other sources
meta.publisher = meta.publisher.substring(0, meta.publisher.lastIndexOf('(')).trim()
try
meta.citation = '['
meta.citation += meta.title + '. ' if meta.title
meta.citation += meta.journal + ' ' if meta.journal
meta.citation += meta.volume + (if meta.issue then ', ' else ' ') if meta.volume
meta.citation += meta.issue + ' ' if meta.issue
meta.citation += 'p' + (meta.page ? meta.pages) if meta.page? or meta.pages?
if meta.year or meta.published
meta.citation += ' (' + (meta.year ? meta.published).split('-')[0] + ')'
meta.citation = meta.citation.trim()
meta.citation += ']'
perms = best_permission: undefined, all_permissions: [], file: undefined
rors = []
if meta.ror?
meta.ror = [meta.ror] if typeof meta.ror is 'string'
rs = oab_permissions.search 'issuer.id.exact:"' + meta.ror.join('" OR issuer.id.exact:"') + '"'
if not rs?.hits?.total
# look up the ROR in wikidata - if found, get the qid from the P17 country snak, look up that country qid
# get the P297 ISO 3166-1 alpha-2 code, search affiliations for that
if rwd = wikidata_record.find 'snaks.property.exact:"P6782" AND snaks.property.exact:"P17" AND (snaks.value.exact:"' + meta.ror.join(" OR snaks.value.exact:") + '")'
snkd = false
for snak in rwd.snaks
if snkd
break
else if snak.property is 'P17'
if cwd = wikidata_record.get snak.qid
for sn in cwd.snaks
if sn.property is 'P297'
snkd = true
rs = oab_permissions.search 'issuer.id.exact:"' + sn.value + '"'
break
for rr in rs?.hits?.hits ? []
tr = _prep rr._source
tr.score = _score tr
rors.push tr
if issns.length or meta.publisher
qr = if issns.length then 'issuer.id.exact:"' + issns.join('" OR issuer.id.exact:"') + '"' else ''
if meta.publisher
qr += ' OR ' if qr isnt ''
qr += 'issuer.id:"' + meta.publisher + '"' # how exact/fuzzy can this be
ps = oab_permissions.search qr
if ps?.hits?.hits? and ps.hits.hits.length
for p in ps.hits.hits
rp = _prep p._source
rp.score = _score rp
perms.all_permissions.push rp
if perms.all_permissions.length is 0 and meta.publisher and not meta.doi and not issns.length
af = academic_journal.find 'publisher:"' + meta.publisher + '"'
if not af?
fz = academic_journal.find 'publisher:"' + meta.publisher.split(' ').join(' AND publisher:"') + '"'
if fz.publisher is meta.publisher
af = fz
else
lvs = API.tdm.levenshtein fz.publisher, meta.publisher, true
longest = if lvs.length.a > lvs.length.b then lvs.length.a else lvs.length.b
af = fz if lvs.distance < 5 or longest/lvs.distance > 10
if typeof af is 'object' and af.is_oa
pisoa = academic_journal.count('publisher:"' + af.publisher + '"') is academic_journal.count('publisher:"' + af.publisher + '" AND is_oa:true')
af = false if not af.is_oa or not pisoa
if typeof af is 'object' and af.is_oa isnt false
af.is_oa = true if not af.is_oa? and ('doaj' in af.src or af.wikidata_in_doaj)
if af.is_oa
altoa =
can_archive: true
version: 'publishedVersion'
versions: ['publishedVersion']
licence: undefined
licence_terms: ""
licences: []
locations: ['institutional repository']
embargo_months: undefined
issuer:
type: 'journal'
has_policy: 'yes'
id: af.issn
meta:
creator: ['<EMAIL>']
contributors: ['<EMAIL>']
monitoring: 'Automatic'
try altoa.licence = af.license[0].type # could have doaj licence info
altoa.licence ?= af.licence # wikidata licence
if 'doaj' in af.src or af.wikidata_in_doaj
altoa.embargo_months = 0
altoa.provenance = {oa_evidence: 'In DOAJ'}
if typeof altoa.licence is 'string'
altoa.licence = altoa.licence.toLowerCase().trim()
if altoa.licence.indexOf('cc') is 0
altoa.licence = altoa.licence.replace(/ /g, '-')
else if altoa.licence.indexOf('creative') isnt -1
altoa.licence = if altoa.licence.indexOf('0') isnt -1 or altoa.licence.indexOf('zero') isnt -1 then 'cc0' else if altoa.licence.indexOf('share') isnt -1 then 'ccbysa' else if altoa.licence.indexOf('derivative') isnt -1 then 'ccbynd' else 'ccby'
else
delete altoa.licence
else
delete altoa.licence
if altoa.licence
altoa.licences = [{type: altoa.licence, terms: ""}]
altoa.score = _score altoa
perms.all_permissions.push altoa
if haddoi and meta.doi and oadoi = API.use.oadoi.doi meta.doi, false
# use oadoi for specific doi
if oadoi?.best_oa_location?.license and oadoi.best_oa_location.license.indexOf('cc') isnt -1
doa =
can_archive: true
version: oadoi.best_oa_location.version
versions: []
licence: oadoi.best_oa_location.license
licence_terms: ""
licences: []
locations: ['institutional repository']
issuer:
type: 'article'
has_policy: 'yes'
id: meta.doi
meta:
creator: ['<EMAIL>']
contributors: ['<EMAIL>']
monitoring: 'Automatic'
updated: oadoi.best_oa_location.updated
provenance:
oa_evidence: oadoi.best_oa_location.evidence
if typeof doa.licence is 'string'
doa.licences = [{type: doa.licence, terms: ""}]
if doa.version
doa.versions = if doa.version in ['submittedVersion','preprint'] then ['submittedVersion'] else if doa.version in ['acceptedVersion','postprint'] then ['submittedVersion', 'acceptedVersion'] else ['submittedVersion', 'acceptedVersion', 'publishedVersion']
doa.score = _score doa
perms.all_permissions.push doa
# sort rors by score, and sort alts by score, then combine
if perms.all_permissions.length
perms.all_permissions = _.sortBy(perms.all_permissions, 'score').reverse()
# note if enforcement_from is after published date, don't apply the permission. If no date, the permission applies to everything
for wp in perms.all_permissions
if not wp.provenance?.enforcement_from
perms.best_permission = JSON.parse JSON.stringify wp
break
else if not meta.published or moment(meta.published,'YYYY-MM-DD').isAfter(moment(wp.provenance.enforcement_from,'DD/MM/YYYY'))
perms.best_permission = JSON.parse JSON.stringify wp
break
if rors.length
rors = _.sortBy(rors, 'score').reverse()
for ro in rors
perms.all_permissions.push ro
if not perms.best_permission?.author_affiliation_requirement?
if perms.best_permission?
if not ro.provenance?.enforcement_from or not meta.published or moment(meta.published,'YYYY-MM-DD').isAfter(moment(ro.provenance.enforcement_from,'DD/MM/YYYY'))
pb = JSON.parse JSON.stringify perms.best_permission
for key in ['<KEY>', 'versions', 'locations']
for vl in (ro[key] ? [])
pb[key] ?= []
pb[key].push(vl) if vl not in pb[key]
for l in pb.licences ? []
pb.licence = l.type if not pb.licence? or l.type.length < pb.licence.length
pb.version = if 'publishedVersion' in pb.versions or 'publisher pdf' in pb.versions then 'publishedVersion' else if 'acceptedVersion' in pb.versions or 'postprint' in pb.versions then 'acceptedVersion' else 'submittedVersion'
if pb.embargo_end
if ro.embargo_end
if moment(ro.embargo_end,"YYYY-MM-DD").isBefore(moment(pb.embargo_end,"YYYY-MM-DD"))
pb.embargo_end = ro.embargo_end
if pb.embargo_months and ro.embargo_months? and ro.embargo_months < pb.embargo_months
pb.embargo_months = ro.embargo_months
pb.can_archive = true if ro.can_archive is true
pb.requirements ?= {}
pb.requirements.author_affiliation_requirement = if not meta.ror? then ro.issuer.id else if typeof meta.ror is 'string' then meta.ror else meta.ror[0]
pb.issuer.affiliation = ro.issuer
pb.meta ?= {}
pb.meta.affiliation = ro.meta
pb.provenance ?= {}
pb.provenance.affiliation = ro.provenance
pb.score = parseInt(pb.score) + parseInt(ro.score)
perms.best_permission = pb
perms.all_permissions.push pb
if file? or url?
# TODO file usage on new permissions API is still to be re-written
# is it possible file will already have been processed, if so can this step be shortened or avoided?
perms.file = API.service.oab.permission.file file, url, confirmed, meta
try perms.lantern = API.service.lantern.licence('https://doi.org/' + meta.doi) if not perms.file?.licence and meta.doi? and 'doi.org' not in url
if perms.file.archivable? and perms.file.archivable isnt true and perms.lantern?.licence? and perms.lantern.licence.toLowerCase().indexOf('cc') is 0
perms.file.licence = perms.lantern.licence
perms.file.licence_evidence = {string_match: perms.lantern.match}
perms.file.archivable = true
perms.file.archivable_reason = 'We think that the splash page the DOI resolves to contains a ' + perms.lantern.licence + ' licence statement which confirms this article can be archived'
if perms.file.archivable and not perms.file.licence?
if perms.best_permission.licence
perms.file.licence = perms.best_permission.licence
else if perms.best_permission?.deposit_statement? and perms.best_permission.deposit_statement.toLowerCase().indexOf('cc') is 0
perms.file.licence = perms.best_permission.deposit_statement
perms.best_permission.licence ?= perms.file.licence if perms.file.licence
if perms.file.same_paper and not perms.file.archivable and perms.file.version?
if perms.best_permission?.version? and perms.file.version is perms.best_permission.version
perms.file.archivable = true
perms.file.archivable_reason = 'We believe this is a ' + perms.file.version + ' and our permission system says that version can be shared'
else
perms.file.archivable_reason ?= 'We believe this file is a ' + perms.file.version + ' version and our permission system does not list that as an archivable version'
if overall_policy_restriction
msgs =
'not publisher': 'Please find another DOI for this article as this is provided as this doesn’t allow us to find required information like who published it'
return
body: if typeof overall_policy_restriction isnt 'string' then overall_policy_restriction else msgs[overall_policy_restriction.toLowerCase()] ? overall_policy_restriction
status: 501
else
return perms
# https://docs.google.com/spreadsheets/d/1qBb0RV1XgO3xOQMdHJBAf3HCJlUgsXqDVauWAtxde4A/edit
API.service.oab.permission.import = (reload=false, src, stale=1000) ->
# unfortunately for now there appears to be no way to uniquely identify a record
# so if ANY show last updated in the last day, reload them all
reload = true
since = Date.now()-86400010 # 1 day and 10ms ago, just to give a little overlap
keys =
versionsarchivable: 'versions'
permissionsrequestcontactemail: 'permissions_contact'
archivinglocationsallowed: 'locations'
license: 'licence'
licencesallowed: 'licences'
'post-printembargo': 'embargo_months'
depositstatementrequired: 'deposit_statement'
copyrightowner: 'copyright_owner' # can be journal, publisher, affiliation or author
publicnotes: 'notes'
authoraffiliationrolerequirement: 'requirements.role'
authoraffiliationrequirement: 'requirements.affiliation'
authoraffiliationdepartmentrequirement: 'requirements.departmental_affiliation'
iffundedby: 'requirements.funder'
fundingproportionrequired: 'requirements.funding_proportion'
subjectcoverage: 'requirements.subject'
has_policy: 'issuer.has_policy'
permissiontype: 'issuer.type'
parentpolicy: 'issuer.parent_policy'
contributedby: 'meta.contributors'
recordlastupdated: 'meta.updated'
reviewers: 'meta.reviewer'
addedby: 'meta.creator'
monitoringtype: 'meta.monitoring'
policyfulltext: 'provenance.archiving_policy'
policylandingpage: 'provenance.archiving_policy_splash'
publishingagreement: 'provenance.sample_publishing_agreement'
publishingagreementsplash: 'provenance.sample_publishing_splash'
rights: 'provenance.author_rights'
embargolist: 'provenance.embargo_list'
policyfaq: 'provenance.faq'
miscsource: 'provenance.misc_source'
enforcementdate: 'provenance.enforcement_from'
example: 'provenance.example'
src ?= API.settings.service?.openaccessbutton?.permissions?.sheet
records = API.use.google.sheets.feed src, stale # get a new sheet if over an hour old
ready = []
for rec in records
nr =
can_archive: false
version: undefined
versions: undefined
licence: undefined
licence_terms: undefined
licences: undefined
locations: undefined
embargo_months: undefined
embargo_end: undefined
deposit_statement: undefined
permission_required: undefined
permissions_contact: undefined
copyright_owner: undefined
copyright_name: undefined
copyright_year: undefined
notes: undefined
requirements: undefined
issuer: {}
meta: {}
provenance: undefined
try
rec.recordlastupdated = rec.recordlastupdated.trim()
if rec.recordlastupdated.indexOf(',') isnt -1
nd = false
for dt in rec.recordlastupdated.split ','
nd = dt.trim() if nd is false or moment(dt.trim(),'DD/MM/YYYY').isAfter(moment(nd,'DD/MM/YYYY'))
rec.recordlastupdated = nd if nd isnt false
nr.meta.updated = rec.recordlastupdated
nr.meta.updatedAt = moment(nr.meta.updated, 'DD/MM/YYYY').valueOf() if nr.meta.updated?
if reload or not nr.meta.updatedAt? or nr.meta.updatedAt > since
# the google feed import will lowercase these key names and remove whitespace, question marks, brackets too, but not dashes
nr.issuer.id = if rec.id.indexOf(',') isnt -1 then rec.id.split(',') else rec.id
if typeof nr.issuer.id isnt 'string'
cids = []
inaj = false
for nid in nr.issuer.id
nid = nid.trim()
if nr.issuer.type is 'journal' and nid.indexOf('-') isnt -1 and nid.indexOf(' ') is -1
nid = nid.toUpperCase()
if af = academic_journal.find 'issn.exact:"' + nid + '"'
inaj = true
for an in af.issn
cids.push(an) if an not in cids
cids.push(nid) if nid not in cids
nr.issuer.id = cids
nr.permission_required = rec.has_policy? and rec.has_policy.toLowerCase().indexOf('permission required') isnt -1
for k of rec
if keys[k] and rec[k]? and rec[k].length isnt 0
nk = keys[k]
nv = undefined
if k is 'post-printembargo' # Post-Print Embargo - empty or number of months like 0, 12, 24
try
kn = parseInt rec[k].trim()
nv = kn if typeof kn is 'number' and not isNaN kn and kn isnt 0
nr.embargo_end = '' if nv? # just to allow neat output later - can't be calculated until compared to a particular article
else if k in ['journal', 'versionsarchivable', 'archivinglocationsallowed', 'licencesallowed', 'policyfulltext', 'contributedby', 'addedby', 'reviewers', 'iffundedby']
nv = []
for s in rcs = rec[k].trim().split ','
st = s.trim()
if k is 'licencesallowed'
if st.toLowerCase() isnt 'unclear'
lc = type: st.toLowerCase()
try lc.terms = rec.licenceterms.split(',')[rcs.indexOf(s)].trim() # these don't seem to exist any more...
nv.push lc
else
if k is 'versionsarchivable'
st = st.toLowerCase()
st = 'submittedVersion' if st is 'preprint'
st = 'acceptedVersion' if st is 'postprint'
st = 'publishedVersion' if st is 'publisher pdf'
nv.push(if k in ['archivinglocationsallowed'] then st.toLowerCase() else st) if st.length and st not in nv
else if k not in ['recordlastupdated']
nv = rec[k].trim()
nv = nv.toLowerCase() if typeof nv is 'string' and (nv.toLowerCase() in ['yes','no'] or k in ['haspolicy','permissiontype','copyrightowner'])
nv = '' if k in ['copyrightowner','license'] and nv is 'unclear'
if nv?
if nk.indexOf('.') isnt -1
nps = nk.split '.'
nr[nps[0]] ?= {}
nr[nps[0]][[nps[1]]] = nv
else
nr[nk] = nv
# Archived Full Text Link - a URL to a web archive link of the full text policy link (ever multiple?)
# Record First Added - date like 12/07/2017
# Post-publication Pre-print Update Allowed - string like No, Yes, could be empty (turn these to booleans?)
# Can Authors Opt Out - seems to be all empty, could presumably be Yes or No
nr.licences ?= []
if not nr.licence
for l in nr.licences
if not nr.licence? or l.type.length < nr.licence.length
nr.licence = l.type
nr.licence_terms = l.terms
nr.versions ?= []
if nr.versions.length
nr.can_archive = true
nr.version = if 'acceptedVersion' in nr.versions or 'postprint' in nr.versions then 'acceptedVersion' else if 'publishedVersion' in nr.versions or 'publisher pdf' in nr.versions then 'publishedVersion' else 'submittedVersion'
nr.copyright_owner ?= nr.issuer?.type ? ''
nr.copyright_name ?= ''
nr.copyright_year ?= '' # the year of publication, to be added at result stage
ready.push(nr) if not _.isEmpty nr
# TODO if there is a provenance.example DOI look up the metadata for it and find the journal ISSN.
# then have a search for ISSN be able to find that. Otherwise, we have coverage by publisher that
# contains no journal info, so no way to go from ISSN to the stored record
if ready.length
if reload
# ideally want a unique ID per record so would only have to update the changed ones
# but as that is not yet possible, have to just dump and reload all
oab_permissions.remove '*'
oab_permissions.insert ready
API.mail.send
service: 'openaccessbutton'
from: '<EMAIL>'
to: ['<EMAIL>','<EMAIL>']
subject: 'OAB permissions import check complete' + if API.settings.dev then ' (dev)' else ''
text: 'Found ' + records.length + ' in sheet, imported ' + ready.length + ' records'
return ready.length
# run import every day on the main machine
_oab_permissions_import = () ->
if API.settings.cluster?.ip? and API.status.ip() not in API.settings.cluster.ip
API.log 'Setting up an OAB permissions import to run every day if not triggered by request on ' + API.status.ip()
Meteor.setInterval (() -> API.service.oab.permission.import()), 86400000
Meteor.setTimeout _oab_permissions_import, 24000
API.service.oab.permission.file = (file, url, confirmed, meta={}) ->
f = {archivable: undefined, archivable_reason: undefined, version: 'unknown', same_paper: undefined, licence: undefined}
# handle different sorts of file passing
if typeof file is 'string'
file = data: file
if _.isArray file
file = if file.length then file[0] else undefined
if not file? and url?
file = API.http.getFile url
if file?
file.name ?= file.filename
try f.name = file.name
try f.format = if file.name? and file.name.indexOf('.') isnt -1 then file.name.substr(file.name.lastIndexOf('.')+1) else 'html'
if file.data
if f.format is 'pdf'
try content = API.convert.pdf2txt file.data
if not content? and f.format? and API.convert[f.format+'2txt']?
try content = API.convert[f.format+'2txt'] file.data
if not content?
content = API.convert.file2txt file.data, {name: file.name}
if not content?
fd = file.data
if typeof file.data isnt 'string'
try fd = file.data.toString()
try
if fd.indexOf('<html') is 0
content = API.convert.html2txt fd
else if file.data.indexOf('<xml') is 0
content = API.convert.xml2txt fd
try content ?= file.data
try content = content.toString()
if not content? and not confirmed
if file? or url?
f.error = file.error ? 'Could not extract any content'
else
_clean = (str) -> return str.toLowerCase().replace(/[^a-z0-9\/\.]+/g, "").replace(/\s\s+/g, ' ').trim()
contentsmall = if content.length < 20000 then content else content.substring(0,6000) + content.substring(content.length-6000,content.length)
lowercontentsmall = contentsmall.toLowerCase()
lowercontentstart = _clean(if lowercontentsmall.length < 6000 then lowercontentsmall else lowercontentsmall.substring(0,6000))
f.name ?= meta.title
try f.checksum = crypto.createHash('md5').update(content, 'utf8').digest('base64')
f.same_paper_evidence = {} # check if the file meets our expectations
try f.same_paper_evidence.words_count = content.split(' ').length # will need to be at least 500 words
try f.same_paper_evidence.words_more_than_threshold = if f.same_paper_evidence.words_count > 500 then true else false
try f.same_paper_evidence.doi_match = if meta.doi and lowercontentstart.indexOf(_clean meta.doi) isnt -1 then true else false # should have the doi in it near the front
#if content and not f.same_paper_evidence.doi_match and not meta.title?
# meta = API.service.oab.metadata undefined, meta, content # get at least title again if not already tried to get it, and could not find doi in the file
try f.same_paper_evidence.title_match = if meta.title and lowercontentstart.replace(/\./g,'').indexOf(_clean meta.title.replace(/ /g,'').replace(/\./g,'')) isnt -1 then true else false
if meta.author?
try
authorsfound = 0
f.same_paper_evidence.author_match = false
# get the surnames out if possible, or author name strings, and find at least one in the doc if there are three or less, or find at least two otherwise
meta.author = {name: meta.author} if typeof meta.author is 'string'
meta.author = [meta.author] if not _.isArray meta.author
for a in meta.author
if f.same_paper_evidence.author_match is true
break
else
try
an = (a.last ? a.lastname ? a.family ? a.surname ? a.name).trim().split(',')[0].split(' ')[0]
af = (a.first ? a.firstname ? a.given ? a.name).trim().split(',')[0].split(' ')[0]
inc = lowercontentstart.indexOf _clean an
if an.length > 2 and af.length > 0 and inc isnt -1 and lowercontentstart.substring(inc-20,inc+an.length+20).indexOf(_clean af) isnt -1
authorsfound += 1
if (meta.author.length < 3 and authorsfound is 1) or (meta.author.length > 2 and authorsfound > 1)
f.same_paper_evidence.author_match = true
break
if f.format?
for ft in ['doc','tex','pdf','htm','xml','txt','rtf','odf','odt','page']
if f.format.indexOf(ft) isnt -1
f.same_paper_evidence.document_format = true
break
f.same_paper = if f.same_paper_evidence.words_more_than_threshold and (f.same_paper_evidence.doi_match or f.same_paper_evidence.title_match or f.same_paper_evidence.author_match) and f.same_paper_evidence.document_format then true else false
if f.same_paper_evidence.words_count < 150 and f.format is 'pdf'
# there was likely a pdf file reading failure due to bad PDF formatting
f.same_paper_evidence.words_count = 0
f.archivable_reason = 'We could not find any text in the provided PDF. It is possible the PDF is a scan in which case text is only contained within images which we do not yet extract. Or, the PDF may have errors in it\'s structure which stops us being able to machine-read it'
f.version_evidence = score: 0, strings_checked: 0, strings_matched: []
try
# dev https://docs.google.com/spreadsheets/d/<KEY>/edit#gid=0
# live https://docs.google.com/spreadsheets/d/<KEY>/edit#gid=0
for l in API.use.google.sheets.feed (if API.settings.dev then '<KEY>' else '<KEY>')
try
f.version_evidence.strings_checked += 1
wts = l.whattosearch
if wts.indexOf('<<') isnt -1 and wts.indexOf('>>') isnt -1
wtm = wts.split('<<')[1].split('>>')[0]
wts = wts.replace('<<'+wtm+'>>',meta[wtm.toLowerCase()]) if meta[wtm.toLowerCase()]?
matched = false
if l.howtosearch is 'string'
#wtsc = _clean wts
#matched = if (l.wheretosearch is 'file' and _clean(lowercontentsmall).indexOf(wtsc) isnt -1) or (l.wheretosearch isnt 'file' and ((meta.title? and _clean(meta.title).indexOf(wtsc) isnt -1) or (f.name? and _clean(f.name).indexOf(wtsc) isnt -1))) then true else false
matched = if (l.wheretosearch is 'file' and contentsmall.indexOf(wts) isnt -1) or (l.wheretosearch isnt 'file' and ((meta.title? and meta.title.indexOf(wts) isnt -1) or (f.name? and f.name.indexOf(wts) isnt -1))) then true else false
else
# could change this to be explicit and not use lowercasing, if wanting more exactness
re = new RegExp wts, 'gium'
matched = if (l.wheretosearch is 'file' and lowercontentsmall.match(re) isnt null) or (l.wheretosearch isnt 'file' and ((meta.title? and meta.title.match(re) isnt null) or (f.name? and f.name.match(re) isnt null))) then true else false
if matched
sc = l.score ? l.score_value
if typeof sc is 'string'
try sc = parseInt sc
sc = 1 if typeof sc isnt 'number'
if l.whatitindicates is 'publisher pdf' then f.version_evidence.score += sc else f.version_evidence.score -= sc
f.version_evidence.strings_matched.push {indicates: l.whatitindicates, found: l.howtosearch + ' ' + wts, in: l.wheretosearch, score_value: sc}
f.version = 'publishedVersion' if f.version_evidence.score > 0
f.version = 'acceptedVersion' if f.version_evidence.score < 0
if f.version is 'unknown' and f.version_evidence.strings_checked > 0 #and f.format? and f.format isnt 'pdf'
f.version = 'acceptedVersion'
try
ls = API.service.lantern.licence undefined, undefined, lowercontentsmall # check lantern for licence info in the file content
if ls?.licence?
f.licence = ls.licence
f.licence_evidence = {string_match: ls.match}
f.lantern = ls
f.archivable = false
if confirmed
f.archivable = true
if confirmed is f.checksum
f.archivable_reason = 'The administrator has confirmed that this file is a version that can be archived.'
f.admin_confirms = true
else
f.archivable_reason = 'The depositor says that this file is a version that can be archived'
f.depositor_says = true
else if f.same_paper
if f.format isnt 'pdf'
f.archivable = true
f.archivable_reason = 'Since the file is not a PDF, we assume it is a Postprint.'
if not f.archivable and f.licence? and f.licence.toLowerCase().indexOf('cc') is 0
f.archivable = true
f.archivable_reason = 'It appears this file contains a ' + f.lantern.licence + ' licence statement. Under this licence the article can be archived'
if not f.archivable
if f.version is 'publishedVersion'
f.archivable_reason = 'The file given is a Publisher PDF, and only postprints are allowed'
else
f.archivable_reason = 'We cannot confirm if it is an archivable version or not'
else
f.archivable_reason ?= if not f.same_paper_evidence.words_more_than_threshold then 'The file is less than 500 words, and so does not appear to be a full article' else if not f.same_paper_evidence.document_format then 'File is an unexpected format ' + f.format else if not meta.doi and not meta.title then 'We have insufficient metadata to validate file is for the correct paper ' else 'File does not contain expected metadata such as DOI or title'
return f
API.service.oab.permission.test = (email) ->
res = {tests: 0, same: 0, results: {}}
for test in ts = API.use.google.sheets.feed '1v<KEY>', 0
break if res.tests > 2
if test.doi and test.doi.startsWith('10.') and test.responseurl
console.log res.tests
res.tests += 1
res.results[test.doi] = {}
try
perms = API.service.oab.permission(doi: test.doi.split('?')[0], ror: (if test.doi.indexOf('?') isnt -1 then test.doi.split('?')[1].split('=')[1] else undefined)).best_permission
catch
perms = {}
try
ricks = HTTP.call('GET', test.responseurl).data.authoritative_permission.application
catch
ricks = {}
if perms? and ricks?
diffs = {}
for k in ['can_archive']
if not perms[k]? or not ricks[k]? or perms[k] isnt ricks[k]
diffs[k] = [perms[k],ricks[k]]
if _.isEmpty diffs
res.same += 1
res.results[test.doi].same = true
else
res.results[test.doi].same = false
res.results[test.doi].diffs = diffs
res.results[test.doi].perms = perms
res.results[test.doi].ricks = ricks
API.mail.send
service: 'openaccessbutton'
from: '<EMAIL>'
to: email ? '<EMAIL>'
subject: 'OAB permissions test complete'
text: JSON.stringify res, '', 2
return res | true |
# See https://github.com/OAButton/discussion/issues/1516
import crypto from 'crypto'
import moment from 'moment'
API.add 'service/oab/permissions',
get: () ->
if this.queryParams?.q? or this.queryParams.source? or _.isEmpty this.queryParams
return oab_permissions.search this.queryParams
else
return API.service.oab.permission this.queryParams, this.queryParams.content, this.queryParams.url, this.queryParams.confirmed, this.queryParams.uid, this.queryParams.meta
post: () ->
if not this.request.files? and typeof this.request.body is 'object' and (this.request.body.q? or this.request.body.source?)
this.bodyParams[k] ?= this.queryParams[k] for k of this.queryParams
return oab_permissions.search this.bodyParams
else
return API.service.oab.permission this.queryParams, this.request.files ? this.request.body, undefined, this.queryParams.confirmed ? this.bodyParams?.confirmed, this.queryParams.uid, this.queryParams.meta
API.add 'service/oab/permissions/:issnorpub',
get: () ->
if typeof this.urlParams.issnorpub is 'string' and this.urlParams.issnorpub.indexOf('-') isnt -1 and this.urlParams.issnorpub.indexOf('10.') isnt 0 and this.urlParams.issnorpub.length < 10
this.queryParams.issn ?= this.urlParams.issnorpub
else if this.urlParams.issnorpub.indexOf('10.') isnt 0
this.queryParams.publisher ?= this.urlParams.issnorpub # but this could be a ror too... any way to tell?
return API.service.oab.permission this.queryParams
API.add 'service/oab/permissions/:doi/:doi2',
get: () ->
this.queryParams.doi ?= this.urlParams.doi + '/' + this.urlParams.doi2
return API.service.oab.permission this.queryParams
API.add 'service/oab/permissions/:doi/:doi2/:doi3',
get: () ->
this.queryParams.doi ?= this.urlParams.doi + '/' + this.urlParams.doi2 + '/' + this.urlParams.doi3
return API.service.oab.permission this.queryParams
API.add 'service/oab/permissions/journal',
get: () -> return oab_permissions.search this.queryParams, restrict: [exists: field: 'journal']
post: () -> return oab_permissions.search this.bodyParams, restrict: [exists: field: 'journal']
API.add 'service/oab/permissions/journal/:issnorid',
get: () ->
if this.urlParams.issnorid.indexOf('-') is -1 and j = oab_permissions.get this.urlParams.issnorid
return j
else if j = oab_permissions.find journal: this.urlParams.issnorid
return j
else if this.urlParams.issnorid.indexOf('-') isnt -1
return API.service.oab.permission {issn: this.urlParams.issnorid, doi: this.queryParams.doi}
API.add 'service/oab/permissions/publisher',
get: () -> return oab_permissions.search this.queryParams, restrict: [exists: field: 'publisher']
post: () -> return oab_permissions.search this.bodyParams, restrict: [exists: field: 'publisher']
API.add 'service/oab/permissions/publisher/:norid',
get: () ->
if p = oab_permissions.get this.urlParams.norid
return p
else if p = oab_permissions.find 'issuer.id': this.urlParams.norid
return p
else
return API.service.oab.permission {publisher: this.urlParams.norid, doi: this.queryParams.doi, issn: this.queryParams.issn}
API.add 'service/oab/permissions/affiliation',
get: () -> return oab_permissions.search this.queryParams, restrict: [exists: field: 'affiliation']
post: () -> return oab_permissions.search this.bodyParams, restrict: [exists: field: 'affiliation']
API.add 'service/oab/permissions/affiliation/:rororid', # could also be a two letter country code, which is in the same affiliation field as the ROR
get: () ->
if a = oab_permissions.get this.urlParams.rororid
return a
else if a = oab_permissions.find 'issuer.id': this.urlParams.rororid
return a
else
return API.service.oab.permission {affiliation: this.urlParams.rororid, publisher: this.queryParams.publisher, doi: this.queryParams.doi, issn: this.queryParams.issn}
API.add 'service/oab/permissions/import',
get:
roleRequired: if API.settings.dev then undefined else 'openaccessbutton.admin'
action: () ->
Meteor.setTimeout (() => API.service.oab.permission.import this.queryParams.reload, undefined, this.queryParams.stale), 1
return true
API.add 'service/oab/permissions/test', get: () -> return API.service.oab.permission.test this.queryParams.email
API.service.oab.permission = (meta={}, file, url, confirmed, roruid, getmeta) ->
overall_policy_restriction = false
cr = false
haddoi = false
_prep = (rec) ->
if haddoi and rec.embargo_months and (meta.published or meta.year)
em = moment meta.published ? meta.year + '-01-01'
em = em.add rec.embargo_months, 'months'
#if em.isAfter moment() # changed 09112020 by JM request to always add embargo_end if we can calculate it, even if it is in the past.
rec.embargo_end = em.format "YYYY-MM-DD"
delete rec.embargo_end if rec.embargo_end is ''
rec.copyright_name = if rec.copyright_owner is 'publisher' then (if typeof rec.issuer.parent_policy is 'string' then rec.issuer.parent_policy else if typeof rec.issuer.id is 'string' then rec.issuer.id else rec.issuer.id[0]) else if rec.copyright_owner in ['journal','affiliation'] then (meta.journal ? '') else if (rec.copyright_owner and rec.copyright_owner.toLowerCase().indexOf('author') isnt -1) and meta.author? and meta.author.length and (meta.author[0].name or meta.author[0].family) then (meta.author[0].name ? meta.author[0].family) + (if meta.author.length > 1 then ' et al' else '') else ''
if rec.copyright_name in ['publisher','journal'] and (cr or meta.doi or rec.provenance?.example)
if cr is false
cr = API.use.crossref.works.doi meta.doi ? rec.provenance.example
if cr?.assertion? and cr.assertion.length
for a in cr.assertion
if a.name.toLowerCase() is 'copyright'
try rec.copyright_name = a.value
try rec.copyright_name = a.value.replace('\u00a9 ','').replace(/[0-9]/g,'').trim()
rec.copyright_year = meta.year if haddoi and rec.copyright_year is '' and meta.year
delete rec.copyright_year if rec.copyright_year is ''
#for ds in ['copyright_name','copyright_year']
# delete rec[ds] if rec[ds] is ''
if haddoi and rec.deposit_statement? and rec.deposit_statement.indexOf('<<') isnt -1
fst = ''
for pt in rec.deposit_statement.split '<<'
if fst is '' and pt.indexOf('>>') is -1
fst += pt
else
eph = pt.split '>>'
ph = eph[0].toLowerCase()
swaps =
'journal title': 'journal'
'vol': 'volume'
'date of publication': 'published'
'(c)': 'year'
'article title': 'title'
'copyright name': 'copyright_name'
ph = swaps[ph] if swaps[ph]?
if ph is 'author'
try fst += (meta.author[0].name ? meta.author[0].family) + (if meta.author.length > 1 then ' et al' else '')
else
fst += meta[ph] ? rec[ph] ? ''
try fst += eph[1]
rec.deposit_statement = fst
if rec._id?
rec.meta ?= {}
rec.meta.source = 'https://' + (if API.settings.dev then 'dev.api.cottagelabs.com/service/oab/permissions/' else 'api.openaccessbutton.org/permissions/') + (if rec.issuer.type then rec.issuer.type + '/' else '') + rec._id
if typeof rec.issuer?.has_policy is 'string' and rec.issuer.has_policy.toLowerCase().trim() in ['not publisher','takedown']
# find out if this should be enacted if it is the case for any permission, or only the best permission
overall_policy_restriction = rec.issuer.has_policy
delete rec[d] for d in ['_id','permission_required','createdAt','updatedAt','created_date','updated_date']
try delete rec.issuer.updatedAt
return rec
_score = (rec) ->
score = if rec.can_archive then 1000 else 0
score += 1000 if rec.provenance?.oa_evidence is 'In DOAJ'
if rec.requirements?
# TODO what about cases where the requirement is met?
# and HOW is requirement met? we search ROR against issuer, but how does that match with author affiliation?
# should we even be searching for permissions by ROR, or only using it to calculate the ones we find by some other means?
# and if it is not met then is can_archive worth anything?
score -= 10
else
score += if rec.version is 'publishedVersion' then 200 else if rec.version is 'acceptedVersion' then 100 else 0
score -= 5 if rec.licences? and rec.licences.length
score += if rec.issuer?.type is 'journal' then 5 else if rec.issuer?.type is 'publisher' then 4 else if rec.issuer?.type is 'university' then 3 else if rec.issuer?.type in 'article' then 2 else 0
score -= 25 if rec.embargo_months and rec.embargo_months >= 36 and (not rec.embargo_end or moment(rec.embargo_end,"YYYY-MM-DD").isBefore(moment()))
return score
inp = {}
if typeof meta is 'string'
meta = if meta.indexOf('10.') is 0 then {doi: meta} else {issn: meta}
delete meta.meta if meta.meta? # just used to pass in a false to getmeta
if meta.metadata? # if passed a catalogue object
inp = meta
meta = meta.metadata
if meta.affiliation
meta.ror = meta.affiliation
delete meta.affiliation
if meta.journal and meta.journal.indexOf(' ') is -1
meta.issn = meta.journal
delete meta.journal
if meta.publisher and meta.publisher.indexOf(' ') is -1 and meta.publisher.indexOf(',') is -1 and not oab_permissions.find 'issuer.type.exact:"publisher" AND issuer.id:"' + meta.publisher + '"'
# it is possible this may actually be a ror, so switch to ror just in case - if it still matches nothing, no loss
meta.ror = meta.publisher
delete meta.publisher
issns = if _.isArray(meta.issn) then meta.issn else [] # only if directly passed a list of ISSNs for the same article, accept them as the ISSNs list to use
meta.issn = meta.issn.split(',') if typeof meta.issn is 'string' and meta.issn.indexOf(',') isnt -1
meta.ror = meta.ror.split(',') if typeof meta.ror is 'string' and meta.ror.indexOf(',') isnt -1
if not meta.ror
uc = if typeof roruid is 'object' then roruid else if typeof roruid is 'string' then API.service.oab.deposit.config(roruid) else undefined
if (typeof uc is 'object' and uc.ror?) or typeof roruid is 'string'
meta.ror = uc?.ror ? roruid
if _.isEmpty(meta) or (meta.issn and JSON.stringify(meta.issn).indexOf('-') is -1) or (meta.doi and (typeof meta.doi isnt 'string' or meta.doi.indexOf('10.') isnt 0 or meta.doi.indexOf('/') is -1))
return body: 'No valid DOI, ISSN, or ROR provided', statusCode: 404
# NOTE later will want to find affiliations related to the authors of the paper, but for now only act on affiliation provided as a ror
# we now always try to get the metadata because joe wants to serve a 501 if the doi is not a journal article
_getmeta = () ->
psm = JSON.parse JSON.stringify meta
delete psm.ror
if not _.isEmpty psm
rsm = API.service.oab.metadata {metadata: ['crossref_type','issn','publisher','published','year','author','ror']}, psm
for mk of rsm
meta[mk] ?= rsm[mk]
_getmeta() if getmeta isnt false and meta.doi and (not meta.publisher or not meta.issn)
meta.published = meta.year + '-01-01' if not meta.published and meta.year
haddoi = meta.doi?
af = false
if meta.issn
meta.issn = [meta.issn] if typeof meta.issn is 'string'
if not issns.length # they're already meta.issn in this case anyway
for inisn in meta.issn
issns.push(inisn) if inisn not in issns # check just in case
if not issns.length or not meta.publisher or not meta.doi
if af = academic_journal.find 'issn.exact:"' + issns.join('" OR issn.exact:"') + '"'
meta.publisher ?= af.publisher
for an in (if typeof af.issn is 'string' then [af.issn] else af.issn)
issns.push(an) if an not in issns # check again
meta.doi ?= af.doi
try
meta.doi ?= API.use.crossref.journals.doi issns
catch # temporary until wider crossref update completed
meta.doi ?= API.use.crossref.journals.dois.example issns
_getmeta() if not haddoi and meta.doi
if haddoi and meta.crossref_type not in ['journal-article']
return
body: 'DOI is not a journal article'
status: 501
if meta.publisher and meta.publisher.indexOf('(') isnt -1 and meta.publisher.lastIndexOf(')') > (meta.publisher.length*.7)
# could be a publisher name with the acronym at the end, like Public Library of Science (PLoS)
# so get rid of the acronym because that is not included in the publisher name in crossref and other sources
meta.publisher = meta.publisher.substring(0, meta.publisher.lastIndexOf('(')).trim()
try
meta.citation = '['
meta.citation += meta.title + '. ' if meta.title
meta.citation += meta.journal + ' ' if meta.journal
meta.citation += meta.volume + (if meta.issue then ', ' else ' ') if meta.volume
meta.citation += meta.issue + ' ' if meta.issue
meta.citation += 'p' + (meta.page ? meta.pages) if meta.page? or meta.pages?
if meta.year or meta.published
meta.citation += ' (' + (meta.year ? meta.published).split('-')[0] + ')'
meta.citation = meta.citation.trim()
meta.citation += ']'
perms = best_permission: undefined, all_permissions: [], file: undefined
rors = []
if meta.ror?
meta.ror = [meta.ror] if typeof meta.ror is 'string'
rs = oab_permissions.search 'issuer.id.exact:"' + meta.ror.join('" OR issuer.id.exact:"') + '"'
if not rs?.hits?.total
# look up the ROR in wikidata - if found, get the qid from the P17 country snak, look up that country qid
# get the P297 ISO 3166-1 alpha-2 code, search affiliations for that
if rwd = wikidata_record.find 'snaks.property.exact:"P6782" AND snaks.property.exact:"P17" AND (snaks.value.exact:"' + meta.ror.join(" OR snaks.value.exact:") + '")'
snkd = false
for snak in rwd.snaks
if snkd
break
else if snak.property is 'P17'
if cwd = wikidata_record.get snak.qid
for sn in cwd.snaks
if sn.property is 'P297'
snkd = true
rs = oab_permissions.search 'issuer.id.exact:"' + sn.value + '"'
break
for rr in rs?.hits?.hits ? []
tr = _prep rr._source
tr.score = _score tr
rors.push tr
if issns.length or meta.publisher
qr = if issns.length then 'issuer.id.exact:"' + issns.join('" OR issuer.id.exact:"') + '"' else ''
if meta.publisher
qr += ' OR ' if qr isnt ''
qr += 'issuer.id:"' + meta.publisher + '"' # how exact/fuzzy can this be
ps = oab_permissions.search qr
if ps?.hits?.hits? and ps.hits.hits.length
for p in ps.hits.hits
rp = _prep p._source
rp.score = _score rp
perms.all_permissions.push rp
if perms.all_permissions.length is 0 and meta.publisher and not meta.doi and not issns.length
af = academic_journal.find 'publisher:"' + meta.publisher + '"'
if not af?
fz = academic_journal.find 'publisher:"' + meta.publisher.split(' ').join(' AND publisher:"') + '"'
if fz.publisher is meta.publisher
af = fz
else
lvs = API.tdm.levenshtein fz.publisher, meta.publisher, true
longest = if lvs.length.a > lvs.length.b then lvs.length.a else lvs.length.b
af = fz if lvs.distance < 5 or longest/lvs.distance > 10
if typeof af is 'object' and af.is_oa
pisoa = academic_journal.count('publisher:"' + af.publisher + '"') is academic_journal.count('publisher:"' + af.publisher + '" AND is_oa:true')
af = false if not af.is_oa or not pisoa
if typeof af is 'object' and af.is_oa isnt false
af.is_oa = true if not af.is_oa? and ('doaj' in af.src or af.wikidata_in_doaj)
if af.is_oa
altoa =
can_archive: true
version: 'publishedVersion'
versions: ['publishedVersion']
licence: undefined
licence_terms: ""
licences: []
locations: ['institutional repository']
embargo_months: undefined
issuer:
type: 'journal'
has_policy: 'yes'
id: af.issn
meta:
creator: ['PI:EMAIL:<EMAIL>END_PI']
contributors: ['PI:EMAIL:<EMAIL>END_PI']
monitoring: 'Automatic'
try altoa.licence = af.license[0].type # could have doaj licence info
altoa.licence ?= af.licence # wikidata licence
if 'doaj' in af.src or af.wikidata_in_doaj
altoa.embargo_months = 0
altoa.provenance = {oa_evidence: 'In DOAJ'}
if typeof altoa.licence is 'string'
altoa.licence = altoa.licence.toLowerCase().trim()
if altoa.licence.indexOf('cc') is 0
altoa.licence = altoa.licence.replace(/ /g, '-')
else if altoa.licence.indexOf('creative') isnt -1
altoa.licence = if altoa.licence.indexOf('0') isnt -1 or altoa.licence.indexOf('zero') isnt -1 then 'cc0' else if altoa.licence.indexOf('share') isnt -1 then 'ccbysa' else if altoa.licence.indexOf('derivative') isnt -1 then 'ccbynd' else 'ccby'
else
delete altoa.licence
else
delete altoa.licence
if altoa.licence
altoa.licences = [{type: altoa.licence, terms: ""}]
altoa.score = _score altoa
perms.all_permissions.push altoa
if haddoi and meta.doi and oadoi = API.use.oadoi.doi meta.doi, false
# use oadoi for specific doi
if oadoi?.best_oa_location?.license and oadoi.best_oa_location.license.indexOf('cc') isnt -1
doa =
can_archive: true
version: oadoi.best_oa_location.version
versions: []
licence: oadoi.best_oa_location.license
licence_terms: ""
licences: []
locations: ['institutional repository']
issuer:
type: 'article'
has_policy: 'yes'
id: meta.doi
meta:
creator: ['PI:EMAIL:<EMAIL>END_PI']
contributors: ['PI:EMAIL:<EMAIL>END_PI']
monitoring: 'Automatic'
updated: oadoi.best_oa_location.updated
provenance:
oa_evidence: oadoi.best_oa_location.evidence
if typeof doa.licence is 'string'
doa.licences = [{type: doa.licence, terms: ""}]
if doa.version
doa.versions = if doa.version in ['submittedVersion','preprint'] then ['submittedVersion'] else if doa.version in ['acceptedVersion','postprint'] then ['submittedVersion', 'acceptedVersion'] else ['submittedVersion', 'acceptedVersion', 'publishedVersion']
doa.score = _score doa
perms.all_permissions.push doa
# sort rors by score, and sort alts by score, then combine
if perms.all_permissions.length
perms.all_permissions = _.sortBy(perms.all_permissions, 'score').reverse()
# note if enforcement_from is after published date, don't apply the permission. If no date, the permission applies to everything
for wp in perms.all_permissions
if not wp.provenance?.enforcement_from
perms.best_permission = JSON.parse JSON.stringify wp
break
else if not meta.published or moment(meta.published,'YYYY-MM-DD').isAfter(moment(wp.provenance.enforcement_from,'DD/MM/YYYY'))
perms.best_permission = JSON.parse JSON.stringify wp
break
if rors.length
rors = _.sortBy(rors, 'score').reverse()
for ro in rors
perms.all_permissions.push ro
if not perms.best_permission?.author_affiliation_requirement?
if perms.best_permission?
if not ro.provenance?.enforcement_from or not meta.published or moment(meta.published,'YYYY-MM-DD').isAfter(moment(ro.provenance.enforcement_from,'DD/MM/YYYY'))
pb = JSON.parse JSON.stringify perms.best_permission
for key in ['PI:KEY:<KEY>END_PI', 'versions', 'locations']
for vl in (ro[key] ? [])
pb[key] ?= []
pb[key].push(vl) if vl not in pb[key]
for l in pb.licences ? []
pb.licence = l.type if not pb.licence? or l.type.length < pb.licence.length
pb.version = if 'publishedVersion' in pb.versions or 'publisher pdf' in pb.versions then 'publishedVersion' else if 'acceptedVersion' in pb.versions or 'postprint' in pb.versions then 'acceptedVersion' else 'submittedVersion'
if pb.embargo_end
if ro.embargo_end
if moment(ro.embargo_end,"YYYY-MM-DD").isBefore(moment(pb.embargo_end,"YYYY-MM-DD"))
pb.embargo_end = ro.embargo_end
if pb.embargo_months and ro.embargo_months? and ro.embargo_months < pb.embargo_months
pb.embargo_months = ro.embargo_months
pb.can_archive = true if ro.can_archive is true
pb.requirements ?= {}
pb.requirements.author_affiliation_requirement = if not meta.ror? then ro.issuer.id else if typeof meta.ror is 'string' then meta.ror else meta.ror[0]
pb.issuer.affiliation = ro.issuer
pb.meta ?= {}
pb.meta.affiliation = ro.meta
pb.provenance ?= {}
pb.provenance.affiliation = ro.provenance
pb.score = parseInt(pb.score) + parseInt(ro.score)
perms.best_permission = pb
perms.all_permissions.push pb
if file? or url?
# TODO file usage on new permissions API is still to be re-written
# is it possible file will already have been processed, if so can this step be shortened or avoided?
perms.file = API.service.oab.permission.file file, url, confirmed, meta
try perms.lantern = API.service.lantern.licence('https://doi.org/' + meta.doi) if not perms.file?.licence and meta.doi? and 'doi.org' not in url
if perms.file.archivable? and perms.file.archivable isnt true and perms.lantern?.licence? and perms.lantern.licence.toLowerCase().indexOf('cc') is 0
perms.file.licence = perms.lantern.licence
perms.file.licence_evidence = {string_match: perms.lantern.match}
perms.file.archivable = true
perms.file.archivable_reason = 'We think that the splash page the DOI resolves to contains a ' + perms.lantern.licence + ' licence statement which confirms this article can be archived'
if perms.file.archivable and not perms.file.licence?
if perms.best_permission.licence
perms.file.licence = perms.best_permission.licence
else if perms.best_permission?.deposit_statement? and perms.best_permission.deposit_statement.toLowerCase().indexOf('cc') is 0
perms.file.licence = perms.best_permission.deposit_statement
perms.best_permission.licence ?= perms.file.licence if perms.file.licence
if perms.file.same_paper and not perms.file.archivable and perms.file.version?
if perms.best_permission?.version? and perms.file.version is perms.best_permission.version
perms.file.archivable = true
perms.file.archivable_reason = 'We believe this is a ' + perms.file.version + ' and our permission system says that version can be shared'
else
perms.file.archivable_reason ?= 'We believe this file is a ' + perms.file.version + ' version and our permission system does not list that as an archivable version'
if overall_policy_restriction
msgs =
'not publisher': 'Please find another DOI for this article as this is provided as this doesn’t allow us to find required information like who published it'
return
body: if typeof overall_policy_restriction isnt 'string' then overall_policy_restriction else msgs[overall_policy_restriction.toLowerCase()] ? overall_policy_restriction
status: 501
else
return perms
# https://docs.google.com/spreadsheets/d/1qBb0RV1XgO3xOQMdHJBAf3HCJlUgsXqDVauWAtxde4A/edit
API.service.oab.permission.import = (reload=false, src, stale=1000) ->
# unfortunately for now there appears to be no way to uniquely identify a record
# so if ANY show last updated in the last day, reload them all
reload = true
since = Date.now()-86400010 # 1 day and 10ms ago, just to give a little overlap
keys =
versionsarchivable: 'versions'
permissionsrequestcontactemail: 'permissions_contact'
archivinglocationsallowed: 'locations'
license: 'licence'
licencesallowed: 'licences'
'post-printembargo': 'embargo_months'
depositstatementrequired: 'deposit_statement'
copyrightowner: 'copyright_owner' # can be journal, publisher, affiliation or author
publicnotes: 'notes'
authoraffiliationrolerequirement: 'requirements.role'
authoraffiliationrequirement: 'requirements.affiliation'
authoraffiliationdepartmentrequirement: 'requirements.departmental_affiliation'
iffundedby: 'requirements.funder'
fundingproportionrequired: 'requirements.funding_proportion'
subjectcoverage: 'requirements.subject'
has_policy: 'issuer.has_policy'
permissiontype: 'issuer.type'
parentpolicy: 'issuer.parent_policy'
contributedby: 'meta.contributors'
recordlastupdated: 'meta.updated'
reviewers: 'meta.reviewer'
addedby: 'meta.creator'
monitoringtype: 'meta.monitoring'
policyfulltext: 'provenance.archiving_policy'
policylandingpage: 'provenance.archiving_policy_splash'
publishingagreement: 'provenance.sample_publishing_agreement'
publishingagreementsplash: 'provenance.sample_publishing_splash'
rights: 'provenance.author_rights'
embargolist: 'provenance.embargo_list'
policyfaq: 'provenance.faq'
miscsource: 'provenance.misc_source'
enforcementdate: 'provenance.enforcement_from'
example: 'provenance.example'
src ?= API.settings.service?.openaccessbutton?.permissions?.sheet
records = API.use.google.sheets.feed src, stale # get a new sheet if over an hour old
ready = []
for rec in records
nr =
can_archive: false
version: undefined
versions: undefined
licence: undefined
licence_terms: undefined
licences: undefined
locations: undefined
embargo_months: undefined
embargo_end: undefined
deposit_statement: undefined
permission_required: undefined
permissions_contact: undefined
copyright_owner: undefined
copyright_name: undefined
copyright_year: undefined
notes: undefined
requirements: undefined
issuer: {}
meta: {}
provenance: undefined
try
rec.recordlastupdated = rec.recordlastupdated.trim()
if rec.recordlastupdated.indexOf(',') isnt -1
nd = false
for dt in rec.recordlastupdated.split ','
nd = dt.trim() if nd is false or moment(dt.trim(),'DD/MM/YYYY').isAfter(moment(nd,'DD/MM/YYYY'))
rec.recordlastupdated = nd if nd isnt false
nr.meta.updated = rec.recordlastupdated
nr.meta.updatedAt = moment(nr.meta.updated, 'DD/MM/YYYY').valueOf() if nr.meta.updated?
if reload or not nr.meta.updatedAt? or nr.meta.updatedAt > since
# the google feed import will lowercase these key names and remove whitespace, question marks, brackets too, but not dashes
nr.issuer.id = if rec.id.indexOf(',') isnt -1 then rec.id.split(',') else rec.id
if typeof nr.issuer.id isnt 'string'
cids = []
inaj = false
for nid in nr.issuer.id
nid = nid.trim()
if nr.issuer.type is 'journal' and nid.indexOf('-') isnt -1 and nid.indexOf(' ') is -1
nid = nid.toUpperCase()
if af = academic_journal.find 'issn.exact:"' + nid + '"'
inaj = true
for an in af.issn
cids.push(an) if an not in cids
cids.push(nid) if nid not in cids
nr.issuer.id = cids
nr.permission_required = rec.has_policy? and rec.has_policy.toLowerCase().indexOf('permission required') isnt -1
for k of rec
if keys[k] and rec[k]? and rec[k].length isnt 0
nk = keys[k]
nv = undefined
if k is 'post-printembargo' # Post-Print Embargo - empty or number of months like 0, 12, 24
try
kn = parseInt rec[k].trim()
nv = kn if typeof kn is 'number' and not isNaN kn and kn isnt 0
nr.embargo_end = '' if nv? # just to allow neat output later - can't be calculated until compared to a particular article
else if k in ['journal', 'versionsarchivable', 'archivinglocationsallowed', 'licencesallowed', 'policyfulltext', 'contributedby', 'addedby', 'reviewers', 'iffundedby']
nv = []
for s in rcs = rec[k].trim().split ','
st = s.trim()
if k is 'licencesallowed'
if st.toLowerCase() isnt 'unclear'
lc = type: st.toLowerCase()
try lc.terms = rec.licenceterms.split(',')[rcs.indexOf(s)].trim() # these don't seem to exist any more...
nv.push lc
else
if k is 'versionsarchivable'
st = st.toLowerCase()
st = 'submittedVersion' if st is 'preprint'
st = 'acceptedVersion' if st is 'postprint'
st = 'publishedVersion' if st is 'publisher pdf'
nv.push(if k in ['archivinglocationsallowed'] then st.toLowerCase() else st) if st.length and st not in nv
else if k not in ['recordlastupdated']
nv = rec[k].trim()
nv = nv.toLowerCase() if typeof nv is 'string' and (nv.toLowerCase() in ['yes','no'] or k in ['haspolicy','permissiontype','copyrightowner'])
nv = '' if k in ['copyrightowner','license'] and nv is 'unclear'
if nv?
if nk.indexOf('.') isnt -1
nps = nk.split '.'
nr[nps[0]] ?= {}
nr[nps[0]][[nps[1]]] = nv
else
nr[nk] = nv
# Archived Full Text Link - a URL to a web archive link of the full text policy link (ever multiple?)
# Record First Added - date like 12/07/2017
# Post-publication Pre-print Update Allowed - string like No, Yes, could be empty (turn these to booleans?)
# Can Authors Opt Out - seems to be all empty, could presumably be Yes or No
nr.licences ?= []
if not nr.licence
for l in nr.licences
if not nr.licence? or l.type.length < nr.licence.length
nr.licence = l.type
nr.licence_terms = l.terms
nr.versions ?= []
if nr.versions.length
nr.can_archive = true
nr.version = if 'acceptedVersion' in nr.versions or 'postprint' in nr.versions then 'acceptedVersion' else if 'publishedVersion' in nr.versions or 'publisher pdf' in nr.versions then 'publishedVersion' else 'submittedVersion'
nr.copyright_owner ?= nr.issuer?.type ? ''
nr.copyright_name ?= ''
nr.copyright_year ?= '' # the year of publication, to be added at result stage
ready.push(nr) if not _.isEmpty nr
# TODO if there is a provenance.example DOI look up the metadata for it and find the journal ISSN.
# then have a search for ISSN be able to find that. Otherwise, we have coverage by publisher that
# contains no journal info, so no way to go from ISSN to the stored record
if ready.length
if reload
# ideally want a unique ID per record so would only have to update the changed ones
# but as that is not yet possible, have to just dump and reload all
oab_permissions.remove '*'
oab_permissions.insert ready
API.mail.send
service: 'openaccessbutton'
from: 'PI:EMAIL:<EMAIL>END_PI'
to: ['PI:EMAIL:<EMAIL>END_PI','PI:EMAIL:<EMAIL>END_PI']
subject: 'OAB permissions import check complete' + if API.settings.dev then ' (dev)' else ''
text: 'Found ' + records.length + ' in sheet, imported ' + ready.length + ' records'
return ready.length
# run import every day on the main machine
_oab_permissions_import = () ->
if API.settings.cluster?.ip? and API.status.ip() not in API.settings.cluster.ip
API.log 'Setting up an OAB permissions import to run every day if not triggered by request on ' + API.status.ip()
Meteor.setInterval (() -> API.service.oab.permission.import()), 86400000
Meteor.setTimeout _oab_permissions_import, 24000
API.service.oab.permission.file = (file, url, confirmed, meta={}) ->
f = {archivable: undefined, archivable_reason: undefined, version: 'unknown', same_paper: undefined, licence: undefined}
# handle different sorts of file passing
if typeof file is 'string'
file = data: file
if _.isArray file
file = if file.length then file[0] else undefined
if not file? and url?
file = API.http.getFile url
if file?
file.name ?= file.filename
try f.name = file.name
try f.format = if file.name? and file.name.indexOf('.') isnt -1 then file.name.substr(file.name.lastIndexOf('.')+1) else 'html'
if file.data
if f.format is 'pdf'
try content = API.convert.pdf2txt file.data
if not content? and f.format? and API.convert[f.format+'2txt']?
try content = API.convert[f.format+'2txt'] file.data
if not content?
content = API.convert.file2txt file.data, {name: file.name}
if not content?
fd = file.data
if typeof file.data isnt 'string'
try fd = file.data.toString()
try
if fd.indexOf('<html') is 0
content = API.convert.html2txt fd
else if file.data.indexOf('<xml') is 0
content = API.convert.xml2txt fd
try content ?= file.data
try content = content.toString()
if not content? and not confirmed
if file? or url?
f.error = file.error ? 'Could not extract any content'
else
_clean = (str) -> return str.toLowerCase().replace(/[^a-z0-9\/\.]+/g, "").replace(/\s\s+/g, ' ').trim()
contentsmall = if content.length < 20000 then content else content.substring(0,6000) + content.substring(content.length-6000,content.length)
lowercontentsmall = contentsmall.toLowerCase()
lowercontentstart = _clean(if lowercontentsmall.length < 6000 then lowercontentsmall else lowercontentsmall.substring(0,6000))
f.name ?= meta.title
try f.checksum = crypto.createHash('md5').update(content, 'utf8').digest('base64')
f.same_paper_evidence = {} # check if the file meets our expectations
try f.same_paper_evidence.words_count = content.split(' ').length # will need to be at least 500 words
try f.same_paper_evidence.words_more_than_threshold = if f.same_paper_evidence.words_count > 500 then true else false
try f.same_paper_evidence.doi_match = if meta.doi and lowercontentstart.indexOf(_clean meta.doi) isnt -1 then true else false # should have the doi in it near the front
#if content and not f.same_paper_evidence.doi_match and not meta.title?
# meta = API.service.oab.metadata undefined, meta, content # get at least title again if not already tried to get it, and could not find doi in the file
try f.same_paper_evidence.title_match = if meta.title and lowercontentstart.replace(/\./g,'').indexOf(_clean meta.title.replace(/ /g,'').replace(/\./g,'')) isnt -1 then true else false
if meta.author?
try
authorsfound = 0
f.same_paper_evidence.author_match = false
# get the surnames out if possible, or author name strings, and find at least one in the doc if there are three or less, or find at least two otherwise
meta.author = {name: meta.author} if typeof meta.author is 'string'
meta.author = [meta.author] if not _.isArray meta.author
for a in meta.author
if f.same_paper_evidence.author_match is true
break
else
try
an = (a.last ? a.lastname ? a.family ? a.surname ? a.name).trim().split(',')[0].split(' ')[0]
af = (a.first ? a.firstname ? a.given ? a.name).trim().split(',')[0].split(' ')[0]
inc = lowercontentstart.indexOf _clean an
if an.length > 2 and af.length > 0 and inc isnt -1 and lowercontentstart.substring(inc-20,inc+an.length+20).indexOf(_clean af) isnt -1
authorsfound += 1
if (meta.author.length < 3 and authorsfound is 1) or (meta.author.length > 2 and authorsfound > 1)
f.same_paper_evidence.author_match = true
break
if f.format?
for ft in ['doc','tex','pdf','htm','xml','txt','rtf','odf','odt','page']
if f.format.indexOf(ft) isnt -1
f.same_paper_evidence.document_format = true
break
f.same_paper = if f.same_paper_evidence.words_more_than_threshold and (f.same_paper_evidence.doi_match or f.same_paper_evidence.title_match or f.same_paper_evidence.author_match) and f.same_paper_evidence.document_format then true else false
if f.same_paper_evidence.words_count < 150 and f.format is 'pdf'
# there was likely a pdf file reading failure due to bad PDF formatting
f.same_paper_evidence.words_count = 0
f.archivable_reason = 'We could not find any text in the provided PDF. It is possible the PDF is a scan in which case text is only contained within images which we do not yet extract. Or, the PDF may have errors in it\'s structure which stops us being able to machine-read it'
f.version_evidence = score: 0, strings_checked: 0, strings_matched: []
try
# dev https://docs.google.com/spreadsheets/d/PI:KEY:<KEY>END_PI/edit#gid=0
# live https://docs.google.com/spreadsheets/d/PI:KEY:<KEY>END_PI/edit#gid=0
for l in API.use.google.sheets.feed (if API.settings.dev then 'PI:KEY:<KEY>END_PI' else 'PI:KEY:<KEY>END_PI')
try
f.version_evidence.strings_checked += 1
wts = l.whattosearch
if wts.indexOf('<<') isnt -1 and wts.indexOf('>>') isnt -1
wtm = wts.split('<<')[1].split('>>')[0]
wts = wts.replace('<<'+wtm+'>>',meta[wtm.toLowerCase()]) if meta[wtm.toLowerCase()]?
matched = false
if l.howtosearch is 'string'
#wtsc = _clean wts
#matched = if (l.wheretosearch is 'file' and _clean(lowercontentsmall).indexOf(wtsc) isnt -1) or (l.wheretosearch isnt 'file' and ((meta.title? and _clean(meta.title).indexOf(wtsc) isnt -1) or (f.name? and _clean(f.name).indexOf(wtsc) isnt -1))) then true else false
matched = if (l.wheretosearch is 'file' and contentsmall.indexOf(wts) isnt -1) or (l.wheretosearch isnt 'file' and ((meta.title? and meta.title.indexOf(wts) isnt -1) or (f.name? and f.name.indexOf(wts) isnt -1))) then true else false
else
# could change this to be explicit and not use lowercasing, if wanting more exactness
re = new RegExp wts, 'gium'
matched = if (l.wheretosearch is 'file' and lowercontentsmall.match(re) isnt null) or (l.wheretosearch isnt 'file' and ((meta.title? and meta.title.match(re) isnt null) or (f.name? and f.name.match(re) isnt null))) then true else false
if matched
sc = l.score ? l.score_value
if typeof sc is 'string'
try sc = parseInt sc
sc = 1 if typeof sc isnt 'number'
if l.whatitindicates is 'publisher pdf' then f.version_evidence.score += sc else f.version_evidence.score -= sc
f.version_evidence.strings_matched.push {indicates: l.whatitindicates, found: l.howtosearch + ' ' + wts, in: l.wheretosearch, score_value: sc}
f.version = 'publishedVersion' if f.version_evidence.score > 0
f.version = 'acceptedVersion' if f.version_evidence.score < 0
if f.version is 'unknown' and f.version_evidence.strings_checked > 0 #and f.format? and f.format isnt 'pdf'
f.version = 'acceptedVersion'
try
ls = API.service.lantern.licence undefined, undefined, lowercontentsmall # check lantern for licence info in the file content
if ls?.licence?
f.licence = ls.licence
f.licence_evidence = {string_match: ls.match}
f.lantern = ls
f.archivable = false
if confirmed
f.archivable = true
if confirmed is f.checksum
f.archivable_reason = 'The administrator has confirmed that this file is a version that can be archived.'
f.admin_confirms = true
else
f.archivable_reason = 'The depositor says that this file is a version that can be archived'
f.depositor_says = true
else if f.same_paper
if f.format isnt 'pdf'
f.archivable = true
f.archivable_reason = 'Since the file is not a PDF, we assume it is a Postprint.'
if not f.archivable and f.licence? and f.licence.toLowerCase().indexOf('cc') is 0
f.archivable = true
f.archivable_reason = 'It appears this file contains a ' + f.lantern.licence + ' licence statement. Under this licence the article can be archived'
if not f.archivable
if f.version is 'publishedVersion'
f.archivable_reason = 'The file given is a Publisher PDF, and only postprints are allowed'
else
f.archivable_reason = 'We cannot confirm if it is an archivable version or not'
else
f.archivable_reason ?= if not f.same_paper_evidence.words_more_than_threshold then 'The file is less than 500 words, and so does not appear to be a full article' else if not f.same_paper_evidence.document_format then 'File is an unexpected format ' + f.format else if not meta.doi and not meta.title then 'We have insufficient metadata to validate file is for the correct paper ' else 'File does not contain expected metadata such as DOI or title'
return f
API.service.oab.permission.test = (email) ->
res = {tests: 0, same: 0, results: {}}
for test in ts = API.use.google.sheets.feed '1vPI:KEY:<KEY>END_PI', 0
break if res.tests > 2
if test.doi and test.doi.startsWith('10.') and test.responseurl
console.log res.tests
res.tests += 1
res.results[test.doi] = {}
try
perms = API.service.oab.permission(doi: test.doi.split('?')[0], ror: (if test.doi.indexOf('?') isnt -1 then test.doi.split('?')[1].split('=')[1] else undefined)).best_permission
catch
perms = {}
try
ricks = HTTP.call('GET', test.responseurl).data.authoritative_permission.application
catch
ricks = {}
if perms? and ricks?
diffs = {}
for k in ['can_archive']
if not perms[k]? or not ricks[k]? or perms[k] isnt ricks[k]
diffs[k] = [perms[k],ricks[k]]
if _.isEmpty diffs
res.same += 1
res.results[test.doi].same = true
else
res.results[test.doi].same = false
res.results[test.doi].diffs = diffs
res.results[test.doi].perms = perms
res.results[test.doi].ricks = ricks
API.mail.send
service: 'openaccessbutton'
from: 'PI:EMAIL:<EMAIL>END_PI'
to: email ? 'PI:EMAIL:<EMAIL>END_PI'
subject: 'OAB permissions test complete'
text: JSON.stringify res, '', 2
return res |
[
{
"context": "ername: config.customer.username\n password: config.customer.password\n body: @objToXml params.trx\n headers:\n ",
"end": 1490,
"score": 0.9992234110832214,
"start": 1466,
"tag": "PASSWORD",
"value": "config.customer.password"
},
{
"context": " else\n ... | src/genesis/request.coffee | Pogix3m/genesis.js | 0 | _ = require 'underscore'
fs = require 'fs'
path = require 'path'
util = require 'util'
config = require 'config'
js2xml = require 'js2xmlparser'
request = require 'request'
Response = require './response'
Promise = require 'bluebird'
class Request
constructor: ->
@response = new Response
###
Format and return the endpoint URL based on the transaction parameters
###
formatUrl: (params) ->
prefix = if config.gateway.testing then 'staging.' else new String
if params.token
util.format '%s://%s%s.%s/%s/%s'
, config.gateway.protocol
, prefix
, params.app
, config.gateway.hostname
, params.path
, params.token
else
util.format '%s://%s%s.%s/%s'
, config.gateway.protocol
, prefix
, params.app
, config.gateway.hostname
, params.path
###
Convert Object to XML structure
###
objToXml: (structure) ->
rootNode = _.first _.keys(structure)
js2xml rootNode, structure[rootNode]
###
Send the transaction to the Gateway
###
send: (params) ->
args =
agentOptions:
# Explicitly state that we want to perform
# certificate verification
rejectUnauthorized: true
# Force TLS1.2 as the only supported method.
#
# Note: Update if necessary
secureProtocol: 'TLSv1_2_method'
auth:
username: config.customer.username
password: config.customer.password
body: @objToXml params.trx
headers:
'Content-Type': 'text/xml',
'User-Agent': 'Genesis Node.js client v' + config.module.version
strictSSL: true
timeout: Number(config.gateway.timeout)
url: @formatUrl params.url
new Promise(
((resolve, reject) ->
request.post args, ((error, httpResponse, responseBody) ->
if error
reject responseBody || error
else
respObj = @response.process httpResponse
if respObj.status in ['declined', 'error']
reject respObj
else
resolve respObj
).bind(@)
).bind(@)
)
module.exports = Request
| 5511 | _ = require 'underscore'
fs = require 'fs'
path = require 'path'
util = require 'util'
config = require 'config'
js2xml = require 'js2xmlparser'
request = require 'request'
Response = require './response'
Promise = require 'bluebird'
class Request
constructor: ->
@response = new Response
###
Format and return the endpoint URL based on the transaction parameters
###
formatUrl: (params) ->
prefix = if config.gateway.testing then 'staging.' else new String
if params.token
util.format '%s://%s%s.%s/%s/%s'
, config.gateway.protocol
, prefix
, params.app
, config.gateway.hostname
, params.path
, params.token
else
util.format '%s://%s%s.%s/%s'
, config.gateway.protocol
, prefix
, params.app
, config.gateway.hostname
, params.path
###
Convert Object to XML structure
###
objToXml: (structure) ->
rootNode = _.first _.keys(structure)
js2xml rootNode, structure[rootNode]
###
Send the transaction to the Gateway
###
send: (params) ->
args =
agentOptions:
# Explicitly state that we want to perform
# certificate verification
rejectUnauthorized: true
# Force TLS1.2 as the only supported method.
#
# Note: Update if necessary
secureProtocol: 'TLSv1_2_method'
auth:
username: config.customer.username
password: <PASSWORD>
body: @objToXml params.trx
headers:
'Content-Type': 'text/xml',
'User-Agent': 'Genesis Node.js client v' + config.module.version
strictSSL: true
timeout: Number(config.gateway.timeout)
url: @formatUrl params.url
new Promise(
((resolve, reject) ->
request.post args, ((error, httpResponse, responseBody) ->
if error
reject responseBody || error
else
respObj = @response.process httpResponse
if respObj.status in ['declined', 'error']
reject respObj
else
resolve respObj
).bind(@)
).bind(@)
)
module.exports = Request
| true | _ = require 'underscore'
fs = require 'fs'
path = require 'path'
util = require 'util'
config = require 'config'
js2xml = require 'js2xmlparser'
request = require 'request'
Response = require './response'
Promise = require 'bluebird'
class Request
constructor: ->
@response = new Response
###
Format and return the endpoint URL based on the transaction parameters
###
formatUrl: (params) ->
prefix = if config.gateway.testing then 'staging.' else new String
if params.token
util.format '%s://%s%s.%s/%s/%s'
, config.gateway.protocol
, prefix
, params.app
, config.gateway.hostname
, params.path
, params.token
else
util.format '%s://%s%s.%s/%s'
, config.gateway.protocol
, prefix
, params.app
, config.gateway.hostname
, params.path
###
Convert Object to XML structure
###
objToXml: (structure) ->
rootNode = _.first _.keys(structure)
js2xml rootNode, structure[rootNode]
###
Send the transaction to the Gateway
###
send: (params) ->
args =
agentOptions:
# Explicitly state that we want to perform
# certificate verification
rejectUnauthorized: true
# Force TLS1.2 as the only supported method.
#
# Note: Update if necessary
secureProtocol: 'TLSv1_2_method'
auth:
username: config.customer.username
password: PI:PASSWORD:<PASSWORD>END_PI
body: @objToXml params.trx
headers:
'Content-Type': 'text/xml',
'User-Agent': 'Genesis Node.js client v' + config.module.version
strictSSL: true
timeout: Number(config.gateway.timeout)
url: @formatUrl params.url
new Promise(
((resolve, reject) ->
request.post args, ((error, httpResponse, responseBody) ->
if error
reject responseBody || error
else
respObj = @response.process httpResponse
if respObj.status in ['declined', 'error']
reject respObj
else
resolve respObj
).bind(@)
).bind(@)
)
module.exports = Request
|
[
{
"context": "# (c) 2013-2017 Flowhub UG\n# (c) 2011-2012 Henri Bergius, Nemein\n# NoFlo may be freely distributed und",
"end": 116,
"score": 0.9998551607131958,
"start": 103,
"tag": "NAME",
"value": "Henri Bergius"
},
{
"context": "2017 Flowhub UG\n# (c) 2011-2012 He... | src/lib/Component.coffee | rrothenb/noflo | 0 | # NoFlo - Flow-Based Programming for JavaScript
# (c) 2013-2017 Flowhub UG
# (c) 2011-2012 Henri Bergius, Nemein
# NoFlo may be freely distributed under the MIT license
{EventEmitter} = require 'events'
ports = require './Ports'
IP = require './IP'
debug = require('debug') 'noflo:component'
debugBrackets = require('debug') 'noflo:component:brackets'
debugSend = require('debug') 'noflo:component:send'
# ## NoFlo Component Base class
#
# The `noflo.Component` interface provides a way to instantiate
# and extend NoFlo components.
class Component extends EventEmitter
description: ''
icon: null
constructor: (options) ->
super()
options = {} unless options
# Prepare inports, if any were given in options.
# They can also be set up imperatively after component
# instantiation by using the `component.inPorts.add`
# method.
options.inPorts = {} unless options.inPorts
if options.inPorts instanceof ports.InPorts
@inPorts = options.inPorts
else
@inPorts = new ports.InPorts options.inPorts
# Prepare outports, if any were given in options.
# They can also be set up imperatively after component
# instantiation by using the `component.outPorts.add`
# method.
options.outPorts = {} unless options.outPorts
if options.outPorts instanceof ports.OutPorts
@outPorts = options.outPorts
else
@outPorts = new ports.OutPorts options.outPorts
# Set the default component icon and description
@icon = options.icon if options.icon
@description = options.description if options.description
# Initially the component is not started
@started = false
@load = 0
# Whether the component should keep send packets
# out in the order they were received
@ordered = options.ordered ? false
@autoOrdering = options.autoOrdering ? null
# Queue for handling ordered output packets
@outputQ = []
# Context used for bracket forwarding
@bracketContext =
in: {}
out: {}
# Whether the component should activate when it
# receives packets
@activateOnInput = options.activateOnInput ? true
# Bracket forwarding rules. By default we forward
# brackets from `in` port to `out` and `error` ports.
@forwardBrackets = in: ['out', 'error']
if 'forwardBrackets' of options
@forwardBrackets = options.forwardBrackets
# The component's process function can either be
# passed in options, or given imperatively after
# instantation using the `component.process` method.
if typeof options.process is 'function'
@process options.process
getDescription: -> @description
isReady: -> true
isSubgraph: -> false
setIcon: (@icon) ->
@emit 'icon', @icon
getIcon: -> @icon
# ### Error emitting helper
#
# If component has an `error` outport that is connected, errors
# are sent as IP objects there. If the port is not connected,
# errors are thrown.
error: (e, groups = [], errorPort = 'error', scope = null) =>
if @outPorts[errorPort] and (@outPorts[errorPort].isAttached() or not @outPorts[errorPort].isRequired())
@outPorts[errorPort].openBracket group, scope: scope for group in groups
@outPorts[errorPort].data e, scope: scope
@outPorts[errorPort].closeBracket group, scope: scope for group in groups
return
throw e
# ### Setup
#
# The setUp method is for component-specific initialization.
# Called at network start-up.
#
# Override in component implementation to do component-specific
# setup work.
setUp: (callback) ->
do callback
return
# ### Setup
#
# The tearDown method is for component-specific cleanup. Called
# at network shutdown
#
# Override in component implementation to do component-specific
# cleanup work, like clearing any accumulated state.
tearDown: (callback) ->
do callback
return
# ### Start
#
# Called when network starts. This sets calls the setUp
# method and sets the component to a started state.
start: (callback) ->
return callback() if @isStarted()
@setUp (err) =>
return callback err if err
@started = true
@emit 'start'
callback null
return
return
# ### Shutdown
#
# Called when network is shut down. This sets calls the
# tearDown method and sets the component back to a
# non-started state.
#
# The callback is called when tearDown finishes and
# all active processing contexts have ended.
shutdown: (callback) ->
finalize = =>
# Clear contents of inport buffers
inPorts = @inPorts.ports or @inPorts
for portName, inPort of inPorts
continue unless typeof inPort.clear is 'function'
inPort.clear()
# Clear bracket context
@bracketContext =
in: {}
out: {}
return callback() unless @isStarted()
@started = false
@emit 'end'
callback()
return
# Tell the component that it is time to shut down
@tearDown (err) =>
return callback err if err
if @load > 0
# Some in-flight processes, wait for them to finish
checkLoad = (load) ->
return if load > 0
@removeListener 'deactivate', checkLoad
finalize()
return
@on 'deactivate', checkLoad
return
finalize()
return
return
isStarted: -> @started
# Ensures braket forwarding map is correct for the existing ports
prepareForwarding: ->
for inPort, outPorts of @forwardBrackets
unless inPort of @inPorts.ports
delete @forwardBrackets[inPort]
continue
tmp = []
for outPort in outPorts
tmp.push outPort if outPort of @outPorts.ports
if tmp.length is 0
delete @forwardBrackets[inPort]
else
@forwardBrackets[inPort] = tmp
# Method for determining if a component is using the modern
# NoFlo Process API
isLegacy: ->
# Process API
return false if @handle
# Legacy
true
# Sets process handler function
process: (handle) ->
unless typeof handle is 'function'
throw new Error "Process handler must be a function"
unless @inPorts
throw new Error "Component ports must be defined before process function"
@prepareForwarding()
@handle = handle
for name, port of @inPorts.ports
do (name, port) =>
port.name = name unless port.name
port.on 'ip', (ip) =>
@handleIP ip, port
@
# Method for checking if a given inport is set up for
# automatic bracket forwarding
isForwardingInport: (port) ->
if typeof port is 'string'
portName = port
else
portName = port.name
if portName of @forwardBrackets
return true
false
# Method for checking if a given outport is set up for
# automatic bracket forwarding
isForwardingOutport: (inport, outport) ->
if typeof inport is 'string'
inportName = inport
else
inportName = inport.name
if typeof outport is 'string'
outportName = outport
else
outportName = outport.name
return false unless @forwardBrackets[inportName]
return true if @forwardBrackets[inportName].indexOf(outportName) isnt -1
false
# Method for checking whether the component sends packets
# in the same order they were received.
isOrdered: ->
return true if @ordered
return true if @autoOrdering
false
# ### Handling IP objects
#
# The component has received an Information Packet. Call the
# processing function so that firing pattern preconditions can
# be checked and component can do processing as needed.
handleIP: (ip, port) ->
unless port.options.triggering
# If port is non-triggering, we can skip the process function call
return
if ip.type is 'openBracket' and @autoOrdering is null and not @ordered
# Switch component to ordered mode when receiving a stream unless
# auto-ordering is disabled
debug "#{@nodeId} port '#{port.name}' entered auto-ordering mode"
@autoOrdering = true
# Initialize the result object for situations where output needs
# to be queued to be kept in order
result = {}
if @isForwardingInport port
# For bracket-forwarding inports we need to initialize a bracket context
# so that brackets can be sent as part of the output, and closed after.
if ip.type is 'openBracket'
# For forwarding ports openBrackets don't fire
return
if ip.type is 'closeBracket'
# For forwarding ports closeBrackets don't fire
# However, we need to handle several different scenarios:
# A. There are closeBrackets in queue before current packet
# B. There are closeBrackets in queue after current packet
# C. We've queued the results from all in-flight processes and
# new closeBracket arrives
buf = port.getBuffer ip.scope, ip.index
dataPackets = buf.filter (ip) -> ip.type is 'data'
if @outputQ.length >= @load and dataPackets.length is 0
return unless buf[0] is ip
# Remove from buffer
port.get ip.scope, ip.index
context = @getBracketContext('in', port.name, ip.scope, ip.index).pop()
context.closeIp = ip
debugBrackets "#{@nodeId} closeBracket-C from '#{context.source}' to #{context.ports}: '#{ip.data}'"
result =
__resolved: true
__bracketClosingAfter: [context]
@outputQ.push result
do @processOutputQueue
# Check if buffer contains data IPs. If it does, we want to allow
# firing
return unless dataPackets.length
# Prepare the input/output pair
context = new ProcessContext ip, @, port, result
input = new ProcessInput @inPorts, context
output = new ProcessOutput @outPorts, context
try
# Call the processing function
@handle input, output, context
catch e
@deactivate context
output.sendDone e
return if context.activated
# If receiving an IP object didn't cause the component to
# activate, log that input conditions were not met
if port.isAddressable()
debug "#{@nodeId} packet on '#{port.name}[#{ip.index}]' didn't match preconditions: #{ip.type}"
return
debug "#{@nodeId} packet on '#{port.name}' didn't match preconditions: #{ip.type}"
return
# Get the current bracket forwarding context for an IP object
getBracketContext: (type, port, scope, idx) ->
{name, index} = ports.normalizePortName port
index = idx if idx?
portsList = if type is 'in' then @inPorts else @outPorts
if portsList[name].isAddressable()
port = "#{name}[#{index}]"
# Ensure we have a bracket context for the current scope
@bracketContext[type][port] = {} unless @bracketContext[type][port]
@bracketContext[type][port][scope] = [] unless @bracketContext[type][port][scope]
return @bracketContext[type][port][scope]
# Add an IP object to the list of results to be sent in
# order
addToResult: (result, port, ip, before = false) ->
{name, index} = ports.normalizePortName port
method = if before then 'unshift' else 'push'
if @outPorts[name].isAddressable()
idx = if index then parseInt(index) else ip.index
result[name] = {} unless result[name]
result[name][idx] = [] unless result[name][idx]
ip.index = idx
result[name][idx][method] ip
return
result[name] = [] unless result[name]
result[name][method] ip
# Get contexts that can be forwarded with this in/outport
# pair.
getForwardableContexts: (inport, outport, contexts) ->
{name, index} = ports.normalizePortName outport
forwardable = []
contexts.forEach (ctx, idx) =>
# No forwarding to this outport
return unless @isForwardingOutport inport, name
# We have already forwarded this context to this outport
return unless ctx.ports.indexOf(outport) is -1
# See if we have already forwarded the same bracket from another
# inport
outContext = @getBracketContext('out', name, ctx.ip.scope, index)[idx]
if outContext
return if outContext.ip.data is ctx.ip.data and outContext.ports.indexOf(outport) isnt -1
forwardable.push ctx
return forwardable
# Add any bracket forwards needed to the result queue
addBracketForwards: (result) ->
if result.__bracketClosingBefore?.length
for context in result.__bracketClosingBefore
debugBrackets "#{@nodeId} closeBracket-A from '#{context.source}' to #{context.ports}: '#{context.closeIp.data}'"
continue unless context.ports.length
for port in context.ports
ipClone = context.closeIp.clone()
@addToResult result, port, ipClone, true
@getBracketContext('out', port, ipClone.scope).pop()
if result.__bracketContext
# First see if there are any brackets to forward. We need to reverse
# the keys so that they get added in correct order
Object.keys(result.__bracketContext).reverse().forEach (inport) =>
context = result.__bracketContext[inport]
return unless context.length
for outport, ips of result
continue if outport.indexOf('__') is 0
if @outPorts[outport].isAddressable()
for idx, idxIps of ips
# Don't register indexes we're only sending brackets to
datas = idxIps.filter (ip) -> ip.type is 'data'
continue unless datas.length
portIdentifier = "#{outport}[#{idx}]"
unforwarded = @getForwardableContexts inport, portIdentifier, context
continue unless unforwarded.length
forwardedOpens = []
for ctx in unforwarded
debugBrackets "#{@nodeId} openBracket from '#{inport}' to '#{portIdentifier}': '#{ctx.ip.data}'"
ipClone = ctx.ip.clone()
ipClone.index = parseInt idx
forwardedOpens.push ipClone
ctx.ports.push portIdentifier
@getBracketContext('out', outport, ctx.ip.scope, idx).push ctx
forwardedOpens.reverse()
@addToResult result, outport, ip, true for ip in forwardedOpens
continue
# Don't register ports we're only sending brackets to
datas = ips.filter (ip) -> ip.type is 'data'
continue unless datas.length
unforwarded = @getForwardableContexts inport, outport, context
continue unless unforwarded.length
forwardedOpens = []
for ctx in unforwarded
debugBrackets "#{@nodeId} openBracket from '#{inport}' to '#{outport}': '#{ctx.ip.data}'"
forwardedOpens.push ctx.ip.clone()
ctx.ports.push outport
@getBracketContext('out', outport, ctx.ip.scope).push ctx
forwardedOpens.reverse()
@addToResult result, outport, ip, true for ip in forwardedOpens
if result.__bracketClosingAfter?.length
for context in result.__bracketClosingAfter
debugBrackets "#{@nodeId} closeBracket-B from '#{context.source}' to #{context.ports}: '#{context.closeIp.data}'"
continue unless context.ports.length
for port in context.ports
ipClone = context.closeIp.clone()
@addToResult result, port, ipClone, false
@getBracketContext('out', port, ipClone.scope).pop()
delete result.__bracketClosingBefore
delete result.__bracketContext
delete result.__bracketClosingAfter
# Whenever an execution context finishes, send all resolved
# output from the queue in the order it is in.
processOutputQueue: ->
while @outputQ.length > 0
break unless @outputQ[0].__resolved
result = @outputQ.shift()
@addBracketForwards result
for port, ips of result
continue if port.indexOf('__') is 0
if @outPorts.ports[port].isAddressable()
for idx, idxIps of ips
idx = parseInt idx
continue unless @outPorts.ports[port].isAttached idx
for ip in idxIps
portIdentifier = "#{port}[#{ip.index}]"
if ip.type is 'openBracket'
debugSend "#{@nodeId} sending #{portIdentifier} < '#{ip.data}'"
else if ip.type is 'closeBracket'
debugSend "#{@nodeId} sending #{portIdentifier} > '#{ip.data}'"
else
debugSend "#{@nodeId} sending #{portIdentifier} DATA"
unless @outPorts[port].options.scoped
ip.scope = null
@outPorts[port].sendIP ip
continue
continue unless @outPorts.ports[port].isAttached()
for ip in ips
portIdentifier = port
if ip.type is 'openBracket'
debugSend "#{@nodeId} sending #{portIdentifier} < '#{ip.data}'"
else if ip.type is 'closeBracket'
debugSend "#{@nodeId} sending #{portIdentifier} > '#{ip.data}'"
else
debugSend "#{@nodeId} sending #{portIdentifier} DATA"
unless @outPorts[port].options.scoped
ip.scope = null
@outPorts[port].sendIP ip
# Signal that component has activated. There may be multiple
# activated contexts at the same time
activate: (context) ->
return if context.activated # prevent double activation
context.activated = true
context.deactivated = false
@load++
@emit 'activate', @load
if @ordered or @autoOrdering
@outputQ.push context.result
# Signal that component has deactivated. There may be multiple
# activated contexts at the same time
deactivate: (context) ->
return if context.deactivated # prevent double deactivation
context.deactivated = true
context.activated = false
if @isOrdered()
@processOutputQueue()
@load--
@emit 'deactivate', @load
class ProcessContext
constructor: (@ip, @nodeInstance, @port, @result) ->
@scope = @ip.scope
@activated = false
@deactivated = false
activate: ->
# Push a new result value if previous has been sent already
if @result.__resolved or @nodeInstance.outputQ.indexOf(@result) is -1
@result = {}
@nodeInstance.activate @
deactivate: ->
@result.__resolved = true unless @result.__resolved
@nodeInstance.deactivate @
class ProcessInput
constructor: (@ports, @context) ->
@nodeInstance = @context.nodeInstance
@ip = @context.ip
@port = @context.port
@result = @context.result
@scope = @context.scope
# When preconditions are met, set component state to `activated`
activate: ->
return if @context.activated
if @nodeInstance.isOrdered()
# We're handling packets in order. Set the result as non-resolved
# so that it can be send when the order comes up
@result.__resolved = false
@nodeInstance.activate @context
if @port.isAddressable()
debug "#{@nodeInstance.nodeId} packet on '#{@port.name}[#{@ip.index}]' caused activation #{@nodeInstance.load}: #{@ip.type}"
else
debug "#{@nodeInstance.nodeId} packet on '#{@port.name}' caused activation #{@nodeInstance.load}: #{@ip.type}"
# ## Connection listing
# This allows components to check which input ports are attached. This is
# useful mainly for addressable ports
attached: (args...) ->
args = ['in'] unless args.length
res = []
for port in args
unless @ports[port]
throw new Error "Node #{@nodeInstance.nodeId} has no port '#{port}'"
res.push @ports[port].listAttached()
return res.pop() if args.length is 1
res
# ## Input preconditions
# When the processing function is called, it can check if input buffers
# contain the packets needed for the process to fire.
# This precondition handling is done via the `has` and `hasStream` methods.
# Returns true if a port (or ports joined by logical AND) has a new IP
# Passing a validation callback as a last argument allows more selective
# checking of packets.
has: (args...) ->
args = ['in'] unless args.length
if typeof args[args.length - 1] is 'function'
validate = args.pop()
else
validate = -> true
for port in args
if Array.isArray port
unless @ports[port[0]]
throw new Error "Node #{@nodeInstance.nodeId} has no port '#{port[0]}'"
unless @ports[port[0]].isAddressable()
throw new Error "Non-addressable ports, access must be with string #{port[0]}"
return false unless @ports[port[0]].has @scope, port[1], validate
continue
unless @ports[port]
throw new Error "Node #{@nodeInstance.nodeId} has no port '#{port}'"
if @ports[port].isAddressable()
throw new Error "For addressable ports, access must be with array [#{port}, idx]"
return false unless @ports[port].has @scope, validate
return true
# Returns true if the ports contain data packets
hasData: (args...) ->
args = ['in'] unless args.length
args.push (ip) -> ip.type is 'data'
return @has.apply @, args
# Returns true if a port has a complete stream in its input buffer.
hasStream: (args...) ->
args = ['in'] unless args.length
if typeof args[args.length - 1] is 'function'
validateStream = args.pop()
else
validateStream = -> true
for port in args
portBrackets = []
dataBrackets = []
hasData = false
validate = (ip) ->
if ip.type is 'openBracket'
portBrackets.push ip.data
return false
if ip.type is 'data'
# Run the stream validation callback
hasData = validateStream ip, portBrackets
# Data IP on its own is a valid stream
return hasData unless portBrackets.length
# Otherwise we need to check for complete stream
return false
if ip.type is 'closeBracket'
portBrackets.pop()
return false if portBrackets.length
return false unless hasData
return true
return false unless @has port, validate
true
# ## Input processing
#
# Once preconditions have been met, the processing function can read from
# the input buffers. Reading packets sets the component as "activated".
#
# Fetches IP object(s) for port(s)
get: (args...) ->
@activate()
args = ['in'] unless args.length
res = []
for port in args
if Array.isArray port
[portname, idx] = port
unless @ports[portname].isAddressable()
throw new Error 'Non-addressable ports, access must be with string portname'
else
portname = port
if @ports[portname].isAddressable()
throw new Error 'For addressable ports, access must be with array [portname, idx]'
if @nodeInstance.isForwardingInport portname
ip = @__getForForwarding portname, idx
res.push ip
continue
ip = @ports[portname].get @scope, idx
res.push ip
if args.length is 1 then res[0] else res
__getForForwarding: (port, idx) ->
prefix = []
dataIp = null
# Read IPs until we hit data
loop
# Read next packet
ip = @ports[port].get @scope, idx
# Stop at the end of the buffer
break unless ip
if ip.type is 'data'
# Hit the data IP, stop here
dataIp = ip
break
# Keep track of bracket closings and openings before
prefix.push ip
# Forwarding brackets that came before data packet need to manipulate context
# and be added to result so they can be forwarded correctly to ports that
# need them
for ip in prefix
if ip.type is 'closeBracket'
# Bracket closings before data should remove bracket context
@result.__bracketClosingBefore = [] unless @result.__bracketClosingBefore
context = @nodeInstance.getBracketContext('in', port, @scope, idx).pop()
context.closeIp = ip
@result.__bracketClosingBefore.push context
continue
if ip.type is 'openBracket'
# Bracket openings need to go to bracket context
@nodeInstance.getBracketContext('in', port, @scope, idx).push
ip: ip
ports: []
source: port
continue
# Add current bracket context to the result so that when we send
# to ports we can also add the surrounding brackets
@result.__bracketContext = {} unless @result.__bracketContext
@result.__bracketContext[port] = @nodeInstance.getBracketContext('in', port, @scope, idx).slice 0
# Bracket closings that were in buffer after the data packet need to
# be added to result for done() to read them from
return dataIp
# Fetches `data` property of IP object(s) for given port(s)
getData: (args...) ->
args = ['in'] unless args.length
datas = []
for port in args
packet = @get port
unless packet?
# we add the null packet to the array so when getting
# multiple ports, if one is null we still return it
# so the indexes are correct.
datas.push packet
continue
until packet.type is 'data'
packet = @get port
break unless packet
datas.push packet.data
return datas.pop() if args.length is 1
datas
# Fetches a complete data stream from the buffer.
getStream: (args...) ->
args = ['in'] unless args.length
datas = []
for port in args
portBrackets = []
portPackets = []
hasData = false
ip = @get port
datas.push undefined unless ip
while ip
if ip.type is 'openBracket'
unless portBrackets.length
# First openBracket in stream, drop previous
portPackets = []
hasData = false
portBrackets.push ip.data
portPackets.push ip
if ip.type is 'data'
portPackets.push ip
hasData = true
# Unbracketed data packet is a valid stream
break unless portBrackets.length
if ip.type is 'closeBracket'
portPackets.push ip
portBrackets.pop()
if hasData and not portBrackets.length
# Last close bracket finishes stream if there was data inside
break
ip = @get port
datas.push portPackets
return datas.pop() if args.length is 1
datas
class ProcessOutput
constructor: (@ports, @context) ->
@nodeInstance = @context.nodeInstance
@ip = @context.ip
@result = @context.result
@scope = @context.scope
# Checks if a value is an Error
isError: (err) ->
err instanceof Error or
Array.isArray(err) and err.length > 0 and err[0] instanceof Error
# Sends an error object
error: (err) ->
multiple = Array.isArray err
err = [err] unless multiple
if 'error' of @ports and
(@ports.error.isAttached() or not @ports.error.isRequired())
@sendIP 'error', new IP 'openBracket' if multiple
@sendIP 'error', e for e in err
@sendIP 'error', new IP 'closeBracket' if multiple
else
throw e for e in err
# Sends a single IP object to a port
sendIP: (port, packet) ->
unless IP.isIP packet
ip = new IP 'data', packet
else
ip = packet
ip.scope = @scope if @scope isnt null and ip.scope is null
if @nodeInstance.outPorts[port].isAddressable() and ip.index is null
throw new Error 'Sending packets to addressable ports requires specifying index'
if @nodeInstance.isOrdered()
@nodeInstance.addToResult @result, port, ip
return
unless @nodeInstance.outPorts[port].options.scoped
ip.scope = null
@nodeInstance.outPorts[port].sendIP ip
# Sends packets for each port as a key in the map
# or sends Error or a list of Errors if passed such
send: (outputMap) ->
return @error outputMap if @isError outputMap
componentPorts = []
mapIsInPorts = false
for port in Object.keys @ports.ports
componentPorts.push port if port isnt 'error' and port isnt 'ports' and port isnt '_callbacks'
if not mapIsInPorts and outputMap? and typeof outputMap is 'object' and Object.keys(outputMap).indexOf(port) isnt -1
mapIsInPorts = true
if componentPorts.length is 1 and not mapIsInPorts
@sendIP componentPorts[0], outputMap
return
if componentPorts.length > 1 and not mapIsInPorts
throw new Error 'Port must be specified for sending output'
for port, packet of outputMap
@sendIP port, packet
# Sends the argument via `send()` and marks activation as `done()`
sendDone: (outputMap) ->
@send outputMap
@done()
# Makes a map-style component pass a result value to `out`
# keeping all IP metadata received from `in`,
# or modifying it if `options` is provided
pass: (data, options = {}) ->
unless 'out' of @ports
throw new Error 'output.pass() requires port "out" to be present'
for key, val of options
@ip[key] = val
@ip.data = data
@sendIP 'out', @ip
@done()
# Finishes process activation gracefully
done: (error) ->
@result.__resolved = true
@nodeInstance.activate @context
@error error if error
isLast = =>
# We only care about real output sets with processing data
resultsOnly = @nodeInstance.outputQ.filter (q) ->
return true unless q.__resolved
if Object.keys(q).length is 2 and q.__bracketClosingAfter
return false
true
pos = resultsOnly.indexOf @result
len = resultsOnly.length
load = @nodeInstance.load
return true if pos is len - 1
return true if pos is -1 and load is len + 1
return true if len <= 1 and load is 1
false
if @nodeInstance.isOrdered() and isLast()
# We're doing bracket forwarding. See if there are
# dangling closeBrackets in buffer since we're the
# last running process function.
for port, contexts of @nodeInstance.bracketContext.in
continue unless contexts[@scope]
nodeContext = contexts[@scope]
continue unless nodeContext.length
context = nodeContext[nodeContext.length - 1]
buf = @nodeInstance.inPorts[context.source].getBuffer context.ip.scope, context.ip.index
loop
break unless buf.length
break unless buf[0].type is 'closeBracket'
ip = @nodeInstance.inPorts[context.source].get context.ip.scope, context.ip.index
ctx = nodeContext.pop()
ctx.closeIp = ip
@result.__bracketClosingAfter = [] unless @result.__bracketClosingAfter
@result.__bracketClosingAfter.push ctx
debug "#{@nodeInstance.nodeId} finished processing #{@nodeInstance.load}"
@nodeInstance.deactivate @context
exports.Component = Component
| 150093 | # NoFlo - Flow-Based Programming for JavaScript
# (c) 2013-2017 Flowhub UG
# (c) 2011-2012 <NAME>, <NAME>
# NoFlo may be freely distributed under the MIT license
{EventEmitter} = require 'events'
ports = require './Ports'
IP = require './IP'
debug = require('debug') 'noflo:component'
debugBrackets = require('debug') 'noflo:component:brackets'
debugSend = require('debug') 'noflo:component:send'
# ## NoFlo Component Base class
#
# The `noflo.Component` interface provides a way to instantiate
# and extend NoFlo components.
class Component extends EventEmitter
description: ''
icon: null
constructor: (options) ->
super()
options = {} unless options
# Prepare inports, if any were given in options.
# They can also be set up imperatively after component
# instantiation by using the `component.inPorts.add`
# method.
options.inPorts = {} unless options.inPorts
if options.inPorts instanceof ports.InPorts
@inPorts = options.inPorts
else
@inPorts = new ports.InPorts options.inPorts
# Prepare outports, if any were given in options.
# They can also be set up imperatively after component
# instantiation by using the `component.outPorts.add`
# method.
options.outPorts = {} unless options.outPorts
if options.outPorts instanceof ports.OutPorts
@outPorts = options.outPorts
else
@outPorts = new ports.OutPorts options.outPorts
# Set the default component icon and description
@icon = options.icon if options.icon
@description = options.description if options.description
# Initially the component is not started
@started = false
@load = 0
# Whether the component should keep send packets
# out in the order they were received
@ordered = options.ordered ? false
@autoOrdering = options.autoOrdering ? null
# Queue for handling ordered output packets
@outputQ = []
# Context used for bracket forwarding
@bracketContext =
in: {}
out: {}
# Whether the component should activate when it
# receives packets
@activateOnInput = options.activateOnInput ? true
# Bracket forwarding rules. By default we forward
# brackets from `in` port to `out` and `error` ports.
@forwardBrackets = in: ['out', 'error']
if 'forwardBrackets' of options
@forwardBrackets = options.forwardBrackets
# The component's process function can either be
# passed in options, or given imperatively after
# instantation using the `component.process` method.
if typeof options.process is 'function'
@process options.process
getDescription: -> @description
isReady: -> true
isSubgraph: -> false
setIcon: (@icon) ->
@emit 'icon', @icon
getIcon: -> @icon
# ### Error emitting helper
#
# If component has an `error` outport that is connected, errors
# are sent as IP objects there. If the port is not connected,
# errors are thrown.
error: (e, groups = [], errorPort = 'error', scope = null) =>
if @outPorts[errorPort] and (@outPorts[errorPort].isAttached() or not @outPorts[errorPort].isRequired())
@outPorts[errorPort].openBracket group, scope: scope for group in groups
@outPorts[errorPort].data e, scope: scope
@outPorts[errorPort].closeBracket group, scope: scope for group in groups
return
throw e
# ### Setup
#
# The setUp method is for component-specific initialization.
# Called at network start-up.
#
# Override in component implementation to do component-specific
# setup work.
setUp: (callback) ->
do callback
return
# ### Setup
#
# The tearDown method is for component-specific cleanup. Called
# at network shutdown
#
# Override in component implementation to do component-specific
# cleanup work, like clearing any accumulated state.
tearDown: (callback) ->
do callback
return
# ### Start
#
# Called when network starts. This sets calls the setUp
# method and sets the component to a started state.
start: (callback) ->
return callback() if @isStarted()
@setUp (err) =>
return callback err if err
@started = true
@emit 'start'
callback null
return
return
# ### Shutdown
#
# Called when network is shut down. This sets calls the
# tearDown method and sets the component back to a
# non-started state.
#
# The callback is called when tearDown finishes and
# all active processing contexts have ended.
shutdown: (callback) ->
finalize = =>
# Clear contents of inport buffers
inPorts = @inPorts.ports or @inPorts
for portName, inPort of inPorts
continue unless typeof inPort.clear is 'function'
inPort.clear()
# Clear bracket context
@bracketContext =
in: {}
out: {}
return callback() unless @isStarted()
@started = false
@emit 'end'
callback()
return
# Tell the component that it is time to shut down
@tearDown (err) =>
return callback err if err
if @load > 0
# Some in-flight processes, wait for them to finish
checkLoad = (load) ->
return if load > 0
@removeListener 'deactivate', checkLoad
finalize()
return
@on 'deactivate', checkLoad
return
finalize()
return
return
isStarted: -> @started
# Ensures braket forwarding map is correct for the existing ports
prepareForwarding: ->
for inPort, outPorts of @forwardBrackets
unless inPort of @inPorts.ports
delete @forwardBrackets[inPort]
continue
tmp = []
for outPort in outPorts
tmp.push outPort if outPort of @outPorts.ports
if tmp.length is 0
delete @forwardBrackets[inPort]
else
@forwardBrackets[inPort] = tmp
# Method for determining if a component is using the modern
# NoFlo Process API
isLegacy: ->
# Process API
return false if @handle
# Legacy
true
# Sets process handler function
process: (handle) ->
unless typeof handle is 'function'
throw new Error "Process handler must be a function"
unless @inPorts
throw new Error "Component ports must be defined before process function"
@prepareForwarding()
@handle = handle
for name, port of @inPorts.ports
do (name, port) =>
port.name = name unless port.name
port.on 'ip', (ip) =>
@handleIP ip, port
@
# Method for checking if a given inport is set up for
# automatic bracket forwarding
isForwardingInport: (port) ->
if typeof port is 'string'
portName = port
else
portName = port.name
if portName of @forwardBrackets
return true
false
# Method for checking if a given outport is set up for
# automatic bracket forwarding
isForwardingOutport: (inport, outport) ->
if typeof inport is 'string'
inportName = inport
else
inportName = inport.name
if typeof outport is 'string'
outportName = outport
else
outportName = outport.name
return false unless @forwardBrackets[inportName]
return true if @forwardBrackets[inportName].indexOf(outportName) isnt -1
false
# Method for checking whether the component sends packets
# in the same order they were received.
isOrdered: ->
return true if @ordered
return true if @autoOrdering
false
# ### Handling IP objects
#
# The component has received an Information Packet. Call the
# processing function so that firing pattern preconditions can
# be checked and component can do processing as needed.
handleIP: (ip, port) ->
unless port.options.triggering
# If port is non-triggering, we can skip the process function call
return
if ip.type is 'openBracket' and @autoOrdering is null and not @ordered
# Switch component to ordered mode when receiving a stream unless
# auto-ordering is disabled
debug "#{@nodeId} port '#{port.name}' entered auto-ordering mode"
@autoOrdering = true
# Initialize the result object for situations where output needs
# to be queued to be kept in order
result = {}
if @isForwardingInport port
# For bracket-forwarding inports we need to initialize a bracket context
# so that brackets can be sent as part of the output, and closed after.
if ip.type is 'openBracket'
# For forwarding ports openBrackets don't fire
return
if ip.type is 'closeBracket'
# For forwarding ports closeBrackets don't fire
# However, we need to handle several different scenarios:
# A. There are closeBrackets in queue before current packet
# B. There are closeBrackets in queue after current packet
# C. We've queued the results from all in-flight processes and
# new closeBracket arrives
buf = port.getBuffer ip.scope, ip.index
dataPackets = buf.filter (ip) -> ip.type is 'data'
if @outputQ.length >= @load and dataPackets.length is 0
return unless buf[0] is ip
# Remove from buffer
port.get ip.scope, ip.index
context = @getBracketContext('in', port.name, ip.scope, ip.index).pop()
context.closeIp = ip
debugBrackets "#{@nodeId} closeBracket-C from '#{context.source}' to #{context.ports}: '#{ip.data}'"
result =
__resolved: true
__bracketClosingAfter: [context]
@outputQ.push result
do @processOutputQueue
# Check if buffer contains data IPs. If it does, we want to allow
# firing
return unless dataPackets.length
# Prepare the input/output pair
context = new ProcessContext ip, @, port, result
input = new ProcessInput @inPorts, context
output = new ProcessOutput @outPorts, context
try
# Call the processing function
@handle input, output, context
catch e
@deactivate context
output.sendDone e
return if context.activated
# If receiving an IP object didn't cause the component to
# activate, log that input conditions were not met
if port.isAddressable()
debug "#{@nodeId} packet on '#{port.name}[#{ip.index}]' didn't match preconditions: #{ip.type}"
return
debug "#{@nodeId} packet on '#{port.name}' didn't match preconditions: #{ip.type}"
return
# Get the current bracket forwarding context for an IP object
getBracketContext: (type, port, scope, idx) ->
{name, index} = ports.normalizePortName port
index = idx if idx?
portsList = if type is 'in' then @inPorts else @outPorts
if portsList[name].isAddressable()
port = "#{name}[#{index}]"
# Ensure we have a bracket context for the current scope
@bracketContext[type][port] = {} unless @bracketContext[type][port]
@bracketContext[type][port][scope] = [] unless @bracketContext[type][port][scope]
return @bracketContext[type][port][scope]
# Add an IP object to the list of results to be sent in
# order
addToResult: (result, port, ip, before = false) ->
{name, index} = ports.normalizePortName port
method = if before then 'unshift' else 'push'
if @outPorts[name].isAddressable()
idx = if index then parseInt(index) else ip.index
result[name] = {} unless result[name]
result[name][idx] = [] unless result[name][idx]
ip.index = idx
result[name][idx][method] ip
return
result[name] = [] unless result[name]
result[name][method] ip
# Get contexts that can be forwarded with this in/outport
# pair.
getForwardableContexts: (inport, outport, contexts) ->
{name, index} = ports.normalizePortName outport
forwardable = []
contexts.forEach (ctx, idx) =>
# No forwarding to this outport
return unless @isForwardingOutport inport, name
# We have already forwarded this context to this outport
return unless ctx.ports.indexOf(outport) is -1
# See if we have already forwarded the same bracket from another
# inport
outContext = @getBracketContext('out', name, ctx.ip.scope, index)[idx]
if outContext
return if outContext.ip.data is ctx.ip.data and outContext.ports.indexOf(outport) isnt -1
forwardable.push ctx
return forwardable
# Add any bracket forwards needed to the result queue
addBracketForwards: (result) ->
if result.__bracketClosingBefore?.length
for context in result.__bracketClosingBefore
debugBrackets "#{@nodeId} closeBracket-A from '#{context.source}' to #{context.ports}: '#{context.closeIp.data}'"
continue unless context.ports.length
for port in context.ports
ipClone = context.closeIp.clone()
@addToResult result, port, ipClone, true
@getBracketContext('out', port, ipClone.scope).pop()
if result.__bracketContext
# First see if there are any brackets to forward. We need to reverse
# the keys so that they get added in correct order
Object.keys(result.__bracketContext).reverse().forEach (inport) =>
context = result.__bracketContext[inport]
return unless context.length
for outport, ips of result
continue if outport.indexOf('__') is 0
if @outPorts[outport].isAddressable()
for idx, idxIps of ips
# Don't register indexes we're only sending brackets to
datas = idxIps.filter (ip) -> ip.type is 'data'
continue unless datas.length
portIdentifier = "#{outport}[#{idx}]"
unforwarded = @getForwardableContexts inport, portIdentifier, context
continue unless unforwarded.length
forwardedOpens = []
for ctx in unforwarded
debugBrackets "#{@nodeId} openBracket from '#{inport}' to '#{portIdentifier}': '#{ctx.ip.data}'"
ipClone = ctx.ip.clone()
ipClone.index = parseInt idx
forwardedOpens.push ipClone
ctx.ports.push portIdentifier
@getBracketContext('out', outport, ctx.ip.scope, idx).push ctx
forwardedOpens.reverse()
@addToResult result, outport, ip, true for ip in forwardedOpens
continue
# Don't register ports we're only sending brackets to
datas = ips.filter (ip) -> ip.type is 'data'
continue unless datas.length
unforwarded = @getForwardableContexts inport, outport, context
continue unless unforwarded.length
forwardedOpens = []
for ctx in unforwarded
debugBrackets "#{@nodeId} openBracket from '#{inport}' to '#{outport}': '#{ctx.ip.data}'"
forwardedOpens.push ctx.ip.clone()
ctx.ports.push outport
@getBracketContext('out', outport, ctx.ip.scope).push ctx
forwardedOpens.reverse()
@addToResult result, outport, ip, true for ip in forwardedOpens
if result.__bracketClosingAfter?.length
for context in result.__bracketClosingAfter
debugBrackets "#{@nodeId} closeBracket-B from '#{context.source}' to #{context.ports}: '#{context.closeIp.data}'"
continue unless context.ports.length
for port in context.ports
ipClone = context.closeIp.clone()
@addToResult result, port, ipClone, false
@getBracketContext('out', port, ipClone.scope).pop()
delete result.__bracketClosingBefore
delete result.__bracketContext
delete result.__bracketClosingAfter
# Whenever an execution context finishes, send all resolved
# output from the queue in the order it is in.
processOutputQueue: ->
while @outputQ.length > 0
break unless @outputQ[0].__resolved
result = @outputQ.shift()
@addBracketForwards result
for port, ips of result
continue if port.indexOf('__') is 0
if @outPorts.ports[port].isAddressable()
for idx, idxIps of ips
idx = parseInt idx
continue unless @outPorts.ports[port].isAttached idx
for ip in idxIps
portIdentifier = "#{port}[#{ip.index}]"
if ip.type is 'openBracket'
debugSend "#{@nodeId} sending #{portIdentifier} < '#{ip.data}'"
else if ip.type is 'closeBracket'
debugSend "#{@nodeId} sending #{portIdentifier} > '#{ip.data}'"
else
debugSend "#{@nodeId} sending #{portIdentifier} DATA"
unless @outPorts[port].options.scoped
ip.scope = null
@outPorts[port].sendIP ip
continue
continue unless @outPorts.ports[port].isAttached()
for ip in ips
portIdentifier = port
if ip.type is 'openBracket'
debugSend "#{@nodeId} sending #{portIdentifier} < '#{ip.data}'"
else if ip.type is 'closeBracket'
debugSend "#{@nodeId} sending #{portIdentifier} > '#{ip.data}'"
else
debugSend "#{@nodeId} sending #{portIdentifier} DATA"
unless @outPorts[port].options.scoped
ip.scope = null
@outPorts[port].sendIP ip
# Signal that component has activated. There may be multiple
# activated contexts at the same time
activate: (context) ->
return if context.activated # prevent double activation
context.activated = true
context.deactivated = false
@load++
@emit 'activate', @load
if @ordered or @autoOrdering
@outputQ.push context.result
# Signal that component has deactivated. There may be multiple
# activated contexts at the same time
deactivate: (context) ->
return if context.deactivated # prevent double deactivation
context.deactivated = true
context.activated = false
if @isOrdered()
@processOutputQueue()
@load--
@emit 'deactivate', @load
class ProcessContext
constructor: (@ip, @nodeInstance, @port, @result) ->
@scope = @ip.scope
@activated = false
@deactivated = false
activate: ->
# Push a new result value if previous has been sent already
if @result.__resolved or @nodeInstance.outputQ.indexOf(@result) is -1
@result = {}
@nodeInstance.activate @
deactivate: ->
@result.__resolved = true unless @result.__resolved
@nodeInstance.deactivate @
class ProcessInput
constructor: (@ports, @context) ->
@nodeInstance = @context.nodeInstance
@ip = @context.ip
@port = @context.port
@result = @context.result
@scope = @context.scope
# When preconditions are met, set component state to `activated`
activate: ->
return if @context.activated
if @nodeInstance.isOrdered()
# We're handling packets in order. Set the result as non-resolved
# so that it can be send when the order comes up
@result.__resolved = false
@nodeInstance.activate @context
if @port.isAddressable()
debug "#{@nodeInstance.nodeId} packet on '#{@port.name}[#{@ip.index}]' caused activation #{@nodeInstance.load}: #{@ip.type}"
else
debug "#{@nodeInstance.nodeId} packet on '#{@port.name}' caused activation #{@nodeInstance.load}: #{@ip.type}"
# ## Connection listing
# This allows components to check which input ports are attached. This is
# useful mainly for addressable ports
attached: (args...) ->
args = ['in'] unless args.length
res = []
for port in args
unless @ports[port]
throw new Error "Node #{@nodeInstance.nodeId} has no port '#{port}'"
res.push @ports[port].listAttached()
return res.pop() if args.length is 1
res
# ## Input preconditions
# When the processing function is called, it can check if input buffers
# contain the packets needed for the process to fire.
# This precondition handling is done via the `has` and `hasStream` methods.
# Returns true if a port (or ports joined by logical AND) has a new IP
# Passing a validation callback as a last argument allows more selective
# checking of packets.
has: (args...) ->
args = ['in'] unless args.length
if typeof args[args.length - 1] is 'function'
validate = args.pop()
else
validate = -> true
for port in args
if Array.isArray port
unless @ports[port[0]]
throw new Error "Node #{@nodeInstance.nodeId} has no port '#{port[0]}'"
unless @ports[port[0]].isAddressable()
throw new Error "Non-addressable ports, access must be with string #{port[0]}"
return false unless @ports[port[0]].has @scope, port[1], validate
continue
unless @ports[port]
throw new Error "Node #{@nodeInstance.nodeId} has no port '#{port}'"
if @ports[port].isAddressable()
throw new Error "For addressable ports, access must be with array [#{port}, idx]"
return false unless @ports[port].has @scope, validate
return true
# Returns true if the ports contain data packets
hasData: (args...) ->
args = ['in'] unless args.length
args.push (ip) -> ip.type is 'data'
return @has.apply @, args
# Returns true if a port has a complete stream in its input buffer.
hasStream: (args...) ->
args = ['in'] unless args.length
if typeof args[args.length - 1] is 'function'
validateStream = args.pop()
else
validateStream = -> true
for port in args
portBrackets = []
dataBrackets = []
hasData = false
validate = (ip) ->
if ip.type is 'openBracket'
portBrackets.push ip.data
return false
if ip.type is 'data'
# Run the stream validation callback
hasData = validateStream ip, portBrackets
# Data IP on its own is a valid stream
return hasData unless portBrackets.length
# Otherwise we need to check for complete stream
return false
if ip.type is 'closeBracket'
portBrackets.pop()
return false if portBrackets.length
return false unless hasData
return true
return false unless @has port, validate
true
# ## Input processing
#
# Once preconditions have been met, the processing function can read from
# the input buffers. Reading packets sets the component as "activated".
#
# Fetches IP object(s) for port(s)
get: (args...) ->
@activate()
args = ['in'] unless args.length
res = []
for port in args
if Array.isArray port
[portname, idx] = port
unless @ports[portname].isAddressable()
throw new Error 'Non-addressable ports, access must be with string portname'
else
portname = port
if @ports[portname].isAddressable()
throw new Error 'For addressable ports, access must be with array [portname, idx]'
if @nodeInstance.isForwardingInport portname
ip = @__getForForwarding portname, idx
res.push ip
continue
ip = @ports[portname].get @scope, idx
res.push ip
if args.length is 1 then res[0] else res
__getForForwarding: (port, idx) ->
prefix = []
dataIp = null
# Read IPs until we hit data
loop
# Read next packet
ip = @ports[port].get @scope, idx
# Stop at the end of the buffer
break unless ip
if ip.type is 'data'
# Hit the data IP, stop here
dataIp = ip
break
# Keep track of bracket closings and openings before
prefix.push ip
# Forwarding brackets that came before data packet need to manipulate context
# and be added to result so they can be forwarded correctly to ports that
# need them
for ip in prefix
if ip.type is 'closeBracket'
# Bracket closings before data should remove bracket context
@result.__bracketClosingBefore = [] unless @result.__bracketClosingBefore
context = @nodeInstance.getBracketContext('in', port, @scope, idx).pop()
context.closeIp = ip
@result.__bracketClosingBefore.push context
continue
if ip.type is 'openBracket'
# Bracket openings need to go to bracket context
@nodeInstance.getBracketContext('in', port, @scope, idx).push
ip: ip
ports: []
source: port
continue
# Add current bracket context to the result so that when we send
# to ports we can also add the surrounding brackets
@result.__bracketContext = {} unless @result.__bracketContext
@result.__bracketContext[port] = @nodeInstance.getBracketContext('in', port, @scope, idx).slice 0
# Bracket closings that were in buffer after the data packet need to
# be added to result for done() to read them from
return dataIp
# Fetches `data` property of IP object(s) for given port(s)
getData: (args...) ->
args = ['in'] unless args.length
datas = []
for port in args
packet = @get port
unless packet?
# we add the null packet to the array so when getting
# multiple ports, if one is null we still return it
# so the indexes are correct.
datas.push packet
continue
until packet.type is 'data'
packet = @get port
break unless packet
datas.push packet.data
return datas.pop() if args.length is 1
datas
# Fetches a complete data stream from the buffer.
getStream: (args...) ->
args = ['in'] unless args.length
datas = []
for port in args
portBrackets = []
portPackets = []
hasData = false
ip = @get port
datas.push undefined unless ip
while ip
if ip.type is 'openBracket'
unless portBrackets.length
# First openBracket in stream, drop previous
portPackets = []
hasData = false
portBrackets.push ip.data
portPackets.push ip
if ip.type is 'data'
portPackets.push ip
hasData = true
# Unbracketed data packet is a valid stream
break unless portBrackets.length
if ip.type is 'closeBracket'
portPackets.push ip
portBrackets.pop()
if hasData and not portBrackets.length
# Last close bracket finishes stream if there was data inside
break
ip = @get port
datas.push portPackets
return datas.pop() if args.length is 1
datas
class ProcessOutput
constructor: (@ports, @context) ->
@nodeInstance = @context.nodeInstance
@ip = @context.ip
@result = @context.result
@scope = @context.scope
# Checks if a value is an Error
isError: (err) ->
err instanceof Error or
Array.isArray(err) and err.length > 0 and err[0] instanceof Error
# Sends an error object
error: (err) ->
multiple = Array.isArray err
err = [err] unless multiple
if 'error' of @ports and
(@ports.error.isAttached() or not @ports.error.isRequired())
@sendIP 'error', new IP 'openBracket' if multiple
@sendIP 'error', e for e in err
@sendIP 'error', new IP 'closeBracket' if multiple
else
throw e for e in err
# Sends a single IP object to a port
sendIP: (port, packet) ->
unless IP.isIP packet
ip = new IP 'data', packet
else
ip = packet
ip.scope = @scope if @scope isnt null and ip.scope is null
if @nodeInstance.outPorts[port].isAddressable() and ip.index is null
throw new Error 'Sending packets to addressable ports requires specifying index'
if @nodeInstance.isOrdered()
@nodeInstance.addToResult @result, port, ip
return
unless @nodeInstance.outPorts[port].options.scoped
ip.scope = null
@nodeInstance.outPorts[port].sendIP ip
# Sends packets for each port as a key in the map
# or sends Error or a list of Errors if passed such
send: (outputMap) ->
return @error outputMap if @isError outputMap
componentPorts = []
mapIsInPorts = false
for port in Object.keys @ports.ports
componentPorts.push port if port isnt 'error' and port isnt 'ports' and port isnt '_callbacks'
if not mapIsInPorts and outputMap? and typeof outputMap is 'object' and Object.keys(outputMap).indexOf(port) isnt -1
mapIsInPorts = true
if componentPorts.length is 1 and not mapIsInPorts
@sendIP componentPorts[0], outputMap
return
if componentPorts.length > 1 and not mapIsInPorts
throw new Error 'Port must be specified for sending output'
for port, packet of outputMap
@sendIP port, packet
# Sends the argument via `send()` and marks activation as `done()`
sendDone: (outputMap) ->
@send outputMap
@done()
# Makes a map-style component pass a result value to `out`
# keeping all IP metadata received from `in`,
# or modifying it if `options` is provided
pass: (data, options = {}) ->
unless 'out' of @ports
throw new Error 'output.pass() requires port "out" to be present'
for key, val of options
@ip[key] = val
@ip.data = data
@sendIP 'out', @ip
@done()
# Finishes process activation gracefully
done: (error) ->
@result.__resolved = true
@nodeInstance.activate @context
@error error if error
isLast = =>
# We only care about real output sets with processing data
resultsOnly = @nodeInstance.outputQ.filter (q) ->
return true unless q.__resolved
if Object.keys(q).length is 2 and q.__bracketClosingAfter
return false
true
pos = resultsOnly.indexOf @result
len = resultsOnly.length
load = @nodeInstance.load
return true if pos is len - 1
return true if pos is -1 and load is len + 1
return true if len <= 1 and load is 1
false
if @nodeInstance.isOrdered() and isLast()
# We're doing bracket forwarding. See if there are
# dangling closeBrackets in buffer since we're the
# last running process function.
for port, contexts of @nodeInstance.bracketContext.in
continue unless contexts[@scope]
nodeContext = contexts[@scope]
continue unless nodeContext.length
context = nodeContext[nodeContext.length - 1]
buf = @nodeInstance.inPorts[context.source].getBuffer context.ip.scope, context.ip.index
loop
break unless buf.length
break unless buf[0].type is 'closeBracket'
ip = @nodeInstance.inPorts[context.source].get context.ip.scope, context.ip.index
ctx = nodeContext.pop()
ctx.closeIp = ip
@result.__bracketClosingAfter = [] unless @result.__bracketClosingAfter
@result.__bracketClosingAfter.push ctx
debug "#{@nodeInstance.nodeId} finished processing #{@nodeInstance.load}"
@nodeInstance.deactivate @context
exports.Component = Component
| true | # NoFlo - Flow-Based Programming for JavaScript
# (c) 2013-2017 Flowhub UG
# (c) 2011-2012 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
# NoFlo may be freely distributed under the MIT license
{EventEmitter} = require 'events'
ports = require './Ports'
IP = require './IP'
debug = require('debug') 'noflo:component'
debugBrackets = require('debug') 'noflo:component:brackets'
debugSend = require('debug') 'noflo:component:send'
# ## NoFlo Component Base class
#
# The `noflo.Component` interface provides a way to instantiate
# and extend NoFlo components.
class Component extends EventEmitter
description: ''
icon: null
constructor: (options) ->
super()
options = {} unless options
# Prepare inports, if any were given in options.
# They can also be set up imperatively after component
# instantiation by using the `component.inPorts.add`
# method.
options.inPorts = {} unless options.inPorts
if options.inPorts instanceof ports.InPorts
@inPorts = options.inPorts
else
@inPorts = new ports.InPorts options.inPorts
# Prepare outports, if any were given in options.
# They can also be set up imperatively after component
# instantiation by using the `component.outPorts.add`
# method.
options.outPorts = {} unless options.outPorts
if options.outPorts instanceof ports.OutPorts
@outPorts = options.outPorts
else
@outPorts = new ports.OutPorts options.outPorts
# Set the default component icon and description
@icon = options.icon if options.icon
@description = options.description if options.description
# Initially the component is not started
@started = false
@load = 0
# Whether the component should keep send packets
# out in the order they were received
@ordered = options.ordered ? false
@autoOrdering = options.autoOrdering ? null
# Queue for handling ordered output packets
@outputQ = []
# Context used for bracket forwarding
@bracketContext =
in: {}
out: {}
# Whether the component should activate when it
# receives packets
@activateOnInput = options.activateOnInput ? true
# Bracket forwarding rules. By default we forward
# brackets from `in` port to `out` and `error` ports.
@forwardBrackets = in: ['out', 'error']
if 'forwardBrackets' of options
@forwardBrackets = options.forwardBrackets
# The component's process function can either be
# passed in options, or given imperatively after
# instantation using the `component.process` method.
if typeof options.process is 'function'
@process options.process
getDescription: -> @description
isReady: -> true
isSubgraph: -> false
setIcon: (@icon) ->
@emit 'icon', @icon
getIcon: -> @icon
# ### Error emitting helper
#
# If component has an `error` outport that is connected, errors
# are sent as IP objects there. If the port is not connected,
# errors are thrown.
error: (e, groups = [], errorPort = 'error', scope = null) =>
if @outPorts[errorPort] and (@outPorts[errorPort].isAttached() or not @outPorts[errorPort].isRequired())
@outPorts[errorPort].openBracket group, scope: scope for group in groups
@outPorts[errorPort].data e, scope: scope
@outPorts[errorPort].closeBracket group, scope: scope for group in groups
return
throw e
# ### Setup
#
# The setUp method is for component-specific initialization.
# Called at network start-up.
#
# Override in component implementation to do component-specific
# setup work.
setUp: (callback) ->
do callback
return
# ### Setup
#
# The tearDown method is for component-specific cleanup. Called
# at network shutdown
#
# Override in component implementation to do component-specific
# cleanup work, like clearing any accumulated state.
tearDown: (callback) ->
do callback
return
# ### Start
#
# Called when network starts. This sets calls the setUp
# method and sets the component to a started state.
start: (callback) ->
return callback() if @isStarted()
@setUp (err) =>
return callback err if err
@started = true
@emit 'start'
callback null
return
return
# ### Shutdown
#
# Called when network is shut down. This sets calls the
# tearDown method and sets the component back to a
# non-started state.
#
# The callback is called when tearDown finishes and
# all active processing contexts have ended.
shutdown: (callback) ->
finalize = =>
# Clear contents of inport buffers
inPorts = @inPorts.ports or @inPorts
for portName, inPort of inPorts
continue unless typeof inPort.clear is 'function'
inPort.clear()
# Clear bracket context
@bracketContext =
in: {}
out: {}
return callback() unless @isStarted()
@started = false
@emit 'end'
callback()
return
# Tell the component that it is time to shut down
@tearDown (err) =>
return callback err if err
if @load > 0
# Some in-flight processes, wait for them to finish
checkLoad = (load) ->
return if load > 0
@removeListener 'deactivate', checkLoad
finalize()
return
@on 'deactivate', checkLoad
return
finalize()
return
return
isStarted: -> @started
# Ensures braket forwarding map is correct for the existing ports
prepareForwarding: ->
for inPort, outPorts of @forwardBrackets
unless inPort of @inPorts.ports
delete @forwardBrackets[inPort]
continue
tmp = []
for outPort in outPorts
tmp.push outPort if outPort of @outPorts.ports
if tmp.length is 0
delete @forwardBrackets[inPort]
else
@forwardBrackets[inPort] = tmp
# Method for determining if a component is using the modern
# NoFlo Process API
isLegacy: ->
# Process API
return false if @handle
# Legacy
true
# Sets process handler function
process: (handle) ->
unless typeof handle is 'function'
throw new Error "Process handler must be a function"
unless @inPorts
throw new Error "Component ports must be defined before process function"
@prepareForwarding()
@handle = handle
for name, port of @inPorts.ports
do (name, port) =>
port.name = name unless port.name
port.on 'ip', (ip) =>
@handleIP ip, port
@
# Method for checking if a given inport is set up for
# automatic bracket forwarding
isForwardingInport: (port) ->
if typeof port is 'string'
portName = port
else
portName = port.name
if portName of @forwardBrackets
return true
false
# Method for checking if a given outport is set up for
# automatic bracket forwarding
isForwardingOutport: (inport, outport) ->
if typeof inport is 'string'
inportName = inport
else
inportName = inport.name
if typeof outport is 'string'
outportName = outport
else
outportName = outport.name
return false unless @forwardBrackets[inportName]
return true if @forwardBrackets[inportName].indexOf(outportName) isnt -1
false
# Method for checking whether the component sends packets
# in the same order they were received.
isOrdered: ->
return true if @ordered
return true if @autoOrdering
false
# ### Handling IP objects
#
# The component has received an Information Packet. Call the
# processing function so that firing pattern preconditions can
# be checked and component can do processing as needed.
handleIP: (ip, port) ->
unless port.options.triggering
# If port is non-triggering, we can skip the process function call
return
if ip.type is 'openBracket' and @autoOrdering is null and not @ordered
# Switch component to ordered mode when receiving a stream unless
# auto-ordering is disabled
debug "#{@nodeId} port '#{port.name}' entered auto-ordering mode"
@autoOrdering = true
# Initialize the result object for situations where output needs
# to be queued to be kept in order
result = {}
if @isForwardingInport port
# For bracket-forwarding inports we need to initialize a bracket context
# so that brackets can be sent as part of the output, and closed after.
if ip.type is 'openBracket'
# For forwarding ports openBrackets don't fire
return
if ip.type is 'closeBracket'
# For forwarding ports closeBrackets don't fire
# However, we need to handle several different scenarios:
# A. There are closeBrackets in queue before current packet
# B. There are closeBrackets in queue after current packet
# C. We've queued the results from all in-flight processes and
# new closeBracket arrives
buf = port.getBuffer ip.scope, ip.index
dataPackets = buf.filter (ip) -> ip.type is 'data'
if @outputQ.length >= @load and dataPackets.length is 0
return unless buf[0] is ip
# Remove from buffer
port.get ip.scope, ip.index
context = @getBracketContext('in', port.name, ip.scope, ip.index).pop()
context.closeIp = ip
debugBrackets "#{@nodeId} closeBracket-C from '#{context.source}' to #{context.ports}: '#{ip.data}'"
result =
__resolved: true
__bracketClosingAfter: [context]
@outputQ.push result
do @processOutputQueue
# Check if buffer contains data IPs. If it does, we want to allow
# firing
return unless dataPackets.length
# Prepare the input/output pair
context = new ProcessContext ip, @, port, result
input = new ProcessInput @inPorts, context
output = new ProcessOutput @outPorts, context
try
# Call the processing function
@handle input, output, context
catch e
@deactivate context
output.sendDone e
return if context.activated
# If receiving an IP object didn't cause the component to
# activate, log that input conditions were not met
if port.isAddressable()
debug "#{@nodeId} packet on '#{port.name}[#{ip.index}]' didn't match preconditions: #{ip.type}"
return
debug "#{@nodeId} packet on '#{port.name}' didn't match preconditions: #{ip.type}"
return
# Get the current bracket forwarding context for an IP object
getBracketContext: (type, port, scope, idx) ->
{name, index} = ports.normalizePortName port
index = idx if idx?
portsList = if type is 'in' then @inPorts else @outPorts
if portsList[name].isAddressable()
port = "#{name}[#{index}]"
# Ensure we have a bracket context for the current scope
@bracketContext[type][port] = {} unless @bracketContext[type][port]
@bracketContext[type][port][scope] = [] unless @bracketContext[type][port][scope]
return @bracketContext[type][port][scope]
# Add an IP object to the list of results to be sent in
# order
addToResult: (result, port, ip, before = false) ->
{name, index} = ports.normalizePortName port
method = if before then 'unshift' else 'push'
if @outPorts[name].isAddressable()
idx = if index then parseInt(index) else ip.index
result[name] = {} unless result[name]
result[name][idx] = [] unless result[name][idx]
ip.index = idx
result[name][idx][method] ip
return
result[name] = [] unless result[name]
result[name][method] ip
# Get contexts that can be forwarded with this in/outport
# pair.
getForwardableContexts: (inport, outport, contexts) ->
{name, index} = ports.normalizePortName outport
forwardable = []
contexts.forEach (ctx, idx) =>
# No forwarding to this outport
return unless @isForwardingOutport inport, name
# We have already forwarded this context to this outport
return unless ctx.ports.indexOf(outport) is -1
# See if we have already forwarded the same bracket from another
# inport
outContext = @getBracketContext('out', name, ctx.ip.scope, index)[idx]
if outContext
return if outContext.ip.data is ctx.ip.data and outContext.ports.indexOf(outport) isnt -1
forwardable.push ctx
return forwardable
# Add any bracket forwards needed to the result queue
addBracketForwards: (result) ->
if result.__bracketClosingBefore?.length
for context in result.__bracketClosingBefore
debugBrackets "#{@nodeId} closeBracket-A from '#{context.source}' to #{context.ports}: '#{context.closeIp.data}'"
continue unless context.ports.length
for port in context.ports
ipClone = context.closeIp.clone()
@addToResult result, port, ipClone, true
@getBracketContext('out', port, ipClone.scope).pop()
if result.__bracketContext
# First see if there are any brackets to forward. We need to reverse
# the keys so that they get added in correct order
Object.keys(result.__bracketContext).reverse().forEach (inport) =>
context = result.__bracketContext[inport]
return unless context.length
for outport, ips of result
continue if outport.indexOf('__') is 0
if @outPorts[outport].isAddressable()
for idx, idxIps of ips
# Don't register indexes we're only sending brackets to
datas = idxIps.filter (ip) -> ip.type is 'data'
continue unless datas.length
portIdentifier = "#{outport}[#{idx}]"
unforwarded = @getForwardableContexts inport, portIdentifier, context
continue unless unforwarded.length
forwardedOpens = []
for ctx in unforwarded
debugBrackets "#{@nodeId} openBracket from '#{inport}' to '#{portIdentifier}': '#{ctx.ip.data}'"
ipClone = ctx.ip.clone()
ipClone.index = parseInt idx
forwardedOpens.push ipClone
ctx.ports.push portIdentifier
@getBracketContext('out', outport, ctx.ip.scope, idx).push ctx
forwardedOpens.reverse()
@addToResult result, outport, ip, true for ip in forwardedOpens
continue
# Don't register ports we're only sending brackets to
datas = ips.filter (ip) -> ip.type is 'data'
continue unless datas.length
unforwarded = @getForwardableContexts inport, outport, context
continue unless unforwarded.length
forwardedOpens = []
for ctx in unforwarded
debugBrackets "#{@nodeId} openBracket from '#{inport}' to '#{outport}': '#{ctx.ip.data}'"
forwardedOpens.push ctx.ip.clone()
ctx.ports.push outport
@getBracketContext('out', outport, ctx.ip.scope).push ctx
forwardedOpens.reverse()
@addToResult result, outport, ip, true for ip in forwardedOpens
if result.__bracketClosingAfter?.length
for context in result.__bracketClosingAfter
debugBrackets "#{@nodeId} closeBracket-B from '#{context.source}' to #{context.ports}: '#{context.closeIp.data}'"
continue unless context.ports.length
for port in context.ports
ipClone = context.closeIp.clone()
@addToResult result, port, ipClone, false
@getBracketContext('out', port, ipClone.scope).pop()
delete result.__bracketClosingBefore
delete result.__bracketContext
delete result.__bracketClosingAfter
# Whenever an execution context finishes, send all resolved
# output from the queue in the order it is in.
processOutputQueue: ->
while @outputQ.length > 0
break unless @outputQ[0].__resolved
result = @outputQ.shift()
@addBracketForwards result
for port, ips of result
continue if port.indexOf('__') is 0
if @outPorts.ports[port].isAddressable()
for idx, idxIps of ips
idx = parseInt idx
continue unless @outPorts.ports[port].isAttached idx
for ip in idxIps
portIdentifier = "#{port}[#{ip.index}]"
if ip.type is 'openBracket'
debugSend "#{@nodeId} sending #{portIdentifier} < '#{ip.data}'"
else if ip.type is 'closeBracket'
debugSend "#{@nodeId} sending #{portIdentifier} > '#{ip.data}'"
else
debugSend "#{@nodeId} sending #{portIdentifier} DATA"
unless @outPorts[port].options.scoped
ip.scope = null
@outPorts[port].sendIP ip
continue
continue unless @outPorts.ports[port].isAttached()
for ip in ips
portIdentifier = port
if ip.type is 'openBracket'
debugSend "#{@nodeId} sending #{portIdentifier} < '#{ip.data}'"
else if ip.type is 'closeBracket'
debugSend "#{@nodeId} sending #{portIdentifier} > '#{ip.data}'"
else
debugSend "#{@nodeId} sending #{portIdentifier} DATA"
unless @outPorts[port].options.scoped
ip.scope = null
@outPorts[port].sendIP ip
# Signal that component has activated. There may be multiple
# activated contexts at the same time
activate: (context) ->
return if context.activated # prevent double activation
context.activated = true
context.deactivated = false
@load++
@emit 'activate', @load
if @ordered or @autoOrdering
@outputQ.push context.result
# Signal that component has deactivated. There may be multiple
# activated contexts at the same time
deactivate: (context) ->
return if context.deactivated # prevent double deactivation
context.deactivated = true
context.activated = false
if @isOrdered()
@processOutputQueue()
@load--
@emit 'deactivate', @load
class ProcessContext
constructor: (@ip, @nodeInstance, @port, @result) ->
@scope = @ip.scope
@activated = false
@deactivated = false
activate: ->
# Push a new result value if previous has been sent already
if @result.__resolved or @nodeInstance.outputQ.indexOf(@result) is -1
@result = {}
@nodeInstance.activate @
deactivate: ->
@result.__resolved = true unless @result.__resolved
@nodeInstance.deactivate @
class ProcessInput
constructor: (@ports, @context) ->
@nodeInstance = @context.nodeInstance
@ip = @context.ip
@port = @context.port
@result = @context.result
@scope = @context.scope
# When preconditions are met, set component state to `activated`
activate: ->
return if @context.activated
if @nodeInstance.isOrdered()
# We're handling packets in order. Set the result as non-resolved
# so that it can be send when the order comes up
@result.__resolved = false
@nodeInstance.activate @context
if @port.isAddressable()
debug "#{@nodeInstance.nodeId} packet on '#{@port.name}[#{@ip.index}]' caused activation #{@nodeInstance.load}: #{@ip.type}"
else
debug "#{@nodeInstance.nodeId} packet on '#{@port.name}' caused activation #{@nodeInstance.load}: #{@ip.type}"
# ## Connection listing
# This allows components to check which input ports are attached. This is
# useful mainly for addressable ports
attached: (args...) ->
args = ['in'] unless args.length
res = []
for port in args
unless @ports[port]
throw new Error "Node #{@nodeInstance.nodeId} has no port '#{port}'"
res.push @ports[port].listAttached()
return res.pop() if args.length is 1
res
# ## Input preconditions
# When the processing function is called, it can check if input buffers
# contain the packets needed for the process to fire.
# This precondition handling is done via the `has` and `hasStream` methods.
# Returns true if a port (or ports joined by logical AND) has a new IP
# Passing a validation callback as a last argument allows more selective
# checking of packets.
has: (args...) ->
args = ['in'] unless args.length
if typeof args[args.length - 1] is 'function'
validate = args.pop()
else
validate = -> true
for port in args
if Array.isArray port
unless @ports[port[0]]
throw new Error "Node #{@nodeInstance.nodeId} has no port '#{port[0]}'"
unless @ports[port[0]].isAddressable()
throw new Error "Non-addressable ports, access must be with string #{port[0]}"
return false unless @ports[port[0]].has @scope, port[1], validate
continue
unless @ports[port]
throw new Error "Node #{@nodeInstance.nodeId} has no port '#{port}'"
if @ports[port].isAddressable()
throw new Error "For addressable ports, access must be with array [#{port}, idx]"
return false unless @ports[port].has @scope, validate
return true
# Returns true if the ports contain data packets
hasData: (args...) ->
args = ['in'] unless args.length
args.push (ip) -> ip.type is 'data'
return @has.apply @, args
# Returns true if a port has a complete stream in its input buffer.
hasStream: (args...) ->
args = ['in'] unless args.length
if typeof args[args.length - 1] is 'function'
validateStream = args.pop()
else
validateStream = -> true
for port in args
portBrackets = []
dataBrackets = []
hasData = false
validate = (ip) ->
if ip.type is 'openBracket'
portBrackets.push ip.data
return false
if ip.type is 'data'
# Run the stream validation callback
hasData = validateStream ip, portBrackets
# Data IP on its own is a valid stream
return hasData unless portBrackets.length
# Otherwise we need to check for complete stream
return false
if ip.type is 'closeBracket'
portBrackets.pop()
return false if portBrackets.length
return false unless hasData
return true
return false unless @has port, validate
true
# ## Input processing
#
# Once preconditions have been met, the processing function can read from
# the input buffers. Reading packets sets the component as "activated".
#
# Fetches IP object(s) for port(s)
get: (args...) ->
@activate()
args = ['in'] unless args.length
res = []
for port in args
if Array.isArray port
[portname, idx] = port
unless @ports[portname].isAddressable()
throw new Error 'Non-addressable ports, access must be with string portname'
else
portname = port
if @ports[portname].isAddressable()
throw new Error 'For addressable ports, access must be with array [portname, idx]'
if @nodeInstance.isForwardingInport portname
ip = @__getForForwarding portname, idx
res.push ip
continue
ip = @ports[portname].get @scope, idx
res.push ip
if args.length is 1 then res[0] else res
__getForForwarding: (port, idx) ->
prefix = []
dataIp = null
# Read IPs until we hit data
loop
# Read next packet
ip = @ports[port].get @scope, idx
# Stop at the end of the buffer
break unless ip
if ip.type is 'data'
# Hit the data IP, stop here
dataIp = ip
break
# Keep track of bracket closings and openings before
prefix.push ip
# Forwarding brackets that came before data packet need to manipulate context
# and be added to result so they can be forwarded correctly to ports that
# need them
for ip in prefix
if ip.type is 'closeBracket'
# Bracket closings before data should remove bracket context
@result.__bracketClosingBefore = [] unless @result.__bracketClosingBefore
context = @nodeInstance.getBracketContext('in', port, @scope, idx).pop()
context.closeIp = ip
@result.__bracketClosingBefore.push context
continue
if ip.type is 'openBracket'
# Bracket openings need to go to bracket context
@nodeInstance.getBracketContext('in', port, @scope, idx).push
ip: ip
ports: []
source: port
continue
# Add current bracket context to the result so that when we send
# to ports we can also add the surrounding brackets
@result.__bracketContext = {} unless @result.__bracketContext
@result.__bracketContext[port] = @nodeInstance.getBracketContext('in', port, @scope, idx).slice 0
# Bracket closings that were in buffer after the data packet need to
# be added to result for done() to read them from
return dataIp
# Fetches `data` property of IP object(s) for given port(s)
getData: (args...) ->
args = ['in'] unless args.length
datas = []
for port in args
packet = @get port
unless packet?
# we add the null packet to the array so when getting
# multiple ports, if one is null we still return it
# so the indexes are correct.
datas.push packet
continue
until packet.type is 'data'
packet = @get port
break unless packet
datas.push packet.data
return datas.pop() if args.length is 1
datas
# Fetches a complete data stream from the buffer.
getStream: (args...) ->
args = ['in'] unless args.length
datas = []
for port in args
portBrackets = []
portPackets = []
hasData = false
ip = @get port
datas.push undefined unless ip
while ip
if ip.type is 'openBracket'
unless portBrackets.length
# First openBracket in stream, drop previous
portPackets = []
hasData = false
portBrackets.push ip.data
portPackets.push ip
if ip.type is 'data'
portPackets.push ip
hasData = true
# Unbracketed data packet is a valid stream
break unless portBrackets.length
if ip.type is 'closeBracket'
portPackets.push ip
portBrackets.pop()
if hasData and not portBrackets.length
# Last close bracket finishes stream if there was data inside
break
ip = @get port
datas.push portPackets
return datas.pop() if args.length is 1
datas
class ProcessOutput
constructor: (@ports, @context) ->
@nodeInstance = @context.nodeInstance
@ip = @context.ip
@result = @context.result
@scope = @context.scope
# Checks if a value is an Error
isError: (err) ->
err instanceof Error or
Array.isArray(err) and err.length > 0 and err[0] instanceof Error
# Sends an error object
error: (err) ->
multiple = Array.isArray err
err = [err] unless multiple
if 'error' of @ports and
(@ports.error.isAttached() or not @ports.error.isRequired())
@sendIP 'error', new IP 'openBracket' if multiple
@sendIP 'error', e for e in err
@sendIP 'error', new IP 'closeBracket' if multiple
else
throw e for e in err
# Sends a single IP object to a port
sendIP: (port, packet) ->
unless IP.isIP packet
ip = new IP 'data', packet
else
ip = packet
ip.scope = @scope if @scope isnt null and ip.scope is null
if @nodeInstance.outPorts[port].isAddressable() and ip.index is null
throw new Error 'Sending packets to addressable ports requires specifying index'
if @nodeInstance.isOrdered()
@nodeInstance.addToResult @result, port, ip
return
unless @nodeInstance.outPorts[port].options.scoped
ip.scope = null
@nodeInstance.outPorts[port].sendIP ip
# Sends packets for each port as a key in the map
# or sends Error or a list of Errors if passed such
send: (outputMap) ->
return @error outputMap if @isError outputMap
componentPorts = []
mapIsInPorts = false
for port in Object.keys @ports.ports
componentPorts.push port if port isnt 'error' and port isnt 'ports' and port isnt '_callbacks'
if not mapIsInPorts and outputMap? and typeof outputMap is 'object' and Object.keys(outputMap).indexOf(port) isnt -1
mapIsInPorts = true
if componentPorts.length is 1 and not mapIsInPorts
@sendIP componentPorts[0], outputMap
return
if componentPorts.length > 1 and not mapIsInPorts
throw new Error 'Port must be specified for sending output'
for port, packet of outputMap
@sendIP port, packet
# Sends the argument via `send()` and marks activation as `done()`
sendDone: (outputMap) ->
@send outputMap
@done()
# Makes a map-style component pass a result value to `out`
# keeping all IP metadata received from `in`,
# or modifying it if `options` is provided
pass: (data, options = {}) ->
unless 'out' of @ports
throw new Error 'output.pass() requires port "out" to be present'
for key, val of options
@ip[key] = val
@ip.data = data
@sendIP 'out', @ip
@done()
# Finishes process activation gracefully
done: (error) ->
@result.__resolved = true
@nodeInstance.activate @context
@error error if error
isLast = =>
# We only care about real output sets with processing data
resultsOnly = @nodeInstance.outputQ.filter (q) ->
return true unless q.__resolved
if Object.keys(q).length is 2 and q.__bracketClosingAfter
return false
true
pos = resultsOnly.indexOf @result
len = resultsOnly.length
load = @nodeInstance.load
return true if pos is len - 1
return true if pos is -1 and load is len + 1
return true if len <= 1 and load is 1
false
if @nodeInstance.isOrdered() and isLast()
# We're doing bracket forwarding. See if there are
# dangling closeBrackets in buffer since we're the
# last running process function.
for port, contexts of @nodeInstance.bracketContext.in
continue unless contexts[@scope]
nodeContext = contexts[@scope]
continue unless nodeContext.length
context = nodeContext[nodeContext.length - 1]
buf = @nodeInstance.inPorts[context.source].getBuffer context.ip.scope, context.ip.index
loop
break unless buf.length
break unless buf[0].type is 'closeBracket'
ip = @nodeInstance.inPorts[context.source].get context.ip.scope, context.ip.index
ctx = nodeContext.pop()
ctx.closeIp = ip
@result.__bracketClosingAfter = [] unless @result.__bracketClosingAfter
@result.__bracketClosingAfter.push ctx
debug "#{@nodeInstance.nodeId} finished processing #{@nodeInstance.load}"
@nodeInstance.deactivate @context
exports.Component = Component
|
[
{
"context": " [\n id: 'm_4',\n threadID: 't_2',\n threadName: 'Dave and Bill',\n authorName: 'Bill',\n text: 'Hey Dave, want t",
"end": 73,
"score": 0.9651613235473633,
"start": 60,
"tag": "NAME",
"value": "Dave and Bill"
},
{
"context": "2',\n threadName: 'Dave and Bill',\n ... | src/client/chat/message/message-directive_test.coffee | DavidSouther/song-flux-chat | 1 | messages = [
id: 'm_4',
threadID: 't_2',
threadName: 'Dave and Bill',
authorName: 'Bill',
text: 'Hey Dave, want to get a beer after the conference?',
timestamp: Date.now() - 69999
,
id: 'm_5',
threadID: 't_2',
threadName: 'Dave and Bill',
authorName: 'Dave',
text: 'Totally! Meet you at the hotel bar.',
timestamp: Date.now() - 59999
]
messages.forEach (_)->_.date = new Date(_.timestamp)
mockThreadStore =
listener: null
addUpdateListener: (cb)-> mockThreadStore.listener = cb
getCurrent: ->
id: 't_2'
name: 'Dave and Bill'
lastMessage: messages[1]
mockMessageStore =
listener: null
addUpdateListener: (cb)-> mockMessageStore.listener = cb
getAllForCurrentThread: -> messages
describe 'MessageDirective', ->
sut = null
beforeEach module 'song.chat.message.directive'
beforeEach module ($provide)->
$provide.value 'ThreadStore', mockThreadStore
$provide.value 'MessageStore', mockMessageStore
return false
describe 'Controller', ->
beforeEach inject ($controller)->
sut = renderElement('chat-messages').isolateScope().state
mockThreadStore.listener()
it 'loads the current thread', ->
sut.thread.id.should.equal 't_2'
sut.messages.length.should.equal 2
describe 'render', ->
beforeEach ->
sut = renderElement 'chat-messages'
mockMessageStore.listener()
sut.$scope.$digest()
it 'prints the thread', ->
sut.find('h3').text().should.equal 'Dave and Bill'
sut.find('message-item').length.should.equal 2
| 6868 | messages = [
id: 'm_4',
threadID: 't_2',
threadName: '<NAME>',
authorName: '<NAME>',
text: 'Hey <NAME>, want to get a beer after the conference?',
timestamp: Date.now() - 69999
,
id: 'm_5',
threadID: 't_2',
threadName: '<NAME>',
authorName: '<NAME>',
text: 'Totally! Meet you at the hotel bar.',
timestamp: Date.now() - 59999
]
messages.forEach (_)->_.date = new Date(_.timestamp)
mockThreadStore =
listener: null
addUpdateListener: (cb)-> mockThreadStore.listener = cb
getCurrent: ->
id: 't_2'
name: '<NAME>'
lastMessage: messages[1]
mockMessageStore =
listener: null
addUpdateListener: (cb)-> mockMessageStore.listener = cb
getAllForCurrentThread: -> messages
describe 'MessageDirective', ->
sut = null
beforeEach module 'song.chat.message.directive'
beforeEach module ($provide)->
$provide.value 'ThreadStore', mockThreadStore
$provide.value 'MessageStore', mockMessageStore
return false
describe 'Controller', ->
beforeEach inject ($controller)->
sut = renderElement('chat-messages').isolateScope().state
mockThreadStore.listener()
it 'loads the current thread', ->
sut.thread.id.should.equal 't_2'
sut.messages.length.should.equal 2
describe 'render', ->
beforeEach ->
sut = renderElement 'chat-messages'
mockMessageStore.listener()
sut.$scope.$digest()
it 'prints the thread', ->
sut.find('h3').text().should.equal '<NAME>'
sut.find('message-item').length.should.equal 2
| true | messages = [
id: 'm_4',
threadID: 't_2',
threadName: 'PI:NAME:<NAME>END_PI',
authorName: 'PI:NAME:<NAME>END_PI',
text: 'Hey PI:NAME:<NAME>END_PI, want to get a beer after the conference?',
timestamp: Date.now() - 69999
,
id: 'm_5',
threadID: 't_2',
threadName: 'PI:NAME:<NAME>END_PI',
authorName: 'PI:NAME:<NAME>END_PI',
text: 'Totally! Meet you at the hotel bar.',
timestamp: Date.now() - 59999
]
messages.forEach (_)->_.date = new Date(_.timestamp)
mockThreadStore =
listener: null
addUpdateListener: (cb)-> mockThreadStore.listener = cb
getCurrent: ->
id: 't_2'
name: 'PI:NAME:<NAME>END_PI'
lastMessage: messages[1]
mockMessageStore =
listener: null
addUpdateListener: (cb)-> mockMessageStore.listener = cb
getAllForCurrentThread: -> messages
describe 'MessageDirective', ->
sut = null
beforeEach module 'song.chat.message.directive'
beforeEach module ($provide)->
$provide.value 'ThreadStore', mockThreadStore
$provide.value 'MessageStore', mockMessageStore
return false
describe 'Controller', ->
beforeEach inject ($controller)->
sut = renderElement('chat-messages').isolateScope().state
mockThreadStore.listener()
it 'loads the current thread', ->
sut.thread.id.should.equal 't_2'
sut.messages.length.should.equal 2
describe 'render', ->
beforeEach ->
sut = renderElement 'chat-messages'
mockMessageStore.listener()
sut.$scope.$digest()
it 'prints the thread', ->
sut.find('h3').text().should.equal 'PI:NAME:<NAME>END_PI'
sut.find('message-item').length.should.equal 2
|
[
{
"context": "@fileoverview Validate JSX maximum depth\n# @author Chris<wfsr@foxmail.com>\n###\n'use strict'\n\n# -----------",
"end": 63,
"score": 0.9996255040168762,
"start": 58,
"tag": "NAME",
"value": "Chris"
},
{
"context": "erview Validate JSX maximum depth\n# @author Chris<wfs... | src/tests/rules/jsx-max-depth.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Validate JSX maximum depth
# @author Chris<wfsr@foxmail.com>
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require 'eslint-plugin-react/lib/rules/jsx-max-depth'
{RuleTester} = require 'eslint'
path = require 'path'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'jsx-max-depth', rule,
valid: [
code: ['<App />'].join '\n'
,
code: ['<App>', ' <foo />', '</App>'].join '\n'
options: [max: 1]
,
code: ['<App>', ' <foo>', ' <bar />', ' </foo>', '</App>'].join '\n'
,
code: ['<App>', ' <foo>', ' <bar />', ' </foo>', '</App>'].join '\n'
options: [max: 2]
,
code: ['x = <div><em>x</em></div>', '<div>{x}</div>'].join '\n'
options: [max: 2]
,
code: 'foo = (x) => <div><em>{x}</em></div>'
options: [max: 2]
,
code: ['<></>'].join '\n'
,
# parser: 'babel-eslint'
code: ['<>', ' <foo />', '</>'].join '\n'
# parser: 'babel-eslint'
options: [max: 1]
,
code: ['x = <><em>x</em></>', '<>{x}</>'].join '\n'
# parser: 'babel-eslint'
options: [max: 2]
]
invalid: [
code: ['<App>', ' <foo />', '</App>'].join '\n'
options: [max: 0]
errors: [
message:
'Expected the depth of nested jsx elements to be <= 0, but found 1.'
]
,
code: ['<App>', ' <foo>{bar}</foo>', '</App>'].join '\n'
options: [max: 0]
errors: [
message:
'Expected the depth of nested jsx elements to be <= 0, but found 1.'
]
,
code: ['<App>', ' <foo>', ' <bar />', ' </foo>', '</App>'].join '\n'
options: [max: 1]
errors: [
message:
'Expected the depth of nested jsx elements to be <= 1, but found 2.'
]
,
code: ['x = <div><span /></div>', '<div>{x}</div>'].join '\n'
options: [max: 1]
errors: [
message:
'Expected the depth of nested jsx elements to be <= 1, but found 2.'
]
,
code: ['x = <div><span /></div>', 'y = x', '<div>{y}</div>'].join '\n'
options: [max: 1]
errors: [
message:
'Expected the depth of nested jsx elements to be <= 1, but found 2.'
]
,
code: ['x = <div><span /></div>', 'y = x', '<div>{x}-{y}</div>'].join '\n'
options: [max: 1]
errors: [
message:
'Expected the depth of nested jsx elements to be <= 1, but found 2.'
,
message:
'Expected the depth of nested jsx elements to be <= 1, but found 2.'
]
,
code: ['<div>', '{<div><div><span /></div></div>}', '</div>'].join '\n'
# parser: 'babel-eslint'
errors: [
message:
'Expected the depth of nested jsx elements to be <= 2, but found 3.'
]
# ,
# code: ['<>', ' <foo />', '</>'].join '\n'
# # parser: 'babel-eslint'
# options: [max: 0]
# errors: [
# message:
# 'Expected the depth of nested jsx elements to be <= 0, but found 1.'
# ]
# ,
# code: ['<>', ' <>', ' <bar />', ' </>', '</>'].join '\n'
# # parser: 'babel-eslint'
# options: [max: 1]
# errors: [
# message:
# 'Expected the depth of nested jsx elements to be <= 1, but found 2.'
# ]
# ,
# code: ['x = <><span /></>', 'y = x', '<>{x}-{y}</>'].join '\n'
# # parser: 'babel-eslint'
# options: [max: 1]
# errors: [
# message:
# 'Expected the depth of nested jsx elements to be <= 1, but found 2.'
# ,
# message:
# 'Expected the depth of nested jsx elements to be <= 1, but found 2.'
# ]
]
| 114618 | ###*
# @fileoverview Validate JSX maximum depth
# @author <NAME><<EMAIL>>
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require 'eslint-plugin-react/lib/rules/jsx-max-depth'
{RuleTester} = require 'eslint'
path = require 'path'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'jsx-max-depth', rule,
valid: [
code: ['<App />'].join '\n'
,
code: ['<App>', ' <foo />', '</App>'].join '\n'
options: [max: 1]
,
code: ['<App>', ' <foo>', ' <bar />', ' </foo>', '</App>'].join '\n'
,
code: ['<App>', ' <foo>', ' <bar />', ' </foo>', '</App>'].join '\n'
options: [max: 2]
,
code: ['x = <div><em>x</em></div>', '<div>{x}</div>'].join '\n'
options: [max: 2]
,
code: 'foo = (x) => <div><em>{x}</em></div>'
options: [max: 2]
,
code: ['<></>'].join '\n'
,
# parser: 'babel-eslint'
code: ['<>', ' <foo />', '</>'].join '\n'
# parser: 'babel-eslint'
options: [max: 1]
,
code: ['x = <><em>x</em></>', '<>{x}</>'].join '\n'
# parser: 'babel-eslint'
options: [max: 2]
]
invalid: [
code: ['<App>', ' <foo />', '</App>'].join '\n'
options: [max: 0]
errors: [
message:
'Expected the depth of nested jsx elements to be <= 0, but found 1.'
]
,
code: ['<App>', ' <foo>{bar}</foo>', '</App>'].join '\n'
options: [max: 0]
errors: [
message:
'Expected the depth of nested jsx elements to be <= 0, but found 1.'
]
,
code: ['<App>', ' <foo>', ' <bar />', ' </foo>', '</App>'].join '\n'
options: [max: 1]
errors: [
message:
'Expected the depth of nested jsx elements to be <= 1, but found 2.'
]
,
code: ['x = <div><span /></div>', '<div>{x}</div>'].join '\n'
options: [max: 1]
errors: [
message:
'Expected the depth of nested jsx elements to be <= 1, but found 2.'
]
,
code: ['x = <div><span /></div>', 'y = x', '<div>{y}</div>'].join '\n'
options: [max: 1]
errors: [
message:
'Expected the depth of nested jsx elements to be <= 1, but found 2.'
]
,
code: ['x = <div><span /></div>', 'y = x', '<div>{x}-{y}</div>'].join '\n'
options: [max: 1]
errors: [
message:
'Expected the depth of nested jsx elements to be <= 1, but found 2.'
,
message:
'Expected the depth of nested jsx elements to be <= 1, but found 2.'
]
,
code: ['<div>', '{<div><div><span /></div></div>}', '</div>'].join '\n'
# parser: 'babel-eslint'
errors: [
message:
'Expected the depth of nested jsx elements to be <= 2, but found 3.'
]
# ,
# code: ['<>', ' <foo />', '</>'].join '\n'
# # parser: 'babel-eslint'
# options: [max: 0]
# errors: [
# message:
# 'Expected the depth of nested jsx elements to be <= 0, but found 1.'
# ]
# ,
# code: ['<>', ' <>', ' <bar />', ' </>', '</>'].join '\n'
# # parser: 'babel-eslint'
# options: [max: 1]
# errors: [
# message:
# 'Expected the depth of nested jsx elements to be <= 1, but found 2.'
# ]
# ,
# code: ['x = <><span /></>', 'y = x', '<>{x}-{y}</>'].join '\n'
# # parser: 'babel-eslint'
# options: [max: 1]
# errors: [
# message:
# 'Expected the depth of nested jsx elements to be <= 1, but found 2.'
# ,
# message:
# 'Expected the depth of nested jsx elements to be <= 1, but found 2.'
# ]
]
| true | ###*
# @fileoverview Validate JSX maximum depth
# @author PI:NAME:<NAME>END_PI<PI:EMAIL:<EMAIL>END_PI>
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require 'eslint-plugin-react/lib/rules/jsx-max-depth'
{RuleTester} = require 'eslint'
path = require 'path'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'jsx-max-depth', rule,
valid: [
code: ['<App />'].join '\n'
,
code: ['<App>', ' <foo />', '</App>'].join '\n'
options: [max: 1]
,
code: ['<App>', ' <foo>', ' <bar />', ' </foo>', '</App>'].join '\n'
,
code: ['<App>', ' <foo>', ' <bar />', ' </foo>', '</App>'].join '\n'
options: [max: 2]
,
code: ['x = <div><em>x</em></div>', '<div>{x}</div>'].join '\n'
options: [max: 2]
,
code: 'foo = (x) => <div><em>{x}</em></div>'
options: [max: 2]
,
code: ['<></>'].join '\n'
,
# parser: 'babel-eslint'
code: ['<>', ' <foo />', '</>'].join '\n'
# parser: 'babel-eslint'
options: [max: 1]
,
code: ['x = <><em>x</em></>', '<>{x}</>'].join '\n'
# parser: 'babel-eslint'
options: [max: 2]
]
invalid: [
code: ['<App>', ' <foo />', '</App>'].join '\n'
options: [max: 0]
errors: [
message:
'Expected the depth of nested jsx elements to be <= 0, but found 1.'
]
,
code: ['<App>', ' <foo>{bar}</foo>', '</App>'].join '\n'
options: [max: 0]
errors: [
message:
'Expected the depth of nested jsx elements to be <= 0, but found 1.'
]
,
code: ['<App>', ' <foo>', ' <bar />', ' </foo>', '</App>'].join '\n'
options: [max: 1]
errors: [
message:
'Expected the depth of nested jsx elements to be <= 1, but found 2.'
]
,
code: ['x = <div><span /></div>', '<div>{x}</div>'].join '\n'
options: [max: 1]
errors: [
message:
'Expected the depth of nested jsx elements to be <= 1, but found 2.'
]
,
code: ['x = <div><span /></div>', 'y = x', '<div>{y}</div>'].join '\n'
options: [max: 1]
errors: [
message:
'Expected the depth of nested jsx elements to be <= 1, but found 2.'
]
,
code: ['x = <div><span /></div>', 'y = x', '<div>{x}-{y}</div>'].join '\n'
options: [max: 1]
errors: [
message:
'Expected the depth of nested jsx elements to be <= 1, but found 2.'
,
message:
'Expected the depth of nested jsx elements to be <= 1, but found 2.'
]
,
code: ['<div>', '{<div><div><span /></div></div>}', '</div>'].join '\n'
# parser: 'babel-eslint'
errors: [
message:
'Expected the depth of nested jsx elements to be <= 2, but found 3.'
]
# ,
# code: ['<>', ' <foo />', '</>'].join '\n'
# # parser: 'babel-eslint'
# options: [max: 0]
# errors: [
# message:
# 'Expected the depth of nested jsx elements to be <= 0, but found 1.'
# ]
# ,
# code: ['<>', ' <>', ' <bar />', ' </>', '</>'].join '\n'
# # parser: 'babel-eslint'
# options: [max: 1]
# errors: [
# message:
# 'Expected the depth of nested jsx elements to be <= 1, but found 2.'
# ]
# ,
# code: ['x = <><span /></>', 'y = x', '<>{x}-{y}</>'].join '\n'
# # parser: 'babel-eslint'
# options: [max: 1]
# errors: [
# message:
# 'Expected the depth of nested jsx elements to be <= 1, but found 2.'
# ,
# message:
# 'Expected the depth of nested jsx elements to be <= 1, but found 2.'
# ]
]
|
[
{
"context": "uire localstorage\n#= require usecase\n\nfullname = \"Pusher Chat\"\ndescription = \"Pusher Chat\"\n\nclass Templates\n m",
"end": 179,
"score": 0.9851713180541992,
"start": 168,
"tag": "NAME",
"value": "Pusher Chat"
},
{
"context": "at: (nick) ->\n\n\nclass @PusherCha... | app/assets/javascripts/pusher_chat.js.coffee | CoffeeDesktop/coffeedesktop-rails | 0 | #Warning: This code contains ugly this
#Warning: You have been warned about this
#= require gui
#= require glue
#= require localstorage
#= require usecase
fullname = "Pusher Chat"
description = "Pusher Chat"
class Templates
main: ->
"<form id='nick_form'>
<h2>Pusher Chat</h2><hr>
Choose your nickname: <input type='text' id='nick'> <input type='submit'>
</form>
"
chat_window: ->
"<table id='chat_window'>
<tr><td class='pusher_chat_title'><h2>Pusher Chat</h2><hr style='margin-top: 0px;margin-bottom: -5px;'></td></tr>
<tr><td><div id='chat'></div></td></tr>
<tr><td class='msg_input_box'><hr style='margin-top: -5px;margin-bottom: 5px;'><form id='msg_input'>
Msg:<input type='text' id='msg'><input type='submit'>
</form>
</td></tr>
</table>"
class Backend
constructor: () ->
postData: (data) ->
$.post("/coffeedesktop/pch_post", data );
class PusherAdapter
update: (data) ->
#console.warn(data)
constructor: (key) ->
pusher = new Pusher(key);
channel = pusher.subscribe('pusher_chat');
channel.bind('data-changed', (data) =>
#console.log(data)
@update(data)
)
class LocalStorage extends @LocalStorageClass
class UseCase extends @UseCaseClass
constructor: (@gui, @backend) ->
super
sendMsg: (msg) ->
@backend.postData({'nick':@nick, 'msg',msg})
startChat: (@nick) ->
@gui.setChatWindowContent()
newMsgReceived:(data) ->
@gui.appendMsg(data.nick, data.msg, data.date)
class Glue extends @GlueClass
constructor: (@useCase, @gui, @storage, @app, @pusher) ->
super
After(@gui, 'startChat', (nick) => @useCase.startChat(nick))
After(@gui, 'sendMsg', (msg) => @useCase.sendMsg(msg))
After(@pusher, 'update', (data) => @useCase.newMsgReceived(data))
#LogAll(@useCase)
#LogAll(@gui)
class Gui extends @GuiClass
setChatWindowContent: () ->
$.updateWindowContent(@div_id, @templates.chat_window());
@setChatBindings()
setBindings: ->
$("#"+ @div_id+ " #nick_form").submit( () =>
nick = $("#"+ @div_id+ " #nick").val()
@startChat(nick)
false
)
setChatBindings: () ->
msg_element = @element.find("#msg_input")
msg_input = msg_element.find("#msg")
msg_element.submit( () =>
msg = msg_input.val()
@sendMsg(msg)
msg_input.val("")
false
)
appendMsg: (nick, msg, date) ->
$("#"+@div_id+ " #chat").append("<span><b>"+nick+"</b>(@"+date+"): "+msg+"<hr>")
#aop shit
sendMsg: (msg) ->
startChat: (nick) ->
class @PusherChatApp
@fullname = fullname
@description = description
@icon = "xchat.png"
constructor: (id) ->
@id = id
@fullname = fullname
@description = description
pusher = new PusherAdapter('dc82e8733c54f74df8d3')
templates = new Templates()
gui = new Gui(templates)
localStorage = new LocalStorage("CoffeeDesktop")
backend = new Backend()
useCase = new UseCase(gui, backend)
#probably this under this line is temporary this because this isnt on the path of truth
glue = new Glue(useCase, gui, localStorage,@, pusher)
# ^ this this is this ugly this
useCase.start()
window.pusher_chat = {}
window.pusher_chat.UseCase = UseCase
window.pusher_chat.Gui = Gui
window.pusher_chat.Templates = Templates
window.pusher_chat.PusherChatApp = PusherChatApp
window.CoffeeDesktop.appAdd('pch',@PusherChatApp) | 121841 | #Warning: This code contains ugly this
#Warning: You have been warned about this
#= require gui
#= require glue
#= require localstorage
#= require usecase
fullname = "<NAME>"
description = "Pusher Chat"
class Templates
main: ->
"<form id='nick_form'>
<h2>Pusher Chat</h2><hr>
Choose your nickname: <input type='text' id='nick'> <input type='submit'>
</form>
"
chat_window: ->
"<table id='chat_window'>
<tr><td class='pusher_chat_title'><h2>Pusher Chat</h2><hr style='margin-top: 0px;margin-bottom: -5px;'></td></tr>
<tr><td><div id='chat'></div></td></tr>
<tr><td class='msg_input_box'><hr style='margin-top: -5px;margin-bottom: 5px;'><form id='msg_input'>
Msg:<input type='text' id='msg'><input type='submit'>
</form>
</td></tr>
</table>"
class Backend
constructor: () ->
postData: (data) ->
$.post("/coffeedesktop/pch_post", data );
class PusherAdapter
update: (data) ->
#console.warn(data)
constructor: (key) ->
pusher = new Pusher(key);
channel = pusher.subscribe('pusher_chat');
channel.bind('data-changed', (data) =>
#console.log(data)
@update(data)
)
class LocalStorage extends @LocalStorageClass
class UseCase extends @UseCaseClass
constructor: (@gui, @backend) ->
super
sendMsg: (msg) ->
@backend.postData({'nick':@nick, 'msg',msg})
startChat: (@nick) ->
@gui.setChatWindowContent()
newMsgReceived:(data) ->
@gui.appendMsg(data.nick, data.msg, data.date)
class Glue extends @GlueClass
constructor: (@useCase, @gui, @storage, @app, @pusher) ->
super
After(@gui, 'startChat', (nick) => @useCase.startChat(nick))
After(@gui, 'sendMsg', (msg) => @useCase.sendMsg(msg))
After(@pusher, 'update', (data) => @useCase.newMsgReceived(data))
#LogAll(@useCase)
#LogAll(@gui)
class Gui extends @GuiClass
setChatWindowContent: () ->
$.updateWindowContent(@div_id, @templates.chat_window());
@setChatBindings()
setBindings: ->
$("#"+ @div_id+ " #nick_form").submit( () =>
nick = $("#"+ @div_id+ " #nick").val()
@startChat(nick)
false
)
setChatBindings: () ->
msg_element = @element.find("#msg_input")
msg_input = msg_element.find("#msg")
msg_element.submit( () =>
msg = msg_input.val()
@sendMsg(msg)
msg_input.val("")
false
)
appendMsg: (nick, msg, date) ->
$("#"+@div_id+ " #chat").append("<span><b>"+nick+"</b>(@"+date+"): "+msg+"<hr>")
#aop shit
sendMsg: (msg) ->
startChat: (nick) ->
class @PusherChatApp
@fullname = <NAME>
@description = description
@icon = "xchat.png"
constructor: (id) ->
@id = id
@fullname = <NAME>
@description = description
pusher = new PusherAdapter('dc82e8733c54f74df8d3')
templates = new Templates()
gui = new Gui(templates)
localStorage = new LocalStorage("CoffeeDesktop")
backend = new Backend()
useCase = new UseCase(gui, backend)
#probably this under this line is temporary this because this isnt on the path of truth
glue = new Glue(useCase, gui, localStorage,@, pusher)
# ^ this this is this ugly this
useCase.start()
window.pusher_chat = {}
window.pusher_chat.UseCase = UseCase
window.pusher_chat.Gui = Gui
window.pusher_chat.Templates = Templates
window.pusher_chat.PusherChatApp = PusherChatApp
window.CoffeeDesktop.appAdd('pch',@PusherChatApp) | true | #Warning: This code contains ugly this
#Warning: You have been warned about this
#= require gui
#= require glue
#= require localstorage
#= require usecase
fullname = "PI:NAME:<NAME>END_PI"
description = "Pusher Chat"
class Templates
main: ->
"<form id='nick_form'>
<h2>Pusher Chat</h2><hr>
Choose your nickname: <input type='text' id='nick'> <input type='submit'>
</form>
"
chat_window: ->
"<table id='chat_window'>
<tr><td class='pusher_chat_title'><h2>Pusher Chat</h2><hr style='margin-top: 0px;margin-bottom: -5px;'></td></tr>
<tr><td><div id='chat'></div></td></tr>
<tr><td class='msg_input_box'><hr style='margin-top: -5px;margin-bottom: 5px;'><form id='msg_input'>
Msg:<input type='text' id='msg'><input type='submit'>
</form>
</td></tr>
</table>"
class Backend
constructor: () ->
postData: (data) ->
$.post("/coffeedesktop/pch_post", data );
class PusherAdapter
update: (data) ->
#console.warn(data)
constructor: (key) ->
pusher = new Pusher(key);
channel = pusher.subscribe('pusher_chat');
channel.bind('data-changed', (data) =>
#console.log(data)
@update(data)
)
class LocalStorage extends @LocalStorageClass
class UseCase extends @UseCaseClass
constructor: (@gui, @backend) ->
super
sendMsg: (msg) ->
@backend.postData({'nick':@nick, 'msg',msg})
startChat: (@nick) ->
@gui.setChatWindowContent()
newMsgReceived:(data) ->
@gui.appendMsg(data.nick, data.msg, data.date)
class Glue extends @GlueClass
constructor: (@useCase, @gui, @storage, @app, @pusher) ->
super
After(@gui, 'startChat', (nick) => @useCase.startChat(nick))
After(@gui, 'sendMsg', (msg) => @useCase.sendMsg(msg))
After(@pusher, 'update', (data) => @useCase.newMsgReceived(data))
#LogAll(@useCase)
#LogAll(@gui)
class Gui extends @GuiClass
setChatWindowContent: () ->
$.updateWindowContent(@div_id, @templates.chat_window());
@setChatBindings()
setBindings: ->
$("#"+ @div_id+ " #nick_form").submit( () =>
nick = $("#"+ @div_id+ " #nick").val()
@startChat(nick)
false
)
setChatBindings: () ->
msg_element = @element.find("#msg_input")
msg_input = msg_element.find("#msg")
msg_element.submit( () =>
msg = msg_input.val()
@sendMsg(msg)
msg_input.val("")
false
)
appendMsg: (nick, msg, date) ->
$("#"+@div_id+ " #chat").append("<span><b>"+nick+"</b>(@"+date+"): "+msg+"<hr>")
#aop shit
sendMsg: (msg) ->
startChat: (nick) ->
class @PusherChatApp
@fullname = PI:NAME:<NAME>END_PI
@description = description
@icon = "xchat.png"
constructor: (id) ->
@id = id
@fullname = PI:NAME:<NAME>END_PI
@description = description
pusher = new PusherAdapter('dc82e8733c54f74df8d3')
templates = new Templates()
gui = new Gui(templates)
localStorage = new LocalStorage("CoffeeDesktop")
backend = new Backend()
useCase = new UseCase(gui, backend)
#probably this under this line is temporary this because this isnt on the path of truth
glue = new Glue(useCase, gui, localStorage,@, pusher)
# ^ this this is this ugly this
useCase.start()
window.pusher_chat = {}
window.pusher_chat.UseCase = UseCase
window.pusher_chat.Gui = Gui
window.pusher_chat.Templates = Templates
window.pusher_chat.PusherChatApp = PusherChatApp
window.CoffeeDesktop.appAdd('pch',@PusherChatApp) |
[
{
"context": "ypeId: null\n protocol: 3 << 16\n\n constructor: (@user, @database, @options) ->\n\n payload: ->\n pos =",
"end": 977,
"score": 0.6839166283607483,
"start": 973,
"tag": "USERNAME",
"value": "user"
},
{
"context": " when Authentication.methods.MD5_PASSWORD then \"m... | src/frontend_message.coffee | simplereach/node-vertica | 0 | Authentication = require('./authentication')
Buffer = require('./buffer').Buffer
###########################################
# Client messages
###########################################
class FrontendMessage
typeId: null
payload: ->
new Buffer(0)
toBuffer: ->
payloadBuffer = @payload()
if typeof payloadBuffer == 'string'
bLength = Buffer.byteLength(payloadBuffer);
b = new Buffer(bLength + 1)
b.writeZeroTerminatedString(payloadBuffer, 0)
payloadBuffer = b
headerLength = if @typeId? then 5 else 4
messageBuffer = new Buffer(headerLength + payloadBuffer.length)
if @typeId
messageBuffer.writeUInt8(@typeId, 0)
pos = 1
else
pos = 0
messageBuffer.writeUInt32BE(payloadBuffer.length + 4, pos)
payloadBuffer.copy(messageBuffer, pos + 4)
return messageBuffer
class FrontendMessage.Startup extends FrontendMessage
typeId: null
protocol: 3 << 16
constructor: (@user, @database, @options) ->
payload: ->
pos = 0
pl = new Buffer(8192)
pl.writeUInt32BE(@protocol, pos)
pos += 4
if @user
pos += pl.writeZeroTerminatedString('user', pos)
pos += pl.writeZeroTerminatedString(@user, pos)
if @database
pos += pl.writeZeroTerminatedString('database', pos)
pos += pl.writeZeroTerminatedString(@database, pos)
if @options
pos += pl.writeZeroTerminatedString('options', pos)
pos += pl.writeZeroTerminatedString(@options, pos)
pl.writeUInt8(0, pos)
pos += 1
return pl.slice(0, pos)
class FrontendMessage.SSLRequest extends FrontendMessage
typeId: null
sslMagicNumber: 80877103
payload: ->
pl = new Buffer(4)
pl.writeUInt32BE(@sslMagicNumber, 0)
return pl
class FrontendMessage.Password extends FrontendMessage
typeId: 112
constructor: (@password, @authMethod, @options) ->
@password ?= ''
@authMethod ?= Authentication.methods.CLEARTEXT_PASSWORD
@options ?= {}
md5: (str) ->
hash = require('crypto').createHash('md5')
hash.update(str)
hash.digest('hex')
encodedPassword: ->
switch @authMethod
when Authentication.methods.CLEARTEXT_PASSWORD then @password
when Authentication.methods.MD5_PASSWORD then "md5" + @md5(@md5(@password + @options.user) + @options.salt)
else throw new Error("Authentication method #{@authMethod} not implemented.")
payload: ->
@encodedPassword()
class FrontendMessage.CancelRequest extends FrontendMessage
cancelRequestMagicNumber: 80877102
constructor: (@backendPid, @backendKey) ->
payload: ->
b = new Buffer(12)
b.writeUInt32BE(@cancelRequestMagicNumber, 0)
b.writeUInt32BE(@backendPid, 4)
b.writeUInt32BE(@backendKey, 8)
return b
class FrontendMessage.Close extends FrontendMessage
typeId: 67
constructor: (type, @name) ->
@name ?= ""
@type = switch type
when 'portal', 'p', 'P', 80 then 80
when 'prepared_statement', 'prepared', 'statement', 's', 'S', 83 then 83
else throw new Error("#{type} not a valid type to describe")
payload: ->
b = new Buffer(@name.length + 2)
b.writeUInt8(@type, 0)
b.writeZeroTerminatedString(@name, 1)
return b
class FrontendMessage.Describe extends FrontendMessage
typeId: 68
constructor: (type, @name) ->
@name ?= ""
@type = switch type
when 'portal', 'P', 80 then 80
when 'prepared_statement', 'prepared', 'statement', 'S', 83 then 83
else throw new Error("#{type} not a valid type to describe")
payload: ->
b = new Buffer(@name.length + 2)
b.writeUInt8(@type, 0)
b.writeZeroTerminatedString(@name, 1)
return b
# EXECUTE (E=69)
class FrontendMessage.Execute extends FrontendMessage
typeId: 69
constructor: (@portal, @maxRows) ->
@portal ?= ""
@maxRows ?= 0
payload: ->
b = new Buffer(5 + @portal.length)
pos = b.writeZeroTerminatedString(@portal, 0)
b.writeUInt32BE(@maxRows, pos)
return b
class FrontendMessage.Query extends FrontendMessage
typeId: 81
constructor: (@sql) ->
payload: ->
@sql
class FrontendMessage.Parse extends FrontendMessage
typeId: 80
constructor: (@name, @sql, @parameterTypes) ->
@name ?= ""
@parameterTypes ?= []
payload: ->
b = new Buffer(8192)
pos = b.writeZeroTerminatedString(@name, 0)
pos += b.writeZeroTerminatedString(@sql, pos)
b.writeUInt16BE(@parameterTypes.length, pos)
pos += 2
for paramType in @parameterTypes
b.writeUInt32BE(paramType, pos)
pos += 4
return b.slice(0, pos)
class FrontendMessage.Bind extends FrontendMessage
typeId: 66
constructor: (@portal, @preparedStatement, parameterValues) ->
@parameterValues = []
for parameterValue in parameterValues
@parameterValues.push parameterValue.toString()
payload: ->
b = new Buffer(8192)
pos = 0
pos += b.writeZeroTerminatedString(@portal, pos)
pos += b.writeZeroTerminatedString(@preparedStatement, pos)
b.writeUInt16BE(0x00, pos) # encode values using text
b.writeUInt16BE(@parameterValues.length, pos + 2)
pos += 4
for value in @parameterValues
b.writeUInt32BE(value.length, pos)
pos += 4
pos += b.write(value, pos)
return b.slice(0, pos)
class FrontendMessage.Flush extends FrontendMessage
typeId: 72
class FrontendMessage.Sync extends FrontendMessage
typeId: 83
class FrontendMessage.Terminate extends FrontendMessage
typeId: 88
class FrontendMessage.CopyData extends FrontendMessage
typeId: 100
constructor: (@data) ->
payload: ->
new Buffer(@data)
class FrontendMessage.CopyDone extends FrontendMessage
typeId: 99
class FrontendMessage.CopyFail extends FrontendMessage
typeId: 102
constructor: (@error) ->
payload: ->
@error
module.exports = FrontendMessage
| 93907 | Authentication = require('./authentication')
Buffer = require('./buffer').Buffer
###########################################
# Client messages
###########################################
class FrontendMessage
typeId: null
payload: ->
new Buffer(0)
toBuffer: ->
payloadBuffer = @payload()
if typeof payloadBuffer == 'string'
bLength = Buffer.byteLength(payloadBuffer);
b = new Buffer(bLength + 1)
b.writeZeroTerminatedString(payloadBuffer, 0)
payloadBuffer = b
headerLength = if @typeId? then 5 else 4
messageBuffer = new Buffer(headerLength + payloadBuffer.length)
if @typeId
messageBuffer.writeUInt8(@typeId, 0)
pos = 1
else
pos = 0
messageBuffer.writeUInt32BE(payloadBuffer.length + 4, pos)
payloadBuffer.copy(messageBuffer, pos + 4)
return messageBuffer
class FrontendMessage.Startup extends FrontendMessage
typeId: null
protocol: 3 << 16
constructor: (@user, @database, @options) ->
payload: ->
pos = 0
pl = new Buffer(8192)
pl.writeUInt32BE(@protocol, pos)
pos += 4
if @user
pos += pl.writeZeroTerminatedString('user', pos)
pos += pl.writeZeroTerminatedString(@user, pos)
if @database
pos += pl.writeZeroTerminatedString('database', pos)
pos += pl.writeZeroTerminatedString(@database, pos)
if @options
pos += pl.writeZeroTerminatedString('options', pos)
pos += pl.writeZeroTerminatedString(@options, pos)
pl.writeUInt8(0, pos)
pos += 1
return pl.slice(0, pos)
class FrontendMessage.SSLRequest extends FrontendMessage
typeId: null
sslMagicNumber: 80877103
payload: ->
pl = new Buffer(4)
pl.writeUInt32BE(@sslMagicNumber, 0)
return pl
class FrontendMessage.Password extends FrontendMessage
typeId: 112
constructor: (@password, @authMethod, @options) ->
@password ?= ''
@authMethod ?= Authentication.methods.CLEARTEXT_PASSWORD
@options ?= {}
md5: (str) ->
hash = require('crypto').createHash('md5')
hash.update(str)
hash.digest('hex')
encodedPassword: ->
switch @authMethod
when Authentication.methods.CLEARTEXT_PASSWORD then @password
when Authentication.methods.MD5_PASSWORD then "md<PASSWORD>" + @md5(@md5(@password + @options.user) + @options.salt)
else throw new Error("Authentication method #{@authMethod} not implemented.")
payload: ->
@encodedPassword()
class FrontendMessage.CancelRequest extends FrontendMessage
cancelRequestMagicNumber: 80877102
constructor: (@backendPid, @backendKey) ->
payload: ->
b = new Buffer(12)
b.writeUInt32BE(@cancelRequestMagicNumber, 0)
b.writeUInt32BE(@backendPid, 4)
b.writeUInt32BE(@backendKey, 8)
return b
class FrontendMessage.Close extends FrontendMessage
typeId: 67
constructor: (type, @name) ->
@name ?= ""
@type = switch type
when 'portal', 'p', 'P', 80 then 80
when 'prepared_statement', 'prepared', 'statement', 's', 'S', 83 then 83
else throw new Error("#{type} not a valid type to describe")
payload: ->
b = new Buffer(@name.length + 2)
b.writeUInt8(@type, 0)
b.writeZeroTerminatedString(@name, 1)
return b
class FrontendMessage.Describe extends FrontendMessage
typeId: 68
constructor: (type, @name) ->
@name ?= ""
@type = switch type
when 'portal', 'P', 80 then 80
when 'prepared_statement', 'prepared', 'statement', 'S', 83 then 83
else throw new Error("#{type} not a valid type to describe")
payload: ->
b = new Buffer(@name.length + 2)
b.writeUInt8(@type, 0)
b.writeZeroTerminatedString(@name, 1)
return b
# EXECUTE (E=69)
class FrontendMessage.Execute extends FrontendMessage
typeId: 69
constructor: (@portal, @maxRows) ->
@portal ?= ""
@maxRows ?= 0
payload: ->
b = new Buffer(5 + @portal.length)
pos = b.writeZeroTerminatedString(@portal, 0)
b.writeUInt32BE(@maxRows, pos)
return b
class FrontendMessage.Query extends FrontendMessage
typeId: 81
constructor: (@sql) ->
payload: ->
@sql
class FrontendMessage.Parse extends FrontendMessage
typeId: 80
constructor: (@name, @sql, @parameterTypes) ->
@name ?= ""
@parameterTypes ?= []
payload: ->
b = new Buffer(8192)
pos = b.writeZeroTerminatedString(@name, 0)
pos += b.writeZeroTerminatedString(@sql, pos)
b.writeUInt16BE(@parameterTypes.length, pos)
pos += 2
for paramType in @parameterTypes
b.writeUInt32BE(paramType, pos)
pos += 4
return b.slice(0, pos)
class FrontendMessage.Bind extends FrontendMessage
typeId: 66
constructor: (@portal, @preparedStatement, parameterValues) ->
@parameterValues = []
for parameterValue in parameterValues
@parameterValues.push parameterValue.toString()
payload: ->
b = new Buffer(8192)
pos = 0
pos += b.writeZeroTerminatedString(@portal, pos)
pos += b.writeZeroTerminatedString(@preparedStatement, pos)
b.writeUInt16BE(0x00, pos) # encode values using text
b.writeUInt16BE(@parameterValues.length, pos + 2)
pos += 4
for value in @parameterValues
b.writeUInt32BE(value.length, pos)
pos += 4
pos += b.write(value, pos)
return b.slice(0, pos)
class FrontendMessage.Flush extends FrontendMessage
typeId: 72
class FrontendMessage.Sync extends FrontendMessage
typeId: 83
class FrontendMessage.Terminate extends FrontendMessage
typeId: 88
class FrontendMessage.CopyData extends FrontendMessage
typeId: 100
constructor: (@data) ->
payload: ->
new Buffer(@data)
class FrontendMessage.CopyDone extends FrontendMessage
typeId: 99
class FrontendMessage.CopyFail extends FrontendMessage
typeId: 102
constructor: (@error) ->
payload: ->
@error
module.exports = FrontendMessage
| true | Authentication = require('./authentication')
Buffer = require('./buffer').Buffer
###########################################
# Client messages
###########################################
class FrontendMessage
typeId: null
payload: ->
new Buffer(0)
toBuffer: ->
payloadBuffer = @payload()
if typeof payloadBuffer == 'string'
bLength = Buffer.byteLength(payloadBuffer);
b = new Buffer(bLength + 1)
b.writeZeroTerminatedString(payloadBuffer, 0)
payloadBuffer = b
headerLength = if @typeId? then 5 else 4
messageBuffer = new Buffer(headerLength + payloadBuffer.length)
if @typeId
messageBuffer.writeUInt8(@typeId, 0)
pos = 1
else
pos = 0
messageBuffer.writeUInt32BE(payloadBuffer.length + 4, pos)
payloadBuffer.copy(messageBuffer, pos + 4)
return messageBuffer
class FrontendMessage.Startup extends FrontendMessage
typeId: null
protocol: 3 << 16
constructor: (@user, @database, @options) ->
payload: ->
pos = 0
pl = new Buffer(8192)
pl.writeUInt32BE(@protocol, pos)
pos += 4
if @user
pos += pl.writeZeroTerminatedString('user', pos)
pos += pl.writeZeroTerminatedString(@user, pos)
if @database
pos += pl.writeZeroTerminatedString('database', pos)
pos += pl.writeZeroTerminatedString(@database, pos)
if @options
pos += pl.writeZeroTerminatedString('options', pos)
pos += pl.writeZeroTerminatedString(@options, pos)
pl.writeUInt8(0, pos)
pos += 1
return pl.slice(0, pos)
class FrontendMessage.SSLRequest extends FrontendMessage
typeId: null
sslMagicNumber: 80877103
payload: ->
pl = new Buffer(4)
pl.writeUInt32BE(@sslMagicNumber, 0)
return pl
class FrontendMessage.Password extends FrontendMessage
typeId: 112
constructor: (@password, @authMethod, @options) ->
@password ?= ''
@authMethod ?= Authentication.methods.CLEARTEXT_PASSWORD
@options ?= {}
md5: (str) ->
hash = require('crypto').createHash('md5')
hash.update(str)
hash.digest('hex')
encodedPassword: ->
switch @authMethod
when Authentication.methods.CLEARTEXT_PASSWORD then @password
when Authentication.methods.MD5_PASSWORD then "mdPI:PASSWORD:<PASSWORD>END_PI" + @md5(@md5(@password + @options.user) + @options.salt)
else throw new Error("Authentication method #{@authMethod} not implemented.")
payload: ->
@encodedPassword()
class FrontendMessage.CancelRequest extends FrontendMessage
cancelRequestMagicNumber: 80877102
constructor: (@backendPid, @backendKey) ->
payload: ->
b = new Buffer(12)
b.writeUInt32BE(@cancelRequestMagicNumber, 0)
b.writeUInt32BE(@backendPid, 4)
b.writeUInt32BE(@backendKey, 8)
return b
class FrontendMessage.Close extends FrontendMessage
typeId: 67
constructor: (type, @name) ->
@name ?= ""
@type = switch type
when 'portal', 'p', 'P', 80 then 80
when 'prepared_statement', 'prepared', 'statement', 's', 'S', 83 then 83
else throw new Error("#{type} not a valid type to describe")
payload: ->
b = new Buffer(@name.length + 2)
b.writeUInt8(@type, 0)
b.writeZeroTerminatedString(@name, 1)
return b
class FrontendMessage.Describe extends FrontendMessage
typeId: 68
constructor: (type, @name) ->
@name ?= ""
@type = switch type
when 'portal', 'P', 80 then 80
when 'prepared_statement', 'prepared', 'statement', 'S', 83 then 83
else throw new Error("#{type} not a valid type to describe")
payload: ->
b = new Buffer(@name.length + 2)
b.writeUInt8(@type, 0)
b.writeZeroTerminatedString(@name, 1)
return b
# EXECUTE (E=69)
class FrontendMessage.Execute extends FrontendMessage
typeId: 69
constructor: (@portal, @maxRows) ->
@portal ?= ""
@maxRows ?= 0
payload: ->
b = new Buffer(5 + @portal.length)
pos = b.writeZeroTerminatedString(@portal, 0)
b.writeUInt32BE(@maxRows, pos)
return b
class FrontendMessage.Query extends FrontendMessage
typeId: 81
constructor: (@sql) ->
payload: ->
@sql
class FrontendMessage.Parse extends FrontendMessage
typeId: 80
constructor: (@name, @sql, @parameterTypes) ->
@name ?= ""
@parameterTypes ?= []
payload: ->
b = new Buffer(8192)
pos = b.writeZeroTerminatedString(@name, 0)
pos += b.writeZeroTerminatedString(@sql, pos)
b.writeUInt16BE(@parameterTypes.length, pos)
pos += 2
for paramType in @parameterTypes
b.writeUInt32BE(paramType, pos)
pos += 4
return b.slice(0, pos)
class FrontendMessage.Bind extends FrontendMessage
typeId: 66
constructor: (@portal, @preparedStatement, parameterValues) ->
@parameterValues = []
for parameterValue in parameterValues
@parameterValues.push parameterValue.toString()
payload: ->
b = new Buffer(8192)
pos = 0
pos += b.writeZeroTerminatedString(@portal, pos)
pos += b.writeZeroTerminatedString(@preparedStatement, pos)
b.writeUInt16BE(0x00, pos) # encode values using text
b.writeUInt16BE(@parameterValues.length, pos + 2)
pos += 4
for value in @parameterValues
b.writeUInt32BE(value.length, pos)
pos += 4
pos += b.write(value, pos)
return b.slice(0, pos)
class FrontendMessage.Flush extends FrontendMessage
typeId: 72
class FrontendMessage.Sync extends FrontendMessage
typeId: 83
class FrontendMessage.Terminate extends FrontendMessage
typeId: 88
class FrontendMessage.CopyData extends FrontendMessage
typeId: 100
constructor: (@data) ->
payload: ->
new Buffer(@data)
class FrontendMessage.CopyDone extends FrontendMessage
typeId: 99
class FrontendMessage.CopyFail extends FrontendMessage
typeId: 102
constructor: (@error) ->
payload: ->
@error
module.exports = FrontendMessage
|
[
{
"context": "user.get('id')\n tempUsername = user.get('username')\n fn(err, user.data)\n ))\n rou",
"end": 2029,
"score": 0.981255292892456,
"start": 2021,
"tag": "USERNAME",
"value": "username"
},
{
"context": "kets()\n request.get(\"/user/create?... | gameserver/test/int/models/game-int-test.coffee | towerstorm/game | 11 | app = require('../../../lib/app.coffee')
request = require("supertest")(app)
_ = require 'lodash'
sinon = require 'sinon'
Game = require('../../../models/game.coffee')
tdb = require 'database'
User = tdb.models.User
assert = require 'assert'
sio = require('socket.io')
cio = require('socket.io-client')
xhr = require('socket.io-client/node_modules/xmlhttprequest');
xhrOriginal = require('xmlhttprequest');
passport = require('passport')
LocalStrategy = require('passport-local').Strategy
rs = require 'randomstring'
delay = (time, func) -> setTimeout(func, time)
options = {
transports: ['websocket']
'force new connection': true
}
userInfo = null
cookies = ""
game = null
global.metricsServer
overrideXmlHttpRequest = () ->
xhr.XMLHttpRequest = ->
@XMLHttpRequest = xhrOriginal.XMLHttpRequest;
xhrOriginal.XMLHttpRequest.apply(@, arguments);
this.setDisableHeaderCheck(true);
openOriginal = this.open;
this.open = (method, url, async, user, password) ->
openOriginal.apply(this, arguments);
this.setRequestHeader('cookie', cookies);
return @
overrideXmlHttpRequest()
describe "Game Model Integration Test", ->
beforeEach ->
global.io = {
set: -> true
of: -> @
on: -> @
}
describe "init", ->
it "Should be able to initialize a game", (done) ->
game = new Game()
game.init ->
done()
describe "create", ->
it "Should be able to create a new game and save it out", (done) ->
Game.create (err, game) ->
if err then return done(err)
game.save (err, result) ->
if err then return done(err)
assert result != null
done()
describe "socket authorization", ->
socketUrl = ""
userId = null
tempUsername = ""
before (done) ->
express = require('express')
passport.use(new LocalStrategy({}, (username, password, fn) ->
User.createTempUser username, (err, user) ->
userId = user.get('id')
tempUsername = user.get('username')
fn(err, user.data)
))
router = express.Router()
router.get('/user/create', passport.authenticate('local'), (req, res) ->
res.status(200).jsonp({user: req.user})
)
app.use(router)
request = require("supertest")(app)
global.io = sio.listen(15001)
global.io.set('log level', 1)
game = new Game()
game.init ->
socketUrl = 'http://0.0.0.0:15001/game/' + game.get('code')
game.bindSockets()
request.get("/user/create?username=test" + rs.generate(4) + "&password=pass")
.end (err, res) ->
if err then return done(err)
console.log("Res text is: " + res.text)
userInfo = JSON.parse(res.text)
cookies = res.headers['set-cookie'].pop().split(';')[0]
console.log("Cookies are: " + cookies)
done()
it "Should allow users to connect", (done) ->
socket = cio.connect(socketUrl, options)
socket.on 'error', (err) ->
done(new Error("Failed to connect, error is: " + err.message))
socket.on 'connect', ->
done()
it "Should call userConnected with the users id and username", (done) ->
sinon.stub game, 'userConnected', ->
assert.equal(arguments[0], userId)
assert.equal(arguments[1], tempUsername)
game.userConnected.restore()
done()
socket = cio.connect(socketUrl, options)
socket.on 'error', (err) ->
done(new Error("Failed to connect, error is: " + err.message))
describe "begin", ->
it "Should be able to call game.begin", (done) ->
game = new Game()
game.init ->
game.begin()
assert true
done()
describe "automatic end", ->
it "Should end if a custom game is going for 10 seconds without anyone connecting", (done) ->
done()
it "Should end and send cancelled to players if a matchmaking game is going for 30 seconds without all players connecting", (done) ->
done()
describe "end", ->
xit "Should call when players have reported that the game has ended", (done) ->
game = new Game()
game.init ->
game.addPlayer({id: 'abc'});
game.begin()
sinon.stub(game, 'end')
game.playerFinished('abc', 15, 1);
delay 200, -> #Wait for game to finish the update loop
assert game.end.calledWith(1)
game.end.restore()
done()
xit "Should send the last tick of the game to clients", (done) ->
game = new Game()
player = null
finalTick = null
game.init ->
player = {
id: 'ppp'
socket: {
emit: -> true
}
disconnect: -> true
sendTick: sinon.stub()
}
game.players = [player]
game.end = ->
finalTick = game.get('currentTick');
game.begin()
delay 200, ->
game.playerFinished('abc', 15, 1);
delay 200, -> #Wait for game to finish update loop
assert(player.sendTick.calledWith(finalTick), "player.sendTick " + finalTick + " actual " + player.sendTick.getCall(0).arguments);
done()
describe "tutorial", ->
it "Should be able to create a tutorial", (done) ->
game = new Game()
game.init ->
game.get('settings').mode = "TUTORIAL"
done()
| 33249 | app = require('../../../lib/app.coffee')
request = require("supertest")(app)
_ = require 'lodash'
sinon = require 'sinon'
Game = require('../../../models/game.coffee')
tdb = require 'database'
User = tdb.models.User
assert = require 'assert'
sio = require('socket.io')
cio = require('socket.io-client')
xhr = require('socket.io-client/node_modules/xmlhttprequest');
xhrOriginal = require('xmlhttprequest');
passport = require('passport')
LocalStrategy = require('passport-local').Strategy
rs = require 'randomstring'
delay = (time, func) -> setTimeout(func, time)
options = {
transports: ['websocket']
'force new connection': true
}
userInfo = null
cookies = ""
game = null
global.metricsServer
overrideXmlHttpRequest = () ->
xhr.XMLHttpRequest = ->
@XMLHttpRequest = xhrOriginal.XMLHttpRequest;
xhrOriginal.XMLHttpRequest.apply(@, arguments);
this.setDisableHeaderCheck(true);
openOriginal = this.open;
this.open = (method, url, async, user, password) ->
openOriginal.apply(this, arguments);
this.setRequestHeader('cookie', cookies);
return @
overrideXmlHttpRequest()
describe "Game Model Integration Test", ->
beforeEach ->
global.io = {
set: -> true
of: -> @
on: -> @
}
describe "init", ->
it "Should be able to initialize a game", (done) ->
game = new Game()
game.init ->
done()
describe "create", ->
it "Should be able to create a new game and save it out", (done) ->
Game.create (err, game) ->
if err then return done(err)
game.save (err, result) ->
if err then return done(err)
assert result != null
done()
describe "socket authorization", ->
socketUrl = ""
userId = null
tempUsername = ""
before (done) ->
express = require('express')
passport.use(new LocalStrategy({}, (username, password, fn) ->
User.createTempUser username, (err, user) ->
userId = user.get('id')
tempUsername = user.get('username')
fn(err, user.data)
))
router = express.Router()
router.get('/user/create', passport.authenticate('local'), (req, res) ->
res.status(200).jsonp({user: req.user})
)
app.use(router)
request = require("supertest")(app)
global.io = sio.listen(15001)
global.io.set('log level', 1)
game = new Game()
game.init ->
socketUrl = 'http://0.0.0.0:15001/game/' + game.get('code')
game.bindSockets()
request.get("/user/create?username=test" + rs.generate(4) + "&password=<PASSWORD>")
.end (err, res) ->
if err then return done(err)
console.log("Res text is: " + res.text)
userInfo = JSON.parse(res.text)
cookies = res.headers['set-cookie'].pop().split(';')[0]
console.log("Cookies are: " + cookies)
done()
it "Should allow users to connect", (done) ->
socket = cio.connect(socketUrl, options)
socket.on 'error', (err) ->
done(new Error("Failed to connect, error is: " + err.message))
socket.on 'connect', ->
done()
it "Should call userConnected with the users id and username", (done) ->
sinon.stub game, 'userConnected', ->
assert.equal(arguments[0], userId)
assert.equal(arguments[1], tempUsername)
game.userConnected.restore()
done()
socket = cio.connect(socketUrl, options)
socket.on 'error', (err) ->
done(new Error("Failed to connect, error is: " + err.message))
describe "begin", ->
it "Should be able to call game.begin", (done) ->
game = new Game()
game.init ->
game.begin()
assert true
done()
describe "automatic end", ->
it "Should end if a custom game is going for 10 seconds without anyone connecting", (done) ->
done()
it "Should end and send cancelled to players if a matchmaking game is going for 30 seconds without all players connecting", (done) ->
done()
describe "end", ->
xit "Should call when players have reported that the game has ended", (done) ->
game = new Game()
game.init ->
game.addPlayer({id: 'abc'});
game.begin()
sinon.stub(game, 'end')
game.playerFinished('abc', 15, 1);
delay 200, -> #Wait for game to finish the update loop
assert game.end.calledWith(1)
game.end.restore()
done()
xit "Should send the last tick of the game to clients", (done) ->
game = new Game()
player = null
finalTick = null
game.init ->
player = {
id: 'ppp'
socket: {
emit: -> true
}
disconnect: -> true
sendTick: sinon.stub()
}
game.players = [player]
game.end = ->
finalTick = game.get('currentTick');
game.begin()
delay 200, ->
game.playerFinished('abc', 15, 1);
delay 200, -> #Wait for game to finish update loop
assert(player.sendTick.calledWith(finalTick), "player.sendTick " + finalTick + " actual " + player.sendTick.getCall(0).arguments);
done()
describe "tutorial", ->
it "Should be able to create a tutorial", (done) ->
game = new Game()
game.init ->
game.get('settings').mode = "TUTORIAL"
done()
| true | app = require('../../../lib/app.coffee')
request = require("supertest")(app)
_ = require 'lodash'
sinon = require 'sinon'
Game = require('../../../models/game.coffee')
tdb = require 'database'
User = tdb.models.User
assert = require 'assert'
sio = require('socket.io')
cio = require('socket.io-client')
xhr = require('socket.io-client/node_modules/xmlhttprequest');
xhrOriginal = require('xmlhttprequest');
passport = require('passport')
LocalStrategy = require('passport-local').Strategy
rs = require 'randomstring'
delay = (time, func) -> setTimeout(func, time)
options = {
transports: ['websocket']
'force new connection': true
}
userInfo = null
cookies = ""
game = null
global.metricsServer
overrideXmlHttpRequest = () ->
xhr.XMLHttpRequest = ->
@XMLHttpRequest = xhrOriginal.XMLHttpRequest;
xhrOriginal.XMLHttpRequest.apply(@, arguments);
this.setDisableHeaderCheck(true);
openOriginal = this.open;
this.open = (method, url, async, user, password) ->
openOriginal.apply(this, arguments);
this.setRequestHeader('cookie', cookies);
return @
overrideXmlHttpRequest()
describe "Game Model Integration Test", ->
beforeEach ->
global.io = {
set: -> true
of: -> @
on: -> @
}
describe "init", ->
it "Should be able to initialize a game", (done) ->
game = new Game()
game.init ->
done()
describe "create", ->
it "Should be able to create a new game and save it out", (done) ->
Game.create (err, game) ->
if err then return done(err)
game.save (err, result) ->
if err then return done(err)
assert result != null
done()
describe "socket authorization", ->
socketUrl = ""
userId = null
tempUsername = ""
before (done) ->
express = require('express')
passport.use(new LocalStrategy({}, (username, password, fn) ->
User.createTempUser username, (err, user) ->
userId = user.get('id')
tempUsername = user.get('username')
fn(err, user.data)
))
router = express.Router()
router.get('/user/create', passport.authenticate('local'), (req, res) ->
res.status(200).jsonp({user: req.user})
)
app.use(router)
request = require("supertest")(app)
global.io = sio.listen(15001)
global.io.set('log level', 1)
game = new Game()
game.init ->
socketUrl = 'http://0.0.0.0:15001/game/' + game.get('code')
game.bindSockets()
request.get("/user/create?username=test" + rs.generate(4) + "&password=PI:PASSWORD:<PASSWORD>END_PI")
.end (err, res) ->
if err then return done(err)
console.log("Res text is: " + res.text)
userInfo = JSON.parse(res.text)
cookies = res.headers['set-cookie'].pop().split(';')[0]
console.log("Cookies are: " + cookies)
done()
it "Should allow users to connect", (done) ->
socket = cio.connect(socketUrl, options)
socket.on 'error', (err) ->
done(new Error("Failed to connect, error is: " + err.message))
socket.on 'connect', ->
done()
it "Should call userConnected with the users id and username", (done) ->
sinon.stub game, 'userConnected', ->
assert.equal(arguments[0], userId)
assert.equal(arguments[1], tempUsername)
game.userConnected.restore()
done()
socket = cio.connect(socketUrl, options)
socket.on 'error', (err) ->
done(new Error("Failed to connect, error is: " + err.message))
describe "begin", ->
it "Should be able to call game.begin", (done) ->
game = new Game()
game.init ->
game.begin()
assert true
done()
describe "automatic end", ->
it "Should end if a custom game is going for 10 seconds without anyone connecting", (done) ->
done()
it "Should end and send cancelled to players if a matchmaking game is going for 30 seconds without all players connecting", (done) ->
done()
describe "end", ->
xit "Should call when players have reported that the game has ended", (done) ->
game = new Game()
game.init ->
game.addPlayer({id: 'abc'});
game.begin()
sinon.stub(game, 'end')
game.playerFinished('abc', 15, 1);
delay 200, -> #Wait for game to finish the update loop
assert game.end.calledWith(1)
game.end.restore()
done()
xit "Should send the last tick of the game to clients", (done) ->
game = new Game()
player = null
finalTick = null
game.init ->
player = {
id: 'ppp'
socket: {
emit: -> true
}
disconnect: -> true
sendTick: sinon.stub()
}
game.players = [player]
game.end = ->
finalTick = game.get('currentTick');
game.begin()
delay 200, ->
game.playerFinished('abc', 15, 1);
delay 200, -> #Wait for game to finish update loop
assert(player.sendTick.calledWith(finalTick), "player.sendTick " + finalTick + " actual " + player.sendTick.getCall(0).arguments);
done()
describe "tutorial", ->
it "Should be able to create a tutorial", (done) ->
game = new Game()
game.init ->
game.get('settings').mode = "TUTORIAL"
done()
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9976466298103333,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-http-write-callbacks.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")
serverEndCb = false
serverIncoming = ""
serverIncomingExpect = "bazquuxblerg"
clientEndCb = false
clientIncoming = ""
clientIncomingExpect = "asdffoobar"
process.on "exit", ->
assert serverEndCb
assert.equal serverIncoming, serverIncomingExpect
assert clientEndCb
assert.equal clientIncoming, clientIncomingExpect
console.log "ok"
return
# Verify that we get a callback when we do res.write(..., cb)
server = http.createServer((req, res) ->
res.statusCode = 400
res.end "Bad Request.\nMust send Expect:100-continue\n"
return
)
server.on "checkContinue", (req, res) ->
server.close()
assert.equal req.method, "PUT"
res.writeContinue ->
# continue has been written
req.on "end", ->
res.write "asdf", (er) ->
assert.ifError er
res.write "foo", "ascii", (er) ->
assert.ifError er
res.end new Buffer("bar"), "buffer", (er) ->
serverEndCb = true
return
return
return
return
return
req.setEncoding "ascii"
req.on "data", (c) ->
serverIncoming += c
return
return
server.listen common.PORT, ->
req = http.request(
port: common.PORT
method: "PUT"
headers:
expect: "100-continue"
)
req.on "continue", ->
# ok, good to go.
req.write "YmF6", "base64", (er) ->
assert.ifError er
req.write new Buffer("quux"), (er) ->
assert.ifError er
req.end "626c657267", "hex", (er) ->
assert.ifError er
clientEndCb = true
return
return
return
return
req.on "response", (res) ->
# this should not come until after the end is flushed out
assert clientEndCb
res.setEncoding "ascii"
res.on "data", (c) ->
clientIncoming += c
return
return
return
| 82118 | # 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")
serverEndCb = false
serverIncoming = ""
serverIncomingExpect = "bazquuxblerg"
clientEndCb = false
clientIncoming = ""
clientIncomingExpect = "asdffoobar"
process.on "exit", ->
assert serverEndCb
assert.equal serverIncoming, serverIncomingExpect
assert clientEndCb
assert.equal clientIncoming, clientIncomingExpect
console.log "ok"
return
# Verify that we get a callback when we do res.write(..., cb)
server = http.createServer((req, res) ->
res.statusCode = 400
res.end "Bad Request.\nMust send Expect:100-continue\n"
return
)
server.on "checkContinue", (req, res) ->
server.close()
assert.equal req.method, "PUT"
res.writeContinue ->
# continue has been written
req.on "end", ->
res.write "asdf", (er) ->
assert.ifError er
res.write "foo", "ascii", (er) ->
assert.ifError er
res.end new Buffer("bar"), "buffer", (er) ->
serverEndCb = true
return
return
return
return
return
req.setEncoding "ascii"
req.on "data", (c) ->
serverIncoming += c
return
return
server.listen common.PORT, ->
req = http.request(
port: common.PORT
method: "PUT"
headers:
expect: "100-continue"
)
req.on "continue", ->
# ok, good to go.
req.write "YmF6", "base64", (er) ->
assert.ifError er
req.write new Buffer("quux"), (er) ->
assert.ifError er
req.end "626c657267", "hex", (er) ->
assert.ifError er
clientEndCb = true
return
return
return
return
req.on "response", (res) ->
# this should not come until after the end is flushed out
assert clientEndCb
res.setEncoding "ascii"
res.on "data", (c) ->
clientIncoming += c
return
return
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")
serverEndCb = false
serverIncoming = ""
serverIncomingExpect = "bazquuxblerg"
clientEndCb = false
clientIncoming = ""
clientIncomingExpect = "asdffoobar"
process.on "exit", ->
assert serverEndCb
assert.equal serverIncoming, serverIncomingExpect
assert clientEndCb
assert.equal clientIncoming, clientIncomingExpect
console.log "ok"
return
# Verify that we get a callback when we do res.write(..., cb)
server = http.createServer((req, res) ->
res.statusCode = 400
res.end "Bad Request.\nMust send Expect:100-continue\n"
return
)
server.on "checkContinue", (req, res) ->
server.close()
assert.equal req.method, "PUT"
res.writeContinue ->
# continue has been written
req.on "end", ->
res.write "asdf", (er) ->
assert.ifError er
res.write "foo", "ascii", (er) ->
assert.ifError er
res.end new Buffer("bar"), "buffer", (er) ->
serverEndCb = true
return
return
return
return
return
req.setEncoding "ascii"
req.on "data", (c) ->
serverIncoming += c
return
return
server.listen common.PORT, ->
req = http.request(
port: common.PORT
method: "PUT"
headers:
expect: "100-continue"
)
req.on "continue", ->
# ok, good to go.
req.write "YmF6", "base64", (er) ->
assert.ifError er
req.write new Buffer("quux"), (er) ->
assert.ifError er
req.end "626c657267", "hex", (er) ->
assert.ifError er
clientEndCb = true
return
return
return
return
req.on "response", (res) ->
# this should not come until after the end is flushed out
assert clientEndCb
res.setEncoding "ascii"
res.on "data", (c) ->
clientIncoming += c
return
return
return
|
[
{
"context": "s file is part of the Konsserto package.\n *\n * (c) Jessym Reziga <jessym@konsserto.com>\n *\n * For the full copyrig",
"end": 74,
"score": 0.9998847842216492,
"start": 61,
"tag": "NAME",
"value": "Jessym Reziga"
},
{
"context": "f the Konsserto package.\n *\n * (c) Je... | node_modules/konsserto/lib/src/Konsserto/Bundle/TwigBundle/Extension/FunctionExtension.coffee | konsserto/konsserto | 2 | ###
* This file is part of the Konsserto package.
*
* (c) Jessym Reziga <jessym@konsserto.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
###
Security = use('/app/config/security')
TwigExtension = use('@Konsserto/Vendor/Twig/Extension/TwigExtension')
TwigFunctionMethod = use('@Konsserto/Vendor/Twig/Extension/TwigFunctionMethod')
#
# TwigFunctionExtension
#
# @author Jessym Reziga <jessym@konsserto.com>
#
class TwigFunctionExtension extends TwigExtension
constructor:(@router,@application) ->
super constructor
getFunctions:() =>
return [
{name:'echo', access: new TwigFunctionMethod(@echo)},
{name:'path', access: new TwigFunctionMethod(@path)},
{name:'asset', access: new TwigFunctionMethod(@asset)},
{name:'socket', access: new TwigFunctionMethod(@socket)},
{name:'form_start', access: new TwigFunctionMethod(@formStart)},
{name:'form_label', access: new TwigFunctionMethod(@formLabel)},
{name:'form_errors', access: new TwigFunctionMethod(@formErrors)},
{name:'form_error', access: new TwigFunctionMethod(@formError)},
{name:'form_widget', access: new TwigFunctionMethod(@formWidget)},
{name:'form_row', access: new TwigFunctionMethod(@formRow)},
{name:'form_end', access: new TwigFunctionMethod(@formEnd)},
{name:'form_rest', access: new TwigFunctionMethod(@formRest)}
]
socket:=>
return '<script src="/socket.io/socket.io.js"></script>'
echo:(str) =>
return '<pre>Echo : '+str+'</pre>'
path:(name,args) =>
return @router.generate(name,args)
asset:(file) =>
protocol = if @application.sslActive() then 'https' else 'http'
return protocol+'://'+@router.getHost()+'/web/'+file
formStart:(form,options,view) =>
return form.formStart(options,view)
formErrors:(form,view) =>
return form.formErrors(view)
formError:(form,field,view) =>
return form.formError(field,view)
formLabel:(form,field,view) =>
return form.formLabel(field,view)
formWidget:(form,field,view) =>
return if field? then form.formWidget(field,view) else form.formWidgets()
formRow:(form,field,view) =>
return form.formRow(field,view)
formEnd:(form,view) =>
return form.formEnd(view)
formRest:(form) =>
return form.formRest()
module.exports = TwigFunctionExtension | 11738 | ###
* This file is part of the Konsserto package.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
###
Security = use('/app/config/security')
TwigExtension = use('@Konsserto/Vendor/Twig/Extension/TwigExtension')
TwigFunctionMethod = use('@Konsserto/Vendor/Twig/Extension/TwigFunctionMethod')
#
# TwigFunctionExtension
#
# @author <NAME> <<EMAIL>>
#
class TwigFunctionExtension extends TwigExtension
constructor:(@router,@application) ->
super constructor
getFunctions:() =>
return [
{name:'echo', access: new TwigFunctionMethod(@echo)},
{name:'path', access: new TwigFunctionMethod(@path)},
{name:'asset', access: new TwigFunctionMethod(@asset)},
{name:'socket', access: new TwigFunctionMethod(@socket)},
{name:'form_start', access: new TwigFunctionMethod(@formStart)},
{name:'form_label', access: new TwigFunctionMethod(@formLabel)},
{name:'form_errors', access: new TwigFunctionMethod(@formErrors)},
{name:'form_error', access: new TwigFunctionMethod(@formError)},
{name:'form_widget', access: new TwigFunctionMethod(@formWidget)},
{name:'form_row', access: new TwigFunctionMethod(@formRow)},
{name:'form_end', access: new TwigFunctionMethod(@formEnd)},
{name:'form_rest', access: new TwigFunctionMethod(@formRest)}
]
socket:=>
return '<script src="/socket.io/socket.io.js"></script>'
echo:(str) =>
return '<pre>Echo : '+str+'</pre>'
path:(name,args) =>
return @router.generate(name,args)
asset:(file) =>
protocol = if @application.sslActive() then 'https' else 'http'
return protocol+'://'+@router.getHost()+'/web/'+file
formStart:(form,options,view) =>
return form.formStart(options,view)
formErrors:(form,view) =>
return form.formErrors(view)
formError:(form,field,view) =>
return form.formError(field,view)
formLabel:(form,field,view) =>
return form.formLabel(field,view)
formWidget:(form,field,view) =>
return if field? then form.formWidget(field,view) else form.formWidgets()
formRow:(form,field,view) =>
return form.formRow(field,view)
formEnd:(form,view) =>
return form.formEnd(view)
formRest:(form) =>
return form.formRest()
module.exports = TwigFunctionExtension | true | ###
* This file is part of the Konsserto package.
*
* (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
###
Security = use('/app/config/security')
TwigExtension = use('@Konsserto/Vendor/Twig/Extension/TwigExtension')
TwigFunctionMethod = use('@Konsserto/Vendor/Twig/Extension/TwigFunctionMethod')
#
# TwigFunctionExtension
#
# @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
#
class TwigFunctionExtension extends TwigExtension
constructor:(@router,@application) ->
super constructor
getFunctions:() =>
return [
{name:'echo', access: new TwigFunctionMethod(@echo)},
{name:'path', access: new TwigFunctionMethod(@path)},
{name:'asset', access: new TwigFunctionMethod(@asset)},
{name:'socket', access: new TwigFunctionMethod(@socket)},
{name:'form_start', access: new TwigFunctionMethod(@formStart)},
{name:'form_label', access: new TwigFunctionMethod(@formLabel)},
{name:'form_errors', access: new TwigFunctionMethod(@formErrors)},
{name:'form_error', access: new TwigFunctionMethod(@formError)},
{name:'form_widget', access: new TwigFunctionMethod(@formWidget)},
{name:'form_row', access: new TwigFunctionMethod(@formRow)},
{name:'form_end', access: new TwigFunctionMethod(@formEnd)},
{name:'form_rest', access: new TwigFunctionMethod(@formRest)}
]
socket:=>
return '<script src="/socket.io/socket.io.js"></script>'
echo:(str) =>
return '<pre>Echo : '+str+'</pre>'
path:(name,args) =>
return @router.generate(name,args)
asset:(file) =>
protocol = if @application.sslActive() then 'https' else 'http'
return protocol+'://'+@router.getHost()+'/web/'+file
formStart:(form,options,view) =>
return form.formStart(options,view)
formErrors:(form,view) =>
return form.formErrors(view)
formError:(form,field,view) =>
return form.formError(field,view)
formLabel:(form,field,view) =>
return form.formLabel(field,view)
formWidget:(form,field,view) =>
return if field? then form.formWidget(field,view) else form.formWidgets()
formRow:(form,field,view) =>
return form.formRow(field,view)
formEnd:(form,view) =>
return form.formEnd(view)
formRest:(form) =>
return form.formRest()
module.exports = TwigFunctionExtension |
[
{
"context": " AccessKeyId: 'KEY'\n SecretAccessKey: 'SECRET'\n SessionToken: 'TOKEN'\n Expirati",
"end": 375,
"score": 0.8467820882797241,
"start": 369,
"tag": "KEY",
"value": "SECRET"
},
{
"context": " AccessKeyId: 'KEY'\n SecretAccessKey: 'SEC... | node_modules/aws-sdk/test/services/sts.spec.coffee | jhford/aws-provisioner | 15 | helpers = require('../helpers')
AWS = helpers.AWS
require('../../lib/services/sts')
describe 'AWS.STS', ->
sts = null
beforeEach ->
sts = new AWS.STS()
describe 'credentialsFrom', ->
it 'creates a TemporaryCredentials object with hydrated data', ->
creds = sts.credentialsFrom Credentials:
AccessKeyId: 'KEY'
SecretAccessKey: 'SECRET'
SessionToken: 'TOKEN'
Expiration: new Date(0)
expect(creds instanceof AWS.TemporaryCredentials)
expect(creds.accessKeyId).toEqual('KEY')
expect(creds.secretAccessKey).toEqual('SECRET')
expect(creds.sessionToken).toEqual('TOKEN')
expect(creds.expireTime).toEqual(new Date(0))
expect(creds.expired).toEqual(false)
it 'updates an existing Credentials object with hydrated data', ->
data = Credentials:
AccessKeyId: 'KEY'
SecretAccessKey: 'SECRET'
SessionToken: 'TOKEN'
Expiration: new Date(0)
creds = new AWS.Credentials
sts.credentialsFrom(data, creds)
expect(creds instanceof AWS.Credentials)
expect(creds.accessKeyId).toEqual('KEY')
expect(creds.secretAccessKey).toEqual('SECRET')
expect(creds.sessionToken).toEqual('TOKEN')
expect(creds.expireTime).toEqual(new Date(0))
expect(creds.expired).toEqual(false)
describe 'assumeRoleWithWebIdentity', ->
service = new AWS.STS
it 'sends an unsigned GET request (params in query string)', ->
helpers.mockHttpResponse 200, {}, '{}'
params = RoleArn: 'ARN', RoleSessionName: 'NAME', WebIdentityToken: 'TOK'
service.assumeRoleWithWebIdentity params, ->
hr = @request.httpRequest
expect(hr.method).toEqual('GET')
expect(hr.body).toEqual('')
expect(hr.headers['Authorization']).toEqual(undefined)
expect(hr.headers['Content-Type']).toEqual(undefined)
expect(hr.path).toEqual('/?Action=AssumeRoleWithWebIdentity&' +
'RoleArn=ARN&RoleSessionName=NAME&Version=' +
service.api.apiVersion + '&WebIdentityToken=TOK')
describe 'assumeRoleWithSAML', ->
service = new AWS.STS
it 'sends an unsigned GET request (params in query string)', ->
helpers.mockHttpResponse 200, {}, '{}'
params = RoleArn: 'ARN', PrincipalArn: 'PARN', SAMLAssertion: 'OK'
service.assumeRoleWithSAML params, ->
hr = @request.httpRequest
expect(hr.method).toEqual('GET')
expect(hr.body).toEqual('')
expect(hr.headers['Authorization']).toEqual(undefined)
expect(hr.headers['Content-Type']).toEqual(undefined)
expect(hr.path).toEqual('/?Action=AssumeRoleWithSAML&' +
'PrincipalArn=PARN&RoleArn=ARN&SAMLAssertion=OK&' +
'Version=' + service.api.apiVersion)
| 10198 | helpers = require('../helpers')
AWS = helpers.AWS
require('../../lib/services/sts')
describe 'AWS.STS', ->
sts = null
beforeEach ->
sts = new AWS.STS()
describe 'credentialsFrom', ->
it 'creates a TemporaryCredentials object with hydrated data', ->
creds = sts.credentialsFrom Credentials:
AccessKeyId: 'KEY'
SecretAccessKey: '<KEY>'
SessionToken: 'TOKEN'
Expiration: new Date(0)
expect(creds instanceof AWS.TemporaryCredentials)
expect(creds.accessKeyId).toEqual('KEY')
expect(creds.secretAccessKey).toEqual('SECRET')
expect(creds.sessionToken).toEqual('TOKEN')
expect(creds.expireTime).toEqual(new Date(0))
expect(creds.expired).toEqual(false)
it 'updates an existing Credentials object with hydrated data', ->
data = Credentials:
AccessKeyId: 'KEY'
SecretAccessKey: '<KEY>'
SessionToken: 'TOKEN'
Expiration: new Date(0)
creds = new AWS.Credentials
sts.credentialsFrom(data, creds)
expect(creds instanceof AWS.Credentials)
expect(creds.accessKeyId).toEqual('KEY')
expect(creds.secretAccessKey).toEqual('SECRET')
expect(creds.sessionToken).toEqual('TOKEN')
expect(creds.expireTime).toEqual(new Date(0))
expect(creds.expired).toEqual(false)
describe 'assumeRoleWithWebIdentity', ->
service = new AWS.STS
it 'sends an unsigned GET request (params in query string)', ->
helpers.mockHttpResponse 200, {}, '{}'
params = RoleArn: 'ARN', RoleSessionName: 'NAME', WebIdentityToken: 'TOK'
service.assumeRoleWithWebIdentity params, ->
hr = @request.httpRequest
expect(hr.method).toEqual('GET')
expect(hr.body).toEqual('')
expect(hr.headers['Authorization']).toEqual(undefined)
expect(hr.headers['Content-Type']).toEqual(undefined)
expect(hr.path).toEqual('/?Action=AssumeRoleWithWebIdentity&' +
'RoleArn=ARN&RoleSessionName=NAME&Version=' +
service.api.apiVersion + '&WebIdentityToken=TOK')
describe 'assumeRoleWithSAML', ->
service = new AWS.STS
it 'sends an unsigned GET request (params in query string)', ->
helpers.mockHttpResponse 200, {}, '{}'
params = RoleArn: 'ARN', PrincipalArn: '<KEY>N', SAMLAssertion: 'OK'
service.assumeRoleWithSAML params, ->
hr = @request.httpRequest
expect(hr.method).toEqual('GET')
expect(hr.body).toEqual('')
expect(hr.headers['Authorization']).toEqual(undefined)
expect(hr.headers['Content-Type']).toEqual(undefined)
expect(hr.path).toEqual('/?Action=AssumeRoleWithSAML&' +
'PrincipalArn=PARN&RoleArn=ARN&SAMLAssertion=OK&' +
'Version=' + service.api.apiVersion)
| true | helpers = require('../helpers')
AWS = helpers.AWS
require('../../lib/services/sts')
describe 'AWS.STS', ->
sts = null
beforeEach ->
sts = new AWS.STS()
describe 'credentialsFrom', ->
it 'creates a TemporaryCredentials object with hydrated data', ->
creds = sts.credentialsFrom Credentials:
AccessKeyId: 'KEY'
SecretAccessKey: 'PI:KEY:<KEY>END_PI'
SessionToken: 'TOKEN'
Expiration: new Date(0)
expect(creds instanceof AWS.TemporaryCredentials)
expect(creds.accessKeyId).toEqual('KEY')
expect(creds.secretAccessKey).toEqual('SECRET')
expect(creds.sessionToken).toEqual('TOKEN')
expect(creds.expireTime).toEqual(new Date(0))
expect(creds.expired).toEqual(false)
it 'updates an existing Credentials object with hydrated data', ->
data = Credentials:
AccessKeyId: 'KEY'
SecretAccessKey: 'PI:KEY:<KEY>END_PI'
SessionToken: 'TOKEN'
Expiration: new Date(0)
creds = new AWS.Credentials
sts.credentialsFrom(data, creds)
expect(creds instanceof AWS.Credentials)
expect(creds.accessKeyId).toEqual('KEY')
expect(creds.secretAccessKey).toEqual('SECRET')
expect(creds.sessionToken).toEqual('TOKEN')
expect(creds.expireTime).toEqual(new Date(0))
expect(creds.expired).toEqual(false)
describe 'assumeRoleWithWebIdentity', ->
service = new AWS.STS
it 'sends an unsigned GET request (params in query string)', ->
helpers.mockHttpResponse 200, {}, '{}'
params = RoleArn: 'ARN', RoleSessionName: 'NAME', WebIdentityToken: 'TOK'
service.assumeRoleWithWebIdentity params, ->
hr = @request.httpRequest
expect(hr.method).toEqual('GET')
expect(hr.body).toEqual('')
expect(hr.headers['Authorization']).toEqual(undefined)
expect(hr.headers['Content-Type']).toEqual(undefined)
expect(hr.path).toEqual('/?Action=AssumeRoleWithWebIdentity&' +
'RoleArn=ARN&RoleSessionName=NAME&Version=' +
service.api.apiVersion + '&WebIdentityToken=TOK')
describe 'assumeRoleWithSAML', ->
service = new AWS.STS
it 'sends an unsigned GET request (params in query string)', ->
helpers.mockHttpResponse 200, {}, '{}'
params = RoleArn: 'ARN', PrincipalArn: 'PI:KEY:<KEY>END_PIN', SAMLAssertion: 'OK'
service.assumeRoleWithSAML params, ->
hr = @request.httpRequest
expect(hr.method).toEqual('GET')
expect(hr.body).toEqual('')
expect(hr.headers['Authorization']).toEqual(undefined)
expect(hr.headers['Content-Type']).toEqual(undefined)
expect(hr.path).toEqual('/?Action=AssumeRoleWithSAML&' +
'PrincipalArn=PARN&RoleArn=ARN&SAMLAssertion=OK&' +
'Version=' + service.api.apiVersion)
|
[
{
"context": "tNormalJoe = (done, force) ->\n unittest.getUser('Joe', 'normal@jo.com', 'food', done, force)\nunittest.",
"end": 2340,
"score": 0.8700928688049316,
"start": 2337,
"tag": "USERNAME",
"value": "Joe"
},
{
"context": "Joe = (done, force) ->\n unittest.getUser('Joe', 'nor... | test/server/common.coffee | pougounias/codecombat | 0 | # import this at the top of every file so we're not juggling connections
# and common libraries are available
console.log 'IT BEGINS'
require 'jasmine-spec-reporter'
jasmine.getEnv().defaultTimeoutInterval = 300000
jasmine.getEnv().reporter.subReporters_ = []
jasmine.getEnv().addReporter(new jasmine.SpecReporter({
displayFailedSpec: true
displayPendingSpec: true
displaySpecDuration: true
displaySuccessfulSpec: true
}))
rep = new jasmine.JsApiReporter()
jasmine.getEnv().addReporter(rep)
GLOBAL._ = require 'lodash'
_.str = require 'underscore.string'
_.mixin(_.str.exports())
GLOBAL.mongoose = require 'mongoose'
mongoose.connect('mongodb://localhost/coco_unittest')
path = require 'path'
GLOBAL.testing = true
GLOBAL.tv4 = require 'tv4' # required for TreemaUtils to work
models_path = [
'../../server/analytics/AnalyticsUsersActive'
'../../server/articles/Article'
'../../server/campaigns/Campaign'
'../../server/clans/Clan'
'../../server/levels/Level'
'../../server/levels/components/LevelComponent'
'../../server/levels/systems/LevelSystem'
'../../server/levels/sessions/LevelSession'
'../../server/levels/thangs/LevelThangType'
'../../server/users/User'
'../../server/patches/Patch'
'../../server/achievements/Achievement'
'../../server/achievements/EarnedAchievement'
'../../server/payments/Payment'
'../../server/prepaids/Prepaid'
]
for m in models_path
model = path.basename(m)
#console.log('model=' + model)
GLOBAL[model] = require m
async = require 'async'
GLOBAL.clearModels = (models, done) ->
funcs = []
for model in models
if model is User
unittest.users = {}
wrapped = (m) -> (callback) ->
m.remove {}, (err) ->
callback(err, true)
funcs.push(wrapped(model))
async.parallel funcs, (err, results) ->
done(err)
GLOBAL.saveModels = (models, done) ->
funcs = []
for model in models
wrapped = (m) -> (callback) ->
m.save (err) ->
callback(err, true)
funcs.push(wrapped(model))
async.parallel funcs, (err, results) ->
done(err)
GLOBAL.simplePermissions = [target: 'public', access: 'owner']
GLOBAL.ObjectId = mongoose.Types.ObjectId
GLOBAL.request = require 'request'
GLOBAL.unittest = {}
unittest.users = unittest.users or {}
unittest.getNormalJoe = (done, force) ->
unittest.getUser('Joe', 'normal@jo.com', 'food', done, force)
unittest.getOtherSam = (done, force) ->
unittest.getUser('Sam', 'other@sam.com', 'beer', done, force)
unittest.getAdmin = (done, force) ->
unittest.getUser('Admin', 'admin@afc.com', '80yqxpb38j', done, force)
unittest.getUser = (name, email, password, done, force) ->
# Creates the user if it doesn't already exist.
return done(unittest.users[email]) if unittest.users[email] and not force
request = require 'request'
request.post getURL('/auth/logout'), ->
request.get getURL('/auth/whoami'), ->
req = request.post(getURL('/db/user'), (err, response, body) ->
throw err if err
User.findOne({email: email}).exec((err, user) ->
user.set('permissions', if password is '80yqxpb38j' then ['admin'] else [])
user.set('name', name)
user.save (err) ->
wrapUpGetUser(email, user, done)
)
)
form = req.form()
form.append('email', email)
form.append('password', password)
wrapUpGetUser = (email, user, done) ->
unittest.users[email] = user
return done(unittest.users[email])
GLOBAL.getURL = (path) ->
return 'http://localhost:3001' + path
GLOBAL.createPrepaid = (type, done) ->
options = uri: GLOBAL.getURL('/db/prepaid/-/create')
options.json = type: type if type?
request.post options, done
newUserCount = 0
GLOBAL.createNewUser = (done) ->
name = password = "user#{newUserCount++}"
email = "#{name}@foo.bar"
unittest.getUser name, email, password, done, true
GLOBAL.loginNewUser = (done) ->
name = password = "user#{newUserCount++}"
email = "#{name}@me.com"
request.post getURL('/auth/logout'), ->
unittest.getUser name, email, password, (user) ->
req = request.post(getURL('/auth/login'), (error, response) ->
expect(response.statusCode).toBe(200)
done(user)
)
form = req.form()
form.append('username', email)
form.append('password', password)
, true
GLOBAL.loginJoe = (done) ->
request.post getURL('/auth/logout'), ->
unittest.getNormalJoe (user) ->
req = request.post(getURL('/auth/login'), (error, response) ->
expect(response.statusCode).toBe(200)
done(user)
)
form = req.form()
form.append('username', 'normal@jo.com')
form.append('password', 'food')
GLOBAL.loginSam = (done) ->
request.post getURL('/auth/logout'), ->
unittest.getOtherSam (user) ->
req = request.post(getURL('/auth/login'), (error, response) ->
expect(response.statusCode).toBe(200)
done(user)
)
form = req.form()
form.append('username', 'other@sam.com')
form.append('password', 'beer')
GLOBAL.loginAdmin = (done) ->
request.post getURL('/auth/logout'), ->
unittest.getAdmin (user) ->
req = request.post(getURL('/auth/login'), (error, response) ->
expect(response.statusCode).toBe(200)
done(user)
)
form = req.form()
form.append('username', 'admin@afc.com')
form.append('password', '80yqxpb38j')
# find some other way to make the admin object an admin... maybe directly?
GLOBAL.loginUser = (user, done) ->
request.post getURL('/auth/logout'), ->
req = request.post(getURL('/auth/login'), (error, response) ->
expect(response.statusCode).toBe(200)
done(user)
)
form = req.form()
form.append('username', user.get('email'))
form.append('password', user.get('name'))
GLOBAL.logoutUser = (done) ->
request.post getURL('/auth/logout'), ->
done()
GLOBAL.dropGridFS = (done) ->
if mongoose.connection.readyState is 2
mongoose.connection.once 'open', ->
_drop(done)
else
_drop(done)
_drop = (done) ->
files = mongoose.connection.db.collection('media.files')
files.remove {}, ->
chunks = mongoose.connection.db.collection('media.chunks')
chunks.remove {}, ->
done()
tickInterval = null
tick = ->
# When you want jasmine-node to exit after running the tests,
# you have to close the connection first.
if rep.finished
mongoose.disconnect()
clearTimeout tickInterval
tickInterval = setInterval tick, 1000
| 36263 | # import this at the top of every file so we're not juggling connections
# and common libraries are available
console.log 'IT BEGINS'
require 'jasmine-spec-reporter'
jasmine.getEnv().defaultTimeoutInterval = 300000
jasmine.getEnv().reporter.subReporters_ = []
jasmine.getEnv().addReporter(new jasmine.SpecReporter({
displayFailedSpec: true
displayPendingSpec: true
displaySpecDuration: true
displaySuccessfulSpec: true
}))
rep = new jasmine.JsApiReporter()
jasmine.getEnv().addReporter(rep)
GLOBAL._ = require 'lodash'
_.str = require 'underscore.string'
_.mixin(_.str.exports())
GLOBAL.mongoose = require 'mongoose'
mongoose.connect('mongodb://localhost/coco_unittest')
path = require 'path'
GLOBAL.testing = true
GLOBAL.tv4 = require 'tv4' # required for TreemaUtils to work
models_path = [
'../../server/analytics/AnalyticsUsersActive'
'../../server/articles/Article'
'../../server/campaigns/Campaign'
'../../server/clans/Clan'
'../../server/levels/Level'
'../../server/levels/components/LevelComponent'
'../../server/levels/systems/LevelSystem'
'../../server/levels/sessions/LevelSession'
'../../server/levels/thangs/LevelThangType'
'../../server/users/User'
'../../server/patches/Patch'
'../../server/achievements/Achievement'
'../../server/achievements/EarnedAchievement'
'../../server/payments/Payment'
'../../server/prepaids/Prepaid'
]
for m in models_path
model = path.basename(m)
#console.log('model=' + model)
GLOBAL[model] = require m
async = require 'async'
GLOBAL.clearModels = (models, done) ->
funcs = []
for model in models
if model is User
unittest.users = {}
wrapped = (m) -> (callback) ->
m.remove {}, (err) ->
callback(err, true)
funcs.push(wrapped(model))
async.parallel funcs, (err, results) ->
done(err)
GLOBAL.saveModels = (models, done) ->
funcs = []
for model in models
wrapped = (m) -> (callback) ->
m.save (err) ->
callback(err, true)
funcs.push(wrapped(model))
async.parallel funcs, (err, results) ->
done(err)
GLOBAL.simplePermissions = [target: 'public', access: 'owner']
GLOBAL.ObjectId = mongoose.Types.ObjectId
GLOBAL.request = require 'request'
GLOBAL.unittest = {}
unittest.users = unittest.users or {}
unittest.getNormalJoe = (done, force) ->
unittest.getUser('Joe', '<EMAIL>', 'food', done, force)
unittest.getOtherSam = (done, force) ->
unittest.getUser('<NAME>', '<EMAIL>', 'beer', done, force)
unittest.getAdmin = (done, force) ->
unittest.getUser('Admin', '<EMAIL>', '<PASSWORD>', done, force)
unittest.getUser = (name, email, password, done, force) ->
# Creates the user if it doesn't already exist.
return done(unittest.users[email]) if unittest.users[email] and not force
request = require 'request'
request.post getURL('/auth/logout'), ->
request.get getURL('/auth/whoami'), ->
req = request.post(getURL('/db/user'), (err, response, body) ->
throw err if err
User.findOne({email: email}).exec((err, user) ->
user.set('permissions', if password is '<PASSWORD>' then ['admin'] else [])
user.set('name', name)
user.save (err) ->
wrapUpGetUser(email, user, done)
)
)
form = req.form()
form.append('email', email)
form.append('password', password)
wrapUpGetUser = (email, user, done) ->
unittest.users[email] = user
return done(unittest.users[email])
GLOBAL.getURL = (path) ->
return 'http://localhost:3001' + path
GLOBAL.createPrepaid = (type, done) ->
options = uri: GLOBAL.getURL('/db/prepaid/-/create')
options.json = type: type if type?
request.post options, done
newUserCount = 0
GLOBAL.createNewUser = (done) ->
name = password = "<PASSWORD>++}"
email = <EMAIL>"
unittest.getUser name, email, password, done, true
GLOBAL.loginNewUser = (done) ->
name = password = "<PASSWORD>++}"
email = <EMAIL>"
request.post getURL('/auth/logout'), ->
unittest.getUser name, email, password, (user) ->
req = request.post(getURL('/auth/login'), (error, response) ->
expect(response.statusCode).toBe(200)
done(user)
)
form = req.form()
form.append('username', email)
form.append('password', <PASSWORD>)
, true
GLOBAL.loginJoe = (done) ->
request.post getURL('/auth/logout'), ->
unittest.getNormalJoe (user) ->
req = request.post(getURL('/auth/login'), (error, response) ->
expect(response.statusCode).toBe(200)
done(user)
)
form = req.form()
form.append('username', '<EMAIL>')
form.append('password', '<PASSWORD>')
GLOBAL.loginSam = (done) ->
request.post getURL('/auth/logout'), ->
unittest.getOtherSam (user) ->
req = request.post(getURL('/auth/login'), (error, response) ->
expect(response.statusCode).toBe(200)
done(user)
)
form = req.form()
form.append('username', '<EMAIL>')
form.append('password', '<PASSWORD>')
GLOBAL.loginAdmin = (done) ->
request.post getURL('/auth/logout'), ->
unittest.getAdmin (user) ->
req = request.post(getURL('/auth/login'), (error, response) ->
expect(response.statusCode).toBe(200)
done(user)
)
form = req.form()
form.append('username', '<EMAIL>')
form.append('password', '<PASSWORD>')
# find some other way to make the admin object an admin... maybe directly?
GLOBAL.loginUser = (user, done) ->
request.post getURL('/auth/logout'), ->
req = request.post(getURL('/auth/login'), (error, response) ->
expect(response.statusCode).toBe(200)
done(user)
)
form = req.form()
form.append('username', user.get('email'))
form.append('password', user.get('name'))
GLOBAL.logoutUser = (done) ->
request.post getURL('/auth/logout'), ->
done()
GLOBAL.dropGridFS = (done) ->
if mongoose.connection.readyState is 2
mongoose.connection.once 'open', ->
_drop(done)
else
_drop(done)
_drop = (done) ->
files = mongoose.connection.db.collection('media.files')
files.remove {}, ->
chunks = mongoose.connection.db.collection('media.chunks')
chunks.remove {}, ->
done()
tickInterval = null
tick = ->
# When you want jasmine-node to exit after running the tests,
# you have to close the connection first.
if rep.finished
mongoose.disconnect()
clearTimeout tickInterval
tickInterval = setInterval tick, 1000
| true | # import this at the top of every file so we're not juggling connections
# and common libraries are available
console.log 'IT BEGINS'
require 'jasmine-spec-reporter'
jasmine.getEnv().defaultTimeoutInterval = 300000
jasmine.getEnv().reporter.subReporters_ = []
jasmine.getEnv().addReporter(new jasmine.SpecReporter({
displayFailedSpec: true
displayPendingSpec: true
displaySpecDuration: true
displaySuccessfulSpec: true
}))
rep = new jasmine.JsApiReporter()
jasmine.getEnv().addReporter(rep)
GLOBAL._ = require 'lodash'
_.str = require 'underscore.string'
_.mixin(_.str.exports())
GLOBAL.mongoose = require 'mongoose'
mongoose.connect('mongodb://localhost/coco_unittest')
path = require 'path'
GLOBAL.testing = true
GLOBAL.tv4 = require 'tv4' # required for TreemaUtils to work
models_path = [
'../../server/analytics/AnalyticsUsersActive'
'../../server/articles/Article'
'../../server/campaigns/Campaign'
'../../server/clans/Clan'
'../../server/levels/Level'
'../../server/levels/components/LevelComponent'
'../../server/levels/systems/LevelSystem'
'../../server/levels/sessions/LevelSession'
'../../server/levels/thangs/LevelThangType'
'../../server/users/User'
'../../server/patches/Patch'
'../../server/achievements/Achievement'
'../../server/achievements/EarnedAchievement'
'../../server/payments/Payment'
'../../server/prepaids/Prepaid'
]
for m in models_path
model = path.basename(m)
#console.log('model=' + model)
GLOBAL[model] = require m
async = require 'async'
GLOBAL.clearModels = (models, done) ->
funcs = []
for model in models
if model is User
unittest.users = {}
wrapped = (m) -> (callback) ->
m.remove {}, (err) ->
callback(err, true)
funcs.push(wrapped(model))
async.parallel funcs, (err, results) ->
done(err)
GLOBAL.saveModels = (models, done) ->
funcs = []
for model in models
wrapped = (m) -> (callback) ->
m.save (err) ->
callback(err, true)
funcs.push(wrapped(model))
async.parallel funcs, (err, results) ->
done(err)
GLOBAL.simplePermissions = [target: 'public', access: 'owner']
GLOBAL.ObjectId = mongoose.Types.ObjectId
GLOBAL.request = require 'request'
GLOBAL.unittest = {}
unittest.users = unittest.users or {}
unittest.getNormalJoe = (done, force) ->
unittest.getUser('Joe', 'PI:EMAIL:<EMAIL>END_PI', 'food', done, force)
unittest.getOtherSam = (done, force) ->
unittest.getUser('PI:NAME:<NAME>END_PI', 'PI:EMAIL:<EMAIL>END_PI', 'beer', done, force)
unittest.getAdmin = (done, force) ->
unittest.getUser('Admin', 'PI:EMAIL:<EMAIL>END_PI', 'PI:PASSWORD:<PASSWORD>END_PI', done, force)
unittest.getUser = (name, email, password, done, force) ->
# Creates the user if it doesn't already exist.
return done(unittest.users[email]) if unittest.users[email] and not force
request = require 'request'
request.post getURL('/auth/logout'), ->
request.get getURL('/auth/whoami'), ->
req = request.post(getURL('/db/user'), (err, response, body) ->
throw err if err
User.findOne({email: email}).exec((err, user) ->
user.set('permissions', if password is 'PI:PASSWORD:<PASSWORD>END_PI' then ['admin'] else [])
user.set('name', name)
user.save (err) ->
wrapUpGetUser(email, user, done)
)
)
form = req.form()
form.append('email', email)
form.append('password', password)
wrapUpGetUser = (email, user, done) ->
unittest.users[email] = user
return done(unittest.users[email])
GLOBAL.getURL = (path) ->
return 'http://localhost:3001' + path
GLOBAL.createPrepaid = (type, done) ->
options = uri: GLOBAL.getURL('/db/prepaid/-/create')
options.json = type: type if type?
request.post options, done
newUserCount = 0
GLOBAL.createNewUser = (done) ->
name = password = "PI:PASSWORD:<PASSWORD>END_PI++}"
email = PI:EMAIL:<EMAIL>END_PI"
unittest.getUser name, email, password, done, true
GLOBAL.loginNewUser = (done) ->
name = password = "PI:PASSWORD:<PASSWORD>END_PI++}"
email = PI:EMAIL:<EMAIL>END_PI"
request.post getURL('/auth/logout'), ->
unittest.getUser name, email, password, (user) ->
req = request.post(getURL('/auth/login'), (error, response) ->
expect(response.statusCode).toBe(200)
done(user)
)
form = req.form()
form.append('username', email)
form.append('password', PI:PASSWORD:<PASSWORD>END_PI)
, true
GLOBAL.loginJoe = (done) ->
request.post getURL('/auth/logout'), ->
unittest.getNormalJoe (user) ->
req = request.post(getURL('/auth/login'), (error, response) ->
expect(response.statusCode).toBe(200)
done(user)
)
form = req.form()
form.append('username', 'PI:EMAIL:<EMAIL>END_PI')
form.append('password', 'PI:PASSWORD:<PASSWORD>END_PI')
GLOBAL.loginSam = (done) ->
request.post getURL('/auth/logout'), ->
unittest.getOtherSam (user) ->
req = request.post(getURL('/auth/login'), (error, response) ->
expect(response.statusCode).toBe(200)
done(user)
)
form = req.form()
form.append('username', 'PI:EMAIL:<EMAIL>END_PI')
form.append('password', 'PI:PASSWORD:<PASSWORD>END_PI')
GLOBAL.loginAdmin = (done) ->
request.post getURL('/auth/logout'), ->
unittest.getAdmin (user) ->
req = request.post(getURL('/auth/login'), (error, response) ->
expect(response.statusCode).toBe(200)
done(user)
)
form = req.form()
form.append('username', 'PI:EMAIL:<EMAIL>END_PI')
form.append('password', 'PI:PASSWORD:<PASSWORD>END_PI')
# find some other way to make the admin object an admin... maybe directly?
GLOBAL.loginUser = (user, done) ->
request.post getURL('/auth/logout'), ->
req = request.post(getURL('/auth/login'), (error, response) ->
expect(response.statusCode).toBe(200)
done(user)
)
form = req.form()
form.append('username', user.get('email'))
form.append('password', user.get('name'))
GLOBAL.logoutUser = (done) ->
request.post getURL('/auth/logout'), ->
done()
GLOBAL.dropGridFS = (done) ->
if mongoose.connection.readyState is 2
mongoose.connection.once 'open', ->
_drop(done)
else
_drop(done)
_drop = (done) ->
files = mongoose.connection.db.collection('media.files')
files.remove {}, ->
chunks = mongoose.connection.db.collection('media.chunks')
chunks.remove {}, ->
done()
tickInterval = null
tick = ->
# When you want jasmine-node to exit after running the tests,
# you have to close the connection first.
if rep.finished
mongoose.disconnect()
clearTimeout tickInterval
tickInterval = setInterval tick, 1000
|
[
{
"context": "subteams are working in these tests.\n\nusers: {\n \"herb\": {}\n \"basil\":\n keys:\n default:\n ",
"end": 298,
"score": 0.9924757480621338,
"start": 294,
"tag": "USERNAME",
"value": "herb"
},
{
"context": "working in these tests.\n\nusers: {\n \"herb... | teamchains/inputs/stub_by_revoked.iced | keybase/keybase-test-vectors | 4 | description: "stub a chain link signed by a revoked device, thus invalid"
# Note: this test doesn't actually test inflating.
# Because the loader throws out the whole cache when need_admin turns on.
# This test could be adapted to inflate when subteams are working in these tests.
users: {
"herb": {}
"basil":
keys:
default:
revoke:
seqno: 1
merkle_hashmeta: 1500 # after link 1
}
teams: {
"cabal": {
links: [
type: "root"
signer: "basil"
members:
owner: ["basil"]
admin: ["herb"]
merkle_hashmetas: [1500] # at these hashmetas, the team chain pointed here
,
# invalid link - signed by a revoked device
type: "invite"
signer: "basil"
invites:
writer: [ {
id: "54eafff3400b5bcd8b40bff3d225ab27",
name: "max+be6ef086a4a5@keyba.se",
type: "email"
} ]
,
type: "rotate_key"
signer: "herb"
]
}
}
sessions: [
loads: [
need_admin: true
error: true
error_type: "ProofError"
error_substr: "team link before user key revocation"
]
,
loads: [
stub: [2] # Stub these seqnos
n_stubbed: 1
# signer isn't checked yet for the stubbed link
,
need_admin: true
error: true
error_type: "ProofError"
error_substr: "team link before user key revocation"
# now the link is inflated and the signer is checked
]
,
loads: [
upto: 2
stub: [2] # Stub these seqnos
,
need_admin: true
error: true
error_type: "ProofError"
error_substr: "team link before user key revocation"
]
,
loads: [
upto: 2
error: true
error_type: "ProofError"
error_substr: "team link before user key revocation"
]
,
loads: [
upto: 1
,
upto: 2
stub: [2] # Stub these seqnos
,
need_admin: true
n_stubbed: 0
error: true
error_type: "ProofError"
error_substr: "team link before user key revocation"
]
]
| 225217 | description: "stub a chain link signed by a revoked device, thus invalid"
# Note: this test doesn't actually test inflating.
# Because the loader throws out the whole cache when need_admin turns on.
# This test could be adapted to inflate when subteams are working in these tests.
users: {
"herb": {}
"basil":
keys:
default:
revoke:
seqno: 1
merkle_hashmeta: 1500 # after link 1
}
teams: {
"cabal": {
links: [
type: "root"
signer: "basil"
members:
owner: ["basil"]
admin: ["herb"]
merkle_hashmetas: [1500] # at these hashmetas, the team chain pointed here
,
# invalid link - signed by a revoked device
type: "invite"
signer: "basil"
invites:
writer: [ {
id: "<KEY> <PASSWORD>",
name: "<EMAIL>",
type: "email"
} ]
,
type: "rotate_key"
signer: "herb"
]
}
}
sessions: [
loads: [
need_admin: true
error: true
error_type: "ProofError"
error_substr: "team link before user key revocation"
]
,
loads: [
stub: [2] # Stub these seqnos
n_stubbed: 1
# signer isn't checked yet for the stubbed link
,
need_admin: true
error: true
error_type: "ProofError"
error_substr: "team link before user key revocation"
# now the link is inflated and the signer is checked
]
,
loads: [
upto: 2
stub: [2] # Stub these seqnos
,
need_admin: true
error: true
error_type: "ProofError"
error_substr: "team link before user key revocation"
]
,
loads: [
upto: 2
error: true
error_type: "ProofError"
error_substr: "team link before user key revocation"
]
,
loads: [
upto: 1
,
upto: 2
stub: [2] # Stub these seqnos
,
need_admin: true
n_stubbed: 0
error: true
error_type: "ProofError"
error_substr: "team link before user key revocation"
]
]
| true | description: "stub a chain link signed by a revoked device, thus invalid"
# Note: this test doesn't actually test inflating.
# Because the loader throws out the whole cache when need_admin turns on.
# This test could be adapted to inflate when subteams are working in these tests.
users: {
"herb": {}
"basil":
keys:
default:
revoke:
seqno: 1
merkle_hashmeta: 1500 # after link 1
}
teams: {
"cabal": {
links: [
type: "root"
signer: "basil"
members:
owner: ["basil"]
admin: ["herb"]
merkle_hashmetas: [1500] # at these hashmetas, the team chain pointed here
,
# invalid link - signed by a revoked device
type: "invite"
signer: "basil"
invites:
writer: [ {
id: "PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI",
name: "PI:EMAIL:<EMAIL>END_PI",
type: "email"
} ]
,
type: "rotate_key"
signer: "herb"
]
}
}
sessions: [
loads: [
need_admin: true
error: true
error_type: "ProofError"
error_substr: "team link before user key revocation"
]
,
loads: [
stub: [2] # Stub these seqnos
n_stubbed: 1
# signer isn't checked yet for the stubbed link
,
need_admin: true
error: true
error_type: "ProofError"
error_substr: "team link before user key revocation"
# now the link is inflated and the signer is checked
]
,
loads: [
upto: 2
stub: [2] # Stub these seqnos
,
need_admin: true
error: true
error_type: "ProofError"
error_substr: "team link before user key revocation"
]
,
loads: [
upto: 2
error: true
error_type: "ProofError"
error_substr: "team link before user key revocation"
]
,
loads: [
upto: 1
,
upto: 2
stub: [2] # Stub these seqnos
,
need_admin: true
n_stubbed: 0
error: true
error_type: "ProofError"
error_substr: "team link before user key revocation"
]
]
|
[
{
"context": "de wrapper around Node.js net library\n#\n# (C) 2011 Tristan Slominski\n#\nanode = require '../lib/anode'\nnodenet = requir",
"end": 88,
"score": 0.9996618032455444,
"start": 71,
"tag": "NAME",
"value": "Tristan Slominski"
}
] | src/net.coffee | tristanls/anodejs | 3 | #
# net.coffee : anode wrapper around Node.js net library
#
# (C) 2011 Tristan Slominski
#
anode = require '../lib/anode'
nodenet = require 'net'
#
# Initialized net server behavior wrapped around a created server
#
initializedServer_beh = anode.beh 'server'
'cust, #address' : ->
@send( @, '#address', @server.address() ).to @cust
'cust, #close' : ->
__cust = @cust
__send = @send
__server = @
if @cust # ack requested
@server.on 'close', ( had_error ) ->
__send( __server, '#close' ).to __cust
@server.close()
'cust, #connections' : ->
@send( @, '#connections', @server.connections ).to @cust
'cust, #maxConnections, [num]' : ->
if @num # setter
@server.maxConnections = @num
if @cust # ack requested
@send( @, '#maxConnections' ).to @cust
else # getter
@send( @, '#maxConnections', @server.maxConnections ).to @cust
'cust, #pause, msecs' : ->
@server.pause @msecs
if @cust # ack requested
@send( @, '#pause' ).to @cust
#
# An uninitialized net server beh that will lazy-initialize the server
# and then become initialized net server beh
#
uninitializedServer_beh = anode.beh
# creates the server and attempts to listen on given port and host
'cust, #listen, port, [host], [options]' : ->
# local aliases for use inside closures
__create = @create
__cust = @cust
__net = @
__send = @send
if @options
server = nodenet.createServer @options
else
server = nodenet.createServer()
if @cust # ack requested
__callback = ->
__send( __net, '#listen' ).to __cust
# all server event bindings need to happen before nextTick
server.on 'close', ->
__send( __net, '#close' ).to __cust
server.on 'connection', ( socket ) ->
socket_actor = __create 'socket', socket_beh __cust, socket
# all socket bindings need to happen before nextTick
socket.on 'close', ( had_error ) ->
__send( socket, '#close', had_error ).to socket_actor
socket.on 'connect', ->
__send( socket, '#connect' ).to socket_actor
socket.on 'data', ( data ) ->
__send( socket, '#data', data ).to socket_actor
socket.on 'drain', ->
__send( socket, '#drain' ).to socket_actor
socket.on 'end', ->
__send( socket, '#end' ).to socket_actor
socket.on 'error', ( exception ) ->
__send( socket, '#error', exception ).to socket_actor
socket.on 'timeout', ->
__send( socket, '#timeout' ).to socket_actor
__send( __net, '#connection', socket_actor ).to __cust
server.on 'error', ( exception ) ->
__send( __net, '#error', exception ).to __cust
server.on 'listening', ->
if __callback then __callback()
@host = if @host then @host else undefined
server.listen @port, @host
@become initializedServer_beh server
#
# An actor behavior wrapper around Node.js Socket
#
socket_beh = anode.beh '_cust', 'socket'
# attempt to match the explicit $socket first before trying generic 'cust'
'$socket, #close, had_error' : ->
@send( @, '#close', @had_error ).to @_cust
'$socket, #connect' : ->
@send( @, '#connect' ).to @_cust
'$socket, #data, data' : ->
@send( @, '#data', @data ).to @_cust
'$socket, #drain' : ->
@send( @, '#drain' ).to @_cust
'$socket, #end' : ->
@send( @, '#end' ).to @_cust
'$socket, #error, exception' : ->
@send( @, '#error', @exception ).to @_cust
'$socket, #timeout' : ->
@send( @, '#timeout' ).to @_cust
'cust, #address' : ->
@send( @, '#address', @socket.address() ).to @cust
'cust, #bufferSize' : ->
@send( @, '#bufferSize', @socket.bufferSize ).to @cust
'cust, #bytesRead' : ->
@send( @, '#bytesRead', @socket.bytesRead ).to @cust
'cust, #bytesWritten' : ->
@send( @, '#bytesWritten', @socket.bytesWritten ).to @cust
'cust, #destroy' : ->
@socket.destroy()
if @cust # ack requested
@send( @, '#destroy' ).to @cust
'cust, #end, [data], [encoding]' : ->
@socket.end @data, @encoding
if @cust # ack requested
@send( @, '#end' ).to @cust
'cust, #pause' : ->
@socket.pause()
if @cust # ack requested
@send( @, '#pause' ).to @cust
# Stream method ( should there be a way of behavior composition? )
'cust, #pipe, destination, [options]' : ->
@socket.pipe @destination, @options
if @cust # ack requested
@send( @, '#pipe' ).to @cust
'cust, #remoteAddress' : ->
@send( @, '#remoteAddress', @socket.remoteAddress ).to @cust
'cust, #remotePort' : ->
@send( @, '#remotePort', @socket.remotePort ).to @cust
'cust, #resume' : ->
@socket.resume()
if @cust # ack requested
@send( @, '#resume' ).to @cust
'cust, #setEncoding, encoding' : ->
@socket.setEncoding @encoding
if @cust # ack requested
@send( @, '#setEncoding' ).to @cust
'cust, #setKeepAlive, enable, [initialDelay]' : ->
@socket.setKeepAlive @enable, @initialDelay
if @cust # ack requested
@send( @, '#setKeepAlive' ).to @cust
'cust, #setNoDelay, noDelay' : ->
@socket.setNoDelay @noDelay
if @cust # ack requested
@send( @, '#setNoDelay' ).to @cust
'cust, #setTimeout, timeout' : ->
@socket.setTimeout @timeout
if @cust # ack requested
@send( @, '#setTimeout' ).to @cust
# get socket associated with this socket actor
'cust, #socket' : ->
@send( @, '#socket', @socket ).to @cust
'cust, #write, data, [encoding]' : ->
result = @socket.write @data, @encoding
if @cust # ack requested
@send( @, '#write', result ).to @cust
#
# The main net_beh wrapping Node.js 'net' functionality
#
exports.server_beh = uninitializedServer_beh | 35975 | #
# net.coffee : anode wrapper around Node.js net library
#
# (C) 2011 <NAME>
#
anode = require '../lib/anode'
nodenet = require 'net'
#
# Initialized net server behavior wrapped around a created server
#
initializedServer_beh = anode.beh 'server'
'cust, #address' : ->
@send( @, '#address', @server.address() ).to @cust
'cust, #close' : ->
__cust = @cust
__send = @send
__server = @
if @cust # ack requested
@server.on 'close', ( had_error ) ->
__send( __server, '#close' ).to __cust
@server.close()
'cust, #connections' : ->
@send( @, '#connections', @server.connections ).to @cust
'cust, #maxConnections, [num]' : ->
if @num # setter
@server.maxConnections = @num
if @cust # ack requested
@send( @, '#maxConnections' ).to @cust
else # getter
@send( @, '#maxConnections', @server.maxConnections ).to @cust
'cust, #pause, msecs' : ->
@server.pause @msecs
if @cust # ack requested
@send( @, '#pause' ).to @cust
#
# An uninitialized net server beh that will lazy-initialize the server
# and then become initialized net server beh
#
uninitializedServer_beh = anode.beh
# creates the server and attempts to listen on given port and host
'cust, #listen, port, [host], [options]' : ->
# local aliases for use inside closures
__create = @create
__cust = @cust
__net = @
__send = @send
if @options
server = nodenet.createServer @options
else
server = nodenet.createServer()
if @cust # ack requested
__callback = ->
__send( __net, '#listen' ).to __cust
# all server event bindings need to happen before nextTick
server.on 'close', ->
__send( __net, '#close' ).to __cust
server.on 'connection', ( socket ) ->
socket_actor = __create 'socket', socket_beh __cust, socket
# all socket bindings need to happen before nextTick
socket.on 'close', ( had_error ) ->
__send( socket, '#close', had_error ).to socket_actor
socket.on 'connect', ->
__send( socket, '#connect' ).to socket_actor
socket.on 'data', ( data ) ->
__send( socket, '#data', data ).to socket_actor
socket.on 'drain', ->
__send( socket, '#drain' ).to socket_actor
socket.on 'end', ->
__send( socket, '#end' ).to socket_actor
socket.on 'error', ( exception ) ->
__send( socket, '#error', exception ).to socket_actor
socket.on 'timeout', ->
__send( socket, '#timeout' ).to socket_actor
__send( __net, '#connection', socket_actor ).to __cust
server.on 'error', ( exception ) ->
__send( __net, '#error', exception ).to __cust
server.on 'listening', ->
if __callback then __callback()
@host = if @host then @host else undefined
server.listen @port, @host
@become initializedServer_beh server
#
# An actor behavior wrapper around Node.js Socket
#
socket_beh = anode.beh '_cust', 'socket'
# attempt to match the explicit $socket first before trying generic 'cust'
'$socket, #close, had_error' : ->
@send( @, '#close', @had_error ).to @_cust
'$socket, #connect' : ->
@send( @, '#connect' ).to @_cust
'$socket, #data, data' : ->
@send( @, '#data', @data ).to @_cust
'$socket, #drain' : ->
@send( @, '#drain' ).to @_cust
'$socket, #end' : ->
@send( @, '#end' ).to @_cust
'$socket, #error, exception' : ->
@send( @, '#error', @exception ).to @_cust
'$socket, #timeout' : ->
@send( @, '#timeout' ).to @_cust
'cust, #address' : ->
@send( @, '#address', @socket.address() ).to @cust
'cust, #bufferSize' : ->
@send( @, '#bufferSize', @socket.bufferSize ).to @cust
'cust, #bytesRead' : ->
@send( @, '#bytesRead', @socket.bytesRead ).to @cust
'cust, #bytesWritten' : ->
@send( @, '#bytesWritten', @socket.bytesWritten ).to @cust
'cust, #destroy' : ->
@socket.destroy()
if @cust # ack requested
@send( @, '#destroy' ).to @cust
'cust, #end, [data], [encoding]' : ->
@socket.end @data, @encoding
if @cust # ack requested
@send( @, '#end' ).to @cust
'cust, #pause' : ->
@socket.pause()
if @cust # ack requested
@send( @, '#pause' ).to @cust
# Stream method ( should there be a way of behavior composition? )
'cust, #pipe, destination, [options]' : ->
@socket.pipe @destination, @options
if @cust # ack requested
@send( @, '#pipe' ).to @cust
'cust, #remoteAddress' : ->
@send( @, '#remoteAddress', @socket.remoteAddress ).to @cust
'cust, #remotePort' : ->
@send( @, '#remotePort', @socket.remotePort ).to @cust
'cust, #resume' : ->
@socket.resume()
if @cust # ack requested
@send( @, '#resume' ).to @cust
'cust, #setEncoding, encoding' : ->
@socket.setEncoding @encoding
if @cust # ack requested
@send( @, '#setEncoding' ).to @cust
'cust, #setKeepAlive, enable, [initialDelay]' : ->
@socket.setKeepAlive @enable, @initialDelay
if @cust # ack requested
@send( @, '#setKeepAlive' ).to @cust
'cust, #setNoDelay, noDelay' : ->
@socket.setNoDelay @noDelay
if @cust # ack requested
@send( @, '#setNoDelay' ).to @cust
'cust, #setTimeout, timeout' : ->
@socket.setTimeout @timeout
if @cust # ack requested
@send( @, '#setTimeout' ).to @cust
# get socket associated with this socket actor
'cust, #socket' : ->
@send( @, '#socket', @socket ).to @cust
'cust, #write, data, [encoding]' : ->
result = @socket.write @data, @encoding
if @cust # ack requested
@send( @, '#write', result ).to @cust
#
# The main net_beh wrapping Node.js 'net' functionality
#
exports.server_beh = uninitializedServer_beh | true | #
# net.coffee : anode wrapper around Node.js net library
#
# (C) 2011 PI:NAME:<NAME>END_PI
#
anode = require '../lib/anode'
nodenet = require 'net'
#
# Initialized net server behavior wrapped around a created server
#
initializedServer_beh = anode.beh 'server'
'cust, #address' : ->
@send( @, '#address', @server.address() ).to @cust
'cust, #close' : ->
__cust = @cust
__send = @send
__server = @
if @cust # ack requested
@server.on 'close', ( had_error ) ->
__send( __server, '#close' ).to __cust
@server.close()
'cust, #connections' : ->
@send( @, '#connections', @server.connections ).to @cust
'cust, #maxConnections, [num]' : ->
if @num # setter
@server.maxConnections = @num
if @cust # ack requested
@send( @, '#maxConnections' ).to @cust
else # getter
@send( @, '#maxConnections', @server.maxConnections ).to @cust
'cust, #pause, msecs' : ->
@server.pause @msecs
if @cust # ack requested
@send( @, '#pause' ).to @cust
#
# An uninitialized net server beh that will lazy-initialize the server
# and then become initialized net server beh
#
uninitializedServer_beh = anode.beh
# creates the server and attempts to listen on given port and host
'cust, #listen, port, [host], [options]' : ->
# local aliases for use inside closures
__create = @create
__cust = @cust
__net = @
__send = @send
if @options
server = nodenet.createServer @options
else
server = nodenet.createServer()
if @cust # ack requested
__callback = ->
__send( __net, '#listen' ).to __cust
# all server event bindings need to happen before nextTick
server.on 'close', ->
__send( __net, '#close' ).to __cust
server.on 'connection', ( socket ) ->
socket_actor = __create 'socket', socket_beh __cust, socket
# all socket bindings need to happen before nextTick
socket.on 'close', ( had_error ) ->
__send( socket, '#close', had_error ).to socket_actor
socket.on 'connect', ->
__send( socket, '#connect' ).to socket_actor
socket.on 'data', ( data ) ->
__send( socket, '#data', data ).to socket_actor
socket.on 'drain', ->
__send( socket, '#drain' ).to socket_actor
socket.on 'end', ->
__send( socket, '#end' ).to socket_actor
socket.on 'error', ( exception ) ->
__send( socket, '#error', exception ).to socket_actor
socket.on 'timeout', ->
__send( socket, '#timeout' ).to socket_actor
__send( __net, '#connection', socket_actor ).to __cust
server.on 'error', ( exception ) ->
__send( __net, '#error', exception ).to __cust
server.on 'listening', ->
if __callback then __callback()
@host = if @host then @host else undefined
server.listen @port, @host
@become initializedServer_beh server
#
# An actor behavior wrapper around Node.js Socket
#
socket_beh = anode.beh '_cust', 'socket'
# attempt to match the explicit $socket first before trying generic 'cust'
'$socket, #close, had_error' : ->
@send( @, '#close', @had_error ).to @_cust
'$socket, #connect' : ->
@send( @, '#connect' ).to @_cust
'$socket, #data, data' : ->
@send( @, '#data', @data ).to @_cust
'$socket, #drain' : ->
@send( @, '#drain' ).to @_cust
'$socket, #end' : ->
@send( @, '#end' ).to @_cust
'$socket, #error, exception' : ->
@send( @, '#error', @exception ).to @_cust
'$socket, #timeout' : ->
@send( @, '#timeout' ).to @_cust
'cust, #address' : ->
@send( @, '#address', @socket.address() ).to @cust
'cust, #bufferSize' : ->
@send( @, '#bufferSize', @socket.bufferSize ).to @cust
'cust, #bytesRead' : ->
@send( @, '#bytesRead', @socket.bytesRead ).to @cust
'cust, #bytesWritten' : ->
@send( @, '#bytesWritten', @socket.bytesWritten ).to @cust
'cust, #destroy' : ->
@socket.destroy()
if @cust # ack requested
@send( @, '#destroy' ).to @cust
'cust, #end, [data], [encoding]' : ->
@socket.end @data, @encoding
if @cust # ack requested
@send( @, '#end' ).to @cust
'cust, #pause' : ->
@socket.pause()
if @cust # ack requested
@send( @, '#pause' ).to @cust
# Stream method ( should there be a way of behavior composition? )
'cust, #pipe, destination, [options]' : ->
@socket.pipe @destination, @options
if @cust # ack requested
@send( @, '#pipe' ).to @cust
'cust, #remoteAddress' : ->
@send( @, '#remoteAddress', @socket.remoteAddress ).to @cust
'cust, #remotePort' : ->
@send( @, '#remotePort', @socket.remotePort ).to @cust
'cust, #resume' : ->
@socket.resume()
if @cust # ack requested
@send( @, '#resume' ).to @cust
'cust, #setEncoding, encoding' : ->
@socket.setEncoding @encoding
if @cust # ack requested
@send( @, '#setEncoding' ).to @cust
'cust, #setKeepAlive, enable, [initialDelay]' : ->
@socket.setKeepAlive @enable, @initialDelay
if @cust # ack requested
@send( @, '#setKeepAlive' ).to @cust
'cust, #setNoDelay, noDelay' : ->
@socket.setNoDelay @noDelay
if @cust # ack requested
@send( @, '#setNoDelay' ).to @cust
'cust, #setTimeout, timeout' : ->
@socket.setTimeout @timeout
if @cust # ack requested
@send( @, '#setTimeout' ).to @cust
# get socket associated with this socket actor
'cust, #socket' : ->
@send( @, '#socket', @socket ).to @cust
'cust, #write, data, [encoding]' : ->
result = @socket.write @data, @encoding
if @cust # ack requested
@send( @, '#write', result ).to @cust
#
# The main net_beh wrapping Node.js 'net' functionality
#
exports.server_beh = uninitializedServer_beh |
[
{
"context": "\n cloudinary.config({api_key:'key',api_secret:'shhh'})\n res = cloudinary.utils.sign_request({param",
"end": 642,
"score": 0.9384742975234985,
"start": 638,
"tag": "KEY",
"value": "shhh"
}
] | node_modules/keystone/node_modules/cloudinary/test/util.coffee | aratinankarplanetria/visintel | 0 | dotenv = require('dotenv')
dotenv.load()
expect = require("expect.js")
cloudinary = require("../cloudinary")
utils = require("../lib/utils")
_ = require("underscore")
Q = require('q')
fs = require('fs')
describe "util", ->
return console.warn("**** Please setup environment for api test to run!") if !cloudinary.config().api_secret?
find_by_attr = (elements, attr, value) ->
for element in elements
return element if element[attr] == value
undefined
it "should call sign_request with one object only", (done) ->
@timeout 1000
orig = cloudinary.config()
cloudinary.config({api_key:'key',api_secret:'shhh'})
res = cloudinary.utils.sign_request({param:'value'})
expect(res.signature).to.eql('f675e7df8256e98b945bd79194d5ebc8bdaa459c')
cloudinary.config(orig)
done()
| 93248 | dotenv = require('dotenv')
dotenv.load()
expect = require("expect.js")
cloudinary = require("../cloudinary")
utils = require("../lib/utils")
_ = require("underscore")
Q = require('q')
fs = require('fs')
describe "util", ->
return console.warn("**** Please setup environment for api test to run!") if !cloudinary.config().api_secret?
find_by_attr = (elements, attr, value) ->
for element in elements
return element if element[attr] == value
undefined
it "should call sign_request with one object only", (done) ->
@timeout 1000
orig = cloudinary.config()
cloudinary.config({api_key:'key',api_secret:'<KEY>'})
res = cloudinary.utils.sign_request({param:'value'})
expect(res.signature).to.eql('f675e7df8256e98b945bd79194d5ebc8bdaa459c')
cloudinary.config(orig)
done()
| true | dotenv = require('dotenv')
dotenv.load()
expect = require("expect.js")
cloudinary = require("../cloudinary")
utils = require("../lib/utils")
_ = require("underscore")
Q = require('q')
fs = require('fs')
describe "util", ->
return console.warn("**** Please setup environment for api test to run!") if !cloudinary.config().api_secret?
find_by_attr = (elements, attr, value) ->
for element in elements
return element if element[attr] == value
undefined
it "should call sign_request with one object only", (done) ->
@timeout 1000
orig = cloudinary.config()
cloudinary.config({api_key:'key',api_secret:'PI:KEY:<KEY>END_PI'})
res = cloudinary.utils.sign_request({param:'value'})
expect(res.signature).to.eql('f675e7df8256e98b945bd79194d5ebc8bdaa459c')
cloudinary.config(orig)
done()
|
[
{
"context": "idate\", () ->\n file = {\n name: 'test',\n size: 4000\n }\n\n resul",
"end": 2487,
"score": 0.9991651773452759,
"start": 2483,
"tag": "NAME",
"value": "test"
},
{
"context": "idate\", () ->\n file = {\n name:... | app/modules/services/attachments.service.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: services/attachments.service.spec.coffee
###
describe "tgAttachmentsService", ->
attachmentsService = provide = null
mocks = {}
_mockTgConfirm = () ->
mocks.confirm = {
notify: sinon.stub()
}
provide.value "$tgConfirm", mocks.confirm
_mockTgConfig = () ->
mocks.config = {
get: sinon.stub()
}
mocks.config.get.withArgs('maxUploadFileSize', null).returns(3000)
provide.value "$tgConfig", mocks.config
_mockRs = () ->
mocks.rs = {}
provide.value "tgResources", mocks.rs
_mockTranslate = () ->
mocks.translate = {
instant: sinon.stub()
}
provide.value "$translate", mocks.translate
_inject = (callback) ->
inject (_tgAttachmentsService_) ->
attachmentsService = _tgAttachmentsService_
callback() if callback
_mocks = () ->
module ($provide) ->
provide = $provide
_mockTgConfirm()
_mockTgConfig()
_mockRs()
_mockTranslate()
return null
_setup = ->
_mocks()
beforeEach ->
module "taigaCommon"
_setup()
_inject()
it "maxFileSize formated", () ->
expect(attachmentsService.maxFileSizeFormated).to.be.equal("2.9 KB")
it "sizeError, send notification", () ->
file = {
name: 'test',
size: 3000
}
mocks.translate.instant.withArgs('ATTACHMENT.ERROR_MAX_SIZE_EXCEEDED').returns('message')
attachmentsService.sizeError(file)
expect(mocks.confirm.notify).to.have.been.calledWith('error', 'message')
it "invalid, validate", () ->
file = {
name: 'test',
size: 4000
}
result = attachmentsService.validate(file)
expect(result).to.be.false
it "valid, validate", () ->
file = {
name: 'test',
size: 1000
}
result = attachmentsService.validate(file)
expect(result).to.be.true
it "get max file size", () ->
result = attachmentsService.getMaxFileSize()
expect(result).to.be.equal(3000)
it "delete", () ->
mocks.rs.attachments = {
delete: sinon.stub()
}
attachmentsService.delete('us', 2)
expect(mocks.rs.attachments.delete).to.have.been.calledWith('us', 2)
it "upload", (done) ->
file = {
id: 1
}
objId = 2
projectId = 2
type = 'us'
mocks.rs.attachments = {
create: sinon.stub().promise()
}
mocks.rs.attachments.create.withArgs('us', type, objId, file).resolve()
attachmentsService.sizeError = sinon.spy()
attachmentsService.upload(file, objId, projectId, 'us').then () ->
expect(mocks.rs.attachments.create).to.have.been.calledOnce
done()
it "patch", (done) ->
file = {
id: 1
}
objId = 2
type = 'us'
patch = {
id: 2
}
mocks.rs.attachments = {
patch: sinon.stub().promise()
}
mocks.rs.attachments.patch.withArgs('us', objId, patch).resolve()
attachmentsService.sizeError = sinon.spy()
attachmentsService.patch(objId, 'us', patch).then () ->
expect(mocks.rs.attachments.patch).to.have.been.calledOnce
done()
it "error", () ->
mocks.translate.instant.withArgs("ATTACHMENT.ERROR_MAX_SIZE_EXCEEDED").returns("msg")
attachmentsService.sizeError({
name: 'name',
size: 123
})
expect(mocks.confirm.notify).to.have.been.calledWith('error', 'msg')
| 123265 | ###
# 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: services/attachments.service.spec.coffee
###
describe "tgAttachmentsService", ->
attachmentsService = provide = null
mocks = {}
_mockTgConfirm = () ->
mocks.confirm = {
notify: sinon.stub()
}
provide.value "$tgConfirm", mocks.confirm
_mockTgConfig = () ->
mocks.config = {
get: sinon.stub()
}
mocks.config.get.withArgs('maxUploadFileSize', null).returns(3000)
provide.value "$tgConfig", mocks.config
_mockRs = () ->
mocks.rs = {}
provide.value "tgResources", mocks.rs
_mockTranslate = () ->
mocks.translate = {
instant: sinon.stub()
}
provide.value "$translate", mocks.translate
_inject = (callback) ->
inject (_tgAttachmentsService_) ->
attachmentsService = _tgAttachmentsService_
callback() if callback
_mocks = () ->
module ($provide) ->
provide = $provide
_mockTgConfirm()
_mockTgConfig()
_mockRs()
_mockTranslate()
return null
_setup = ->
_mocks()
beforeEach ->
module "taigaCommon"
_setup()
_inject()
it "maxFileSize formated", () ->
expect(attachmentsService.maxFileSizeFormated).to.be.equal("2.9 KB")
it "sizeError, send notification", () ->
file = {
name: 'test',
size: 3000
}
mocks.translate.instant.withArgs('ATTACHMENT.ERROR_MAX_SIZE_EXCEEDED').returns('message')
attachmentsService.sizeError(file)
expect(mocks.confirm.notify).to.have.been.calledWith('error', 'message')
it "invalid, validate", () ->
file = {
name: '<NAME>',
size: 4000
}
result = attachmentsService.validate(file)
expect(result).to.be.false
it "valid, validate", () ->
file = {
name: '<NAME>',
size: 1000
}
result = attachmentsService.validate(file)
expect(result).to.be.true
it "get max file size", () ->
result = attachmentsService.getMaxFileSize()
expect(result).to.be.equal(3000)
it "delete", () ->
mocks.rs.attachments = {
delete: sinon.stub()
}
attachmentsService.delete('us', 2)
expect(mocks.rs.attachments.delete).to.have.been.calledWith('us', 2)
it "upload", (done) ->
file = {
id: 1
}
objId = 2
projectId = 2
type = 'us'
mocks.rs.attachments = {
create: sinon.stub().promise()
}
mocks.rs.attachments.create.withArgs('us', type, objId, file).resolve()
attachmentsService.sizeError = sinon.spy()
attachmentsService.upload(file, objId, projectId, 'us').then () ->
expect(mocks.rs.attachments.create).to.have.been.calledOnce
done()
it "patch", (done) ->
file = {
id: 1
}
objId = 2
type = 'us'
patch = {
id: 2
}
mocks.rs.attachments = {
patch: sinon.stub().promise()
}
mocks.rs.attachments.patch.withArgs('us', objId, patch).resolve()
attachmentsService.sizeError = sinon.spy()
attachmentsService.patch(objId, 'us', patch).then () ->
expect(mocks.rs.attachments.patch).to.have.been.calledOnce
done()
it "error", () ->
mocks.translate.instant.withArgs("ATTACHMENT.ERROR_MAX_SIZE_EXCEEDED").returns("msg")
attachmentsService.sizeError({
name: '<NAME>',
size: 123
})
expect(mocks.confirm.notify).to.have.been.calledWith('error', 'msg')
| 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: services/attachments.service.spec.coffee
###
describe "tgAttachmentsService", ->
attachmentsService = provide = null
mocks = {}
_mockTgConfirm = () ->
mocks.confirm = {
notify: sinon.stub()
}
provide.value "$tgConfirm", mocks.confirm
_mockTgConfig = () ->
mocks.config = {
get: sinon.stub()
}
mocks.config.get.withArgs('maxUploadFileSize', null).returns(3000)
provide.value "$tgConfig", mocks.config
_mockRs = () ->
mocks.rs = {}
provide.value "tgResources", mocks.rs
_mockTranslate = () ->
mocks.translate = {
instant: sinon.stub()
}
provide.value "$translate", mocks.translate
_inject = (callback) ->
inject (_tgAttachmentsService_) ->
attachmentsService = _tgAttachmentsService_
callback() if callback
_mocks = () ->
module ($provide) ->
provide = $provide
_mockTgConfirm()
_mockTgConfig()
_mockRs()
_mockTranslate()
return null
_setup = ->
_mocks()
beforeEach ->
module "taigaCommon"
_setup()
_inject()
it "maxFileSize formated", () ->
expect(attachmentsService.maxFileSizeFormated).to.be.equal("2.9 KB")
it "sizeError, send notification", () ->
file = {
name: 'test',
size: 3000
}
mocks.translate.instant.withArgs('ATTACHMENT.ERROR_MAX_SIZE_EXCEEDED').returns('message')
attachmentsService.sizeError(file)
expect(mocks.confirm.notify).to.have.been.calledWith('error', 'message')
it "invalid, validate", () ->
file = {
name: 'PI:NAME:<NAME>END_PI',
size: 4000
}
result = attachmentsService.validate(file)
expect(result).to.be.false
it "valid, validate", () ->
file = {
name: 'PI:NAME:<NAME>END_PI',
size: 1000
}
result = attachmentsService.validate(file)
expect(result).to.be.true
it "get max file size", () ->
result = attachmentsService.getMaxFileSize()
expect(result).to.be.equal(3000)
it "delete", () ->
mocks.rs.attachments = {
delete: sinon.stub()
}
attachmentsService.delete('us', 2)
expect(mocks.rs.attachments.delete).to.have.been.calledWith('us', 2)
it "upload", (done) ->
file = {
id: 1
}
objId = 2
projectId = 2
type = 'us'
mocks.rs.attachments = {
create: sinon.stub().promise()
}
mocks.rs.attachments.create.withArgs('us', type, objId, file).resolve()
attachmentsService.sizeError = sinon.spy()
attachmentsService.upload(file, objId, projectId, 'us').then () ->
expect(mocks.rs.attachments.create).to.have.been.calledOnce
done()
it "patch", (done) ->
file = {
id: 1
}
objId = 2
type = 'us'
patch = {
id: 2
}
mocks.rs.attachments = {
patch: sinon.stub().promise()
}
mocks.rs.attachments.patch.withArgs('us', objId, patch).resolve()
attachmentsService.sizeError = sinon.spy()
attachmentsService.patch(objId, 'us', patch).then () ->
expect(mocks.rs.attachments.patch).to.have.been.calledOnce
done()
it "error", () ->
mocks.translate.instant.withArgs("ATTACHMENT.ERROR_MAX_SIZE_EXCEEDED").returns("msg")
attachmentsService.sizeError({
name: 'PI:NAME:<NAME>END_PI',
size: 123
})
expect(mocks.confirm.notify).to.have.been.calledWith('error', 'msg')
|
[
{
"context": "':new Date(2012, 9), 'color':'#ff7f0e'}, {'name':'Winter', 'date':new Date(2012,12), 'color':'#7f7f7f'}]\n ",
"end": 1299,
"score": 0.9967656135559082,
"start": 1293,
"tag": "NAME",
"value": "Winter"
}
] | slides/color_seasons/coffee/all.coffee | Nordstrom/stratanyc | 1 |
root = exports ? this
showAll = true
valid_cities = {'seaptl':0, 'fla':0, 'laoc':0, 'sfbay':0,'chi':0,'dc':0, 'all':1}
# showColors = {'Red':1, 'Orange': 1, 'Yellow':1, 'Green':0, 'Blue':0, 'Violet':0, 'Brown':0, 'Black':0}
showColors = {'Red':1, 'Orange': 1, 'Yellow':1, 'Green':0, 'Blue':0, 'Violet':0, 'Brown':0, 'Black':0}
startDate = new Date(2012, 2)
endDate = new Date(2013, 3)
parseTime = d3.time.format("%Y-%m-%d").parse
limitData = (rawData) ->
rawData = rawData.filter (d) -> valid_cities[d.city] == 1
rawData.forEach (city,i) ->
city.colors.forEach (color) ->
color.data = color.data.filter (data) ->
parseTime(data.date) >= startDate and parseTime(data.date) < endDate
rawData
Plot = () ->
width = 900
height = 500
points = null
svg = null
margin = {top: 0, right: 0, bottom: 40, left: 0}
duration = 1000
layout = "stack"
filteredData = []
xScale = d3.time.scale().range([0,width])
yScale = d3.scale.linear().domain([0,10]).range([height,0])
xValue = (d) -> d.date
yValue = (d) -> parseFloat(d.percent)
seasons = [{'name':'Spring', 'date':new Date(2012, 3), 'color':'#2ca02c'}, {'name':'Summer', 'date':new Date(2012, 6), 'color':'#d62728'}, {'name':'Fall', 'date':new Date(2012, 9), 'color':'#ff7f0e'}, {'name':'Winter', 'date':new Date(2012,12), 'color':'#7f7f7f'}]
seasonScale = d3.scale.ordinal().domain(seasons.map((d) -> d.name)).rangeBands([0,width])
xAxis = d3.svg.axis()
.scale(xScale)
.tickSize(-height)
# .tickFormat(d3.time.format('%b'))
.tickFormat(d3.time.format(''))
area = d3.svg.area()
.interpolate("basis")
.x((d) -> xScale(xValue(d)))
# line generator to be used
# for the Area Chart edges
line = d3.svg.line()
.interpolate("basis")
.x((d) -> xScale(xValue(d)))
# stack layout for streamgraph
# and stacked area chart
stack = d3.layout.stack()
.values((d) -> d.data)
.x((d) -> xValue(d))
.y((d) -> yValue(d))
.out((d,y0,y) -> d.count0 = y0)
.order("reverse")
applyFilter = () ->
if !showAll
filteredData.forEach (d) ->
d.colors = d.colors.filter (c) ->
match = ntc.name(c.color)
hsl_color = d3.hsl(c.color)
shade_name = match[3]
showColors[shade_name] == 1
calculatePercentage = () ->
sums = d3.map()
filteredData.forEach (d) ->
d.colors.forEach (color) ->
color.data.forEach (x) ->
if !sums.has(x.epoch)
sums.set(x.epoch, 0)
sums.set(x.epoch, sums.get(x.epoch) + x.volume)
filteredData.forEach (d) ->
d.colors.forEach (color) ->
color.data.forEach (x) ->
x.percent = x.volume / sums.get(x.epoch)
setupData = (dd) ->
# dd = dd.filter (d) -> !d.grayscale and !(d.name == "Dark Slate Gray")
sums = d3.map()
# this recalculates the 'percentage' - so that it always sums to 100% after filtering
dd.forEach (color) ->
color.data.forEach (x) ->
if !sums.has(x.date)
sums.set(x.date, 0)
sums.set(x.date, sums.get(x.date) + x.volume)
dd.forEach (color) ->
color.data.forEach (x) ->
x.percent = x.volume / sums.get(x.date)
x.date = parseTime(x.date)
# precompute the largest count value for each request type
color.maxCount = d3.max(color.data, (d) -> d.percent)
# dd.sort((a,b) -> b.maxCount - a.maxCount)
dd
setup = (data) ->
minDate = d3.min(data, (d) -> d.data[0].date)
maxDate = d3.max(data, (d) -> d.data[d.data.length - 1].date)
xScale.domain([minDate, maxDate])
area.y0(height / 2)
.y1(height / 2)
chart = (selection) ->
selection.each (rawData) ->
data = limitData(rawData)
newData = []
data.forEach (d) ->
newData.push({'city':d.city, 'colors':setupData(d.colors)})
filteredData = newData
setup(filteredData[0].colors)
# chart = d3.select(this).selectAll(".chart").data(newData)
# chart.enter().append("h2").text((d) -> d.city)
svg = d3.select(this).selectAll("svg").data(newData)
gEnter = svg.enter().append("svg").attr("id", (d) -> d.city).append("g")
svg.attr("width", width + margin.left + margin.right )
svg.attr("height", height + margin.top + margin.bottom )
# svg.append("text")
# .attr("x", width + margin.left)
# .attr("y", margin.top)
# .attr("class", "title")
# .attr("text-anchor", "end")
# .text((d) -> d.city)
g = svg.select("g")
.attr("transform", "translate(#{margin.left},#{margin.top})")
points = g.append("g").attr("class", "vis_points")
g.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (height) + ")")
.call(xAxis)
seasonG = g.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + height + ")")
seasonG.selectAll(".season_rect")
.data(seasons).enter()
.append("rect")
.attr("x", (d) -> seasonScale(d.name))
.attr("y", 0)
.attr("width", seasonScale.rangeBand())
.attr("height", 40)
.attr("fill", (d) -> d3.hsl(d.color).brighter())
.attr("stroke", "white")
seasonG.selectAll(".season")
.data(seasons).enter()
.append("text")
.attr("class", "season")
.attr("x", (d) -> xScale(d.date) - xScale(startDate))
.attr("x", (d) -> seasonScale(d.name) + (seasonScale.rangeBand() / 2))
.attr("y", 0)
.attr("dy", 28)
.attr("text-anchor", 'middle')
.attr("fill", "white")
.text((d) -> d.name)
update = () ->
applyFilter()
calculatePercentage()
svg = d3.selectAll("svg").data(filteredData)
g = points.selectAll(".request")
.data(((d) -> d.colors), ((d) -> d.color_id))
g.exit().remove()
requests = g.enter().append("g")
.attr("class", "request")
requests.append("path")
.attr("class", "area")
.style("fill", (d) -> d.color)
.attr("d", (d) -> area(d.data))
.on("click", (d) -> console.log(d))
requests.append("path")
.attr("class", "line")
.style("stroke-opacity", 1e-6)
if layout == "stream"
svg.each((d) -> streamgraph(d.city, d.colors))
if layout == "stack"
svg.each((d) -> stackedAreas(d.city, d.colors))
if layout == "area"
svg.each((d) -> areas(d.city, d.colors))
streamgraph = (city, data) ->
# 'wiggle' is the offset to use
# for streamgraphs.
stack.offset("wiggle")
# the stack layout will set the count0 attribute
# of our data
stack(data)
# reset our y domain and range so that it
# accommodates the highest value + offset
yScale.domain([0, d3.max(data[0].data.map((d) -> d.count0 + d.percent))])
.range([height, 0])
# the line will be placed along the
# baseline of the streams, but will
# be faded away by the transition below.
# this positioning is just for smooth transitioning
# from the area chart
line.y((d) -> yScale(d.count0))
# setup the area generator to utilize
# the count0 values created from the stack
# layout
area.y0((d) -> yScale(d.count0))
.y1((d) -> yScale(d.count0 + d.percent))
# here we create the transition
# and modify the area and line for
# each request group through postselection
t = d3.select("##{city}").selectAll(".request")
.transition()
.duration(duration)
# D3 will take care of the details of transitioning
# between the current state of the elements and
# this new line path and opacity.
t.select("path.area")
.style("fill-opacity", 1.0)
.attr("d", (d) -> area(d.data))
# 1e-6 is the smallest number in JS that
# won't get converted to scientific notation.
# as scientific notation is not supported by CSS,
# we need to use this as the low value so that the
# line doesn't reappear due to an invalid number.
t.select("path.line")
.style("stroke-opacity", 1e-6)
.attr("d", (d) -> line(d.data))
# ---
# Code to transition to Stacked Area chart.
#
# Again, like in the streamgraph function,
# we use the stack layout to manage
# the layout details.
# ---
stackedAreas = (city, data) ->
# the offset is the only thing we need to
# change on our stack layout to have a completely
# different type of chart!
stack.offset("zero")
# re-run the layout on the data to modify the count0
# values
stack(data)
# the rest of this is the same as the streamgraph - but
# because the count0 values are now set for stacking,
# we will get a Stacked Area chart.
yScale.domain([0, d3.max(data[0].data.map((d) -> d.count0 + d.percent))])
.range([height, 0])
line.y((d) -> yScale(d.count0))
area.y0((d) -> yScale(d.count0))
.y1((d) -> yScale(d.count0 + d.percent))
t = d3.select("##{city}").selectAll(".request")
.transition()
.duration(duration)
t.select("path.area")
.style("fill-opacity", 1.0)
.attr("d", (d) -> area(d.data))
t.select("path.line")
.style("stroke-opacity", 1e-6)
.attr("d", (d) -> line(d.data))
# ---
# Code to transition to Area chart.
# ---
areas = (city, data) ->
g = points.selectAll(".request")
# set the starting position of the border
# line to be on the top part of the areas.
# then it is immediately hidden so that it
# can fade in during the transition below
line.y((d) -> yScale(d.count0 + d.percent))
d3.select("##{city}").select("path.line")
.attr("d", (d) -> line(d.data))
.style("stroke-opacity", 1e-6)
# as there is no stacking in this chart, the maximum
# value of the input domain is simply the maximum count value,
# which we precomputed in the display function
yScale.domain([0, d3.max(data.map((d) -> d.maxCount))])
.range([height, 0])
# the baseline of this chart will always
# be at the bottom of the display, so we
# can set y0 to a constant.
area.y0(height)
.y1((d) -> yScale(d.percent))
line.y((d) -> yScale(d.percent))
t = g.transition()
.duration(duration)
# transition the areas to be
# partially transparent so that the
# overlap is better understood.
t.select("path.area")
.style("fill-opacity", 0.5)
.attr("d", (d) -> area(d.data))
# here we finally show the line
# that serves as a nice border at the
# top of our areas
t.select("path.line")
.style("stroke-opacity", 1)
.attr("d", (d) -> line(d.data))
chart.start = () ->
update()
chart.toggle = (name) ->
layout = name
update()
chart.height = (_) ->
if !arguments.length
return height
height = _
chart
chart.width = (_) ->
if !arguments.length
return width
width = _
chart
chart.margin = (_) ->
if !arguments.length
return margin
margin = _
chart
chart.x = (_) ->
if !arguments.length
return xValue
xValue = _
chart
chart.y = (_) ->
if !arguments.length
return yValue
yValue = _
chart
return chart
root.Plot = Plot
root.plotData = (selector, data, plot) ->
d3.select(selector)
.datum(data)
.call(plot)
$ ->
plot = Plot()
# diffplot.color("Red")
display = (error, data) ->
plotData("#vis", data, plot)
# plotData("#detail", data, diffplot)
d3.selectAll(".switch").on "click", (d) ->
d3.event.preventDefault()
id = d3.select(this).attr("id")
plot.toggle(id)
queue()
.defer(d3.json, "data/city_color_disp_data.json")
.await(display)
startPlot = (e) ->
console.log('start')
action = e.data
if action == 'start'
plot.start()
window.addEventListener('message', startPlot, false)
| 108947 |
root = exports ? this
showAll = true
valid_cities = {'seaptl':0, 'fla':0, 'laoc':0, 'sfbay':0,'chi':0,'dc':0, 'all':1}
# showColors = {'Red':1, 'Orange': 1, 'Yellow':1, 'Green':0, 'Blue':0, 'Violet':0, 'Brown':0, 'Black':0}
showColors = {'Red':1, 'Orange': 1, 'Yellow':1, 'Green':0, 'Blue':0, 'Violet':0, 'Brown':0, 'Black':0}
startDate = new Date(2012, 2)
endDate = new Date(2013, 3)
parseTime = d3.time.format("%Y-%m-%d").parse
limitData = (rawData) ->
rawData = rawData.filter (d) -> valid_cities[d.city] == 1
rawData.forEach (city,i) ->
city.colors.forEach (color) ->
color.data = color.data.filter (data) ->
parseTime(data.date) >= startDate and parseTime(data.date) < endDate
rawData
Plot = () ->
width = 900
height = 500
points = null
svg = null
margin = {top: 0, right: 0, bottom: 40, left: 0}
duration = 1000
layout = "stack"
filteredData = []
xScale = d3.time.scale().range([0,width])
yScale = d3.scale.linear().domain([0,10]).range([height,0])
xValue = (d) -> d.date
yValue = (d) -> parseFloat(d.percent)
seasons = [{'name':'Spring', 'date':new Date(2012, 3), 'color':'#2ca02c'}, {'name':'Summer', 'date':new Date(2012, 6), 'color':'#d62728'}, {'name':'Fall', 'date':new Date(2012, 9), 'color':'#ff7f0e'}, {'name':'<NAME>', 'date':new Date(2012,12), 'color':'#7f7f7f'}]
seasonScale = d3.scale.ordinal().domain(seasons.map((d) -> d.name)).rangeBands([0,width])
xAxis = d3.svg.axis()
.scale(xScale)
.tickSize(-height)
# .tickFormat(d3.time.format('%b'))
.tickFormat(d3.time.format(''))
area = d3.svg.area()
.interpolate("basis")
.x((d) -> xScale(xValue(d)))
# line generator to be used
# for the Area Chart edges
line = d3.svg.line()
.interpolate("basis")
.x((d) -> xScale(xValue(d)))
# stack layout for streamgraph
# and stacked area chart
stack = d3.layout.stack()
.values((d) -> d.data)
.x((d) -> xValue(d))
.y((d) -> yValue(d))
.out((d,y0,y) -> d.count0 = y0)
.order("reverse")
applyFilter = () ->
if !showAll
filteredData.forEach (d) ->
d.colors = d.colors.filter (c) ->
match = ntc.name(c.color)
hsl_color = d3.hsl(c.color)
shade_name = match[3]
showColors[shade_name] == 1
calculatePercentage = () ->
sums = d3.map()
filteredData.forEach (d) ->
d.colors.forEach (color) ->
color.data.forEach (x) ->
if !sums.has(x.epoch)
sums.set(x.epoch, 0)
sums.set(x.epoch, sums.get(x.epoch) + x.volume)
filteredData.forEach (d) ->
d.colors.forEach (color) ->
color.data.forEach (x) ->
x.percent = x.volume / sums.get(x.epoch)
setupData = (dd) ->
# dd = dd.filter (d) -> !d.grayscale and !(d.name == "Dark Slate Gray")
sums = d3.map()
# this recalculates the 'percentage' - so that it always sums to 100% after filtering
dd.forEach (color) ->
color.data.forEach (x) ->
if !sums.has(x.date)
sums.set(x.date, 0)
sums.set(x.date, sums.get(x.date) + x.volume)
dd.forEach (color) ->
color.data.forEach (x) ->
x.percent = x.volume / sums.get(x.date)
x.date = parseTime(x.date)
# precompute the largest count value for each request type
color.maxCount = d3.max(color.data, (d) -> d.percent)
# dd.sort((a,b) -> b.maxCount - a.maxCount)
dd
setup = (data) ->
minDate = d3.min(data, (d) -> d.data[0].date)
maxDate = d3.max(data, (d) -> d.data[d.data.length - 1].date)
xScale.domain([minDate, maxDate])
area.y0(height / 2)
.y1(height / 2)
chart = (selection) ->
selection.each (rawData) ->
data = limitData(rawData)
newData = []
data.forEach (d) ->
newData.push({'city':d.city, 'colors':setupData(d.colors)})
filteredData = newData
setup(filteredData[0].colors)
# chart = d3.select(this).selectAll(".chart").data(newData)
# chart.enter().append("h2").text((d) -> d.city)
svg = d3.select(this).selectAll("svg").data(newData)
gEnter = svg.enter().append("svg").attr("id", (d) -> d.city).append("g")
svg.attr("width", width + margin.left + margin.right )
svg.attr("height", height + margin.top + margin.bottom )
# svg.append("text")
# .attr("x", width + margin.left)
# .attr("y", margin.top)
# .attr("class", "title")
# .attr("text-anchor", "end")
# .text((d) -> d.city)
g = svg.select("g")
.attr("transform", "translate(#{margin.left},#{margin.top})")
points = g.append("g").attr("class", "vis_points")
g.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (height) + ")")
.call(xAxis)
seasonG = g.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + height + ")")
seasonG.selectAll(".season_rect")
.data(seasons).enter()
.append("rect")
.attr("x", (d) -> seasonScale(d.name))
.attr("y", 0)
.attr("width", seasonScale.rangeBand())
.attr("height", 40)
.attr("fill", (d) -> d3.hsl(d.color).brighter())
.attr("stroke", "white")
seasonG.selectAll(".season")
.data(seasons).enter()
.append("text")
.attr("class", "season")
.attr("x", (d) -> xScale(d.date) - xScale(startDate))
.attr("x", (d) -> seasonScale(d.name) + (seasonScale.rangeBand() / 2))
.attr("y", 0)
.attr("dy", 28)
.attr("text-anchor", 'middle')
.attr("fill", "white")
.text((d) -> d.name)
update = () ->
applyFilter()
calculatePercentage()
svg = d3.selectAll("svg").data(filteredData)
g = points.selectAll(".request")
.data(((d) -> d.colors), ((d) -> d.color_id))
g.exit().remove()
requests = g.enter().append("g")
.attr("class", "request")
requests.append("path")
.attr("class", "area")
.style("fill", (d) -> d.color)
.attr("d", (d) -> area(d.data))
.on("click", (d) -> console.log(d))
requests.append("path")
.attr("class", "line")
.style("stroke-opacity", 1e-6)
if layout == "stream"
svg.each((d) -> streamgraph(d.city, d.colors))
if layout == "stack"
svg.each((d) -> stackedAreas(d.city, d.colors))
if layout == "area"
svg.each((d) -> areas(d.city, d.colors))
streamgraph = (city, data) ->
# 'wiggle' is the offset to use
# for streamgraphs.
stack.offset("wiggle")
# the stack layout will set the count0 attribute
# of our data
stack(data)
# reset our y domain and range so that it
# accommodates the highest value + offset
yScale.domain([0, d3.max(data[0].data.map((d) -> d.count0 + d.percent))])
.range([height, 0])
# the line will be placed along the
# baseline of the streams, but will
# be faded away by the transition below.
# this positioning is just for smooth transitioning
# from the area chart
line.y((d) -> yScale(d.count0))
# setup the area generator to utilize
# the count0 values created from the stack
# layout
area.y0((d) -> yScale(d.count0))
.y1((d) -> yScale(d.count0 + d.percent))
# here we create the transition
# and modify the area and line for
# each request group through postselection
t = d3.select("##{city}").selectAll(".request")
.transition()
.duration(duration)
# D3 will take care of the details of transitioning
# between the current state of the elements and
# this new line path and opacity.
t.select("path.area")
.style("fill-opacity", 1.0)
.attr("d", (d) -> area(d.data))
# 1e-6 is the smallest number in JS that
# won't get converted to scientific notation.
# as scientific notation is not supported by CSS,
# we need to use this as the low value so that the
# line doesn't reappear due to an invalid number.
t.select("path.line")
.style("stroke-opacity", 1e-6)
.attr("d", (d) -> line(d.data))
# ---
# Code to transition to Stacked Area chart.
#
# Again, like in the streamgraph function,
# we use the stack layout to manage
# the layout details.
# ---
stackedAreas = (city, data) ->
# the offset is the only thing we need to
# change on our stack layout to have a completely
# different type of chart!
stack.offset("zero")
# re-run the layout on the data to modify the count0
# values
stack(data)
# the rest of this is the same as the streamgraph - but
# because the count0 values are now set for stacking,
# we will get a Stacked Area chart.
yScale.domain([0, d3.max(data[0].data.map((d) -> d.count0 + d.percent))])
.range([height, 0])
line.y((d) -> yScale(d.count0))
area.y0((d) -> yScale(d.count0))
.y1((d) -> yScale(d.count0 + d.percent))
t = d3.select("##{city}").selectAll(".request")
.transition()
.duration(duration)
t.select("path.area")
.style("fill-opacity", 1.0)
.attr("d", (d) -> area(d.data))
t.select("path.line")
.style("stroke-opacity", 1e-6)
.attr("d", (d) -> line(d.data))
# ---
# Code to transition to Area chart.
# ---
areas = (city, data) ->
g = points.selectAll(".request")
# set the starting position of the border
# line to be on the top part of the areas.
# then it is immediately hidden so that it
# can fade in during the transition below
line.y((d) -> yScale(d.count0 + d.percent))
d3.select("##{city}").select("path.line")
.attr("d", (d) -> line(d.data))
.style("stroke-opacity", 1e-6)
# as there is no stacking in this chart, the maximum
# value of the input domain is simply the maximum count value,
# which we precomputed in the display function
yScale.domain([0, d3.max(data.map((d) -> d.maxCount))])
.range([height, 0])
# the baseline of this chart will always
# be at the bottom of the display, so we
# can set y0 to a constant.
area.y0(height)
.y1((d) -> yScale(d.percent))
line.y((d) -> yScale(d.percent))
t = g.transition()
.duration(duration)
# transition the areas to be
# partially transparent so that the
# overlap is better understood.
t.select("path.area")
.style("fill-opacity", 0.5)
.attr("d", (d) -> area(d.data))
# here we finally show the line
# that serves as a nice border at the
# top of our areas
t.select("path.line")
.style("stroke-opacity", 1)
.attr("d", (d) -> line(d.data))
chart.start = () ->
update()
chart.toggle = (name) ->
layout = name
update()
chart.height = (_) ->
if !arguments.length
return height
height = _
chart
chart.width = (_) ->
if !arguments.length
return width
width = _
chart
chart.margin = (_) ->
if !arguments.length
return margin
margin = _
chart
chart.x = (_) ->
if !arguments.length
return xValue
xValue = _
chart
chart.y = (_) ->
if !arguments.length
return yValue
yValue = _
chart
return chart
root.Plot = Plot
root.plotData = (selector, data, plot) ->
d3.select(selector)
.datum(data)
.call(plot)
$ ->
plot = Plot()
# diffplot.color("Red")
display = (error, data) ->
plotData("#vis", data, plot)
# plotData("#detail", data, diffplot)
d3.selectAll(".switch").on "click", (d) ->
d3.event.preventDefault()
id = d3.select(this).attr("id")
plot.toggle(id)
queue()
.defer(d3.json, "data/city_color_disp_data.json")
.await(display)
startPlot = (e) ->
console.log('start')
action = e.data
if action == 'start'
plot.start()
window.addEventListener('message', startPlot, false)
| true |
root = exports ? this
showAll = true
valid_cities = {'seaptl':0, 'fla':0, 'laoc':0, 'sfbay':0,'chi':0,'dc':0, 'all':1}
# showColors = {'Red':1, 'Orange': 1, 'Yellow':1, 'Green':0, 'Blue':0, 'Violet':0, 'Brown':0, 'Black':0}
showColors = {'Red':1, 'Orange': 1, 'Yellow':1, 'Green':0, 'Blue':0, 'Violet':0, 'Brown':0, 'Black':0}
startDate = new Date(2012, 2)
endDate = new Date(2013, 3)
parseTime = d3.time.format("%Y-%m-%d").parse
limitData = (rawData) ->
rawData = rawData.filter (d) -> valid_cities[d.city] == 1
rawData.forEach (city,i) ->
city.colors.forEach (color) ->
color.data = color.data.filter (data) ->
parseTime(data.date) >= startDate and parseTime(data.date) < endDate
rawData
Plot = () ->
width = 900
height = 500
points = null
svg = null
margin = {top: 0, right: 0, bottom: 40, left: 0}
duration = 1000
layout = "stack"
filteredData = []
xScale = d3.time.scale().range([0,width])
yScale = d3.scale.linear().domain([0,10]).range([height,0])
xValue = (d) -> d.date
yValue = (d) -> parseFloat(d.percent)
seasons = [{'name':'Spring', 'date':new Date(2012, 3), 'color':'#2ca02c'}, {'name':'Summer', 'date':new Date(2012, 6), 'color':'#d62728'}, {'name':'Fall', 'date':new Date(2012, 9), 'color':'#ff7f0e'}, {'name':'PI:NAME:<NAME>END_PI', 'date':new Date(2012,12), 'color':'#7f7f7f'}]
seasonScale = d3.scale.ordinal().domain(seasons.map((d) -> d.name)).rangeBands([0,width])
xAxis = d3.svg.axis()
.scale(xScale)
.tickSize(-height)
# .tickFormat(d3.time.format('%b'))
.tickFormat(d3.time.format(''))
area = d3.svg.area()
.interpolate("basis")
.x((d) -> xScale(xValue(d)))
# line generator to be used
# for the Area Chart edges
line = d3.svg.line()
.interpolate("basis")
.x((d) -> xScale(xValue(d)))
# stack layout for streamgraph
# and stacked area chart
stack = d3.layout.stack()
.values((d) -> d.data)
.x((d) -> xValue(d))
.y((d) -> yValue(d))
.out((d,y0,y) -> d.count0 = y0)
.order("reverse")
applyFilter = () ->
if !showAll
filteredData.forEach (d) ->
d.colors = d.colors.filter (c) ->
match = ntc.name(c.color)
hsl_color = d3.hsl(c.color)
shade_name = match[3]
showColors[shade_name] == 1
calculatePercentage = () ->
sums = d3.map()
filteredData.forEach (d) ->
d.colors.forEach (color) ->
color.data.forEach (x) ->
if !sums.has(x.epoch)
sums.set(x.epoch, 0)
sums.set(x.epoch, sums.get(x.epoch) + x.volume)
filteredData.forEach (d) ->
d.colors.forEach (color) ->
color.data.forEach (x) ->
x.percent = x.volume / sums.get(x.epoch)
setupData = (dd) ->
# dd = dd.filter (d) -> !d.grayscale and !(d.name == "Dark Slate Gray")
sums = d3.map()
# this recalculates the 'percentage' - so that it always sums to 100% after filtering
dd.forEach (color) ->
color.data.forEach (x) ->
if !sums.has(x.date)
sums.set(x.date, 0)
sums.set(x.date, sums.get(x.date) + x.volume)
dd.forEach (color) ->
color.data.forEach (x) ->
x.percent = x.volume / sums.get(x.date)
x.date = parseTime(x.date)
# precompute the largest count value for each request type
color.maxCount = d3.max(color.data, (d) -> d.percent)
# dd.sort((a,b) -> b.maxCount - a.maxCount)
dd
setup = (data) ->
minDate = d3.min(data, (d) -> d.data[0].date)
maxDate = d3.max(data, (d) -> d.data[d.data.length - 1].date)
xScale.domain([minDate, maxDate])
area.y0(height / 2)
.y1(height / 2)
chart = (selection) ->
selection.each (rawData) ->
data = limitData(rawData)
newData = []
data.forEach (d) ->
newData.push({'city':d.city, 'colors':setupData(d.colors)})
filteredData = newData
setup(filteredData[0].colors)
# chart = d3.select(this).selectAll(".chart").data(newData)
# chart.enter().append("h2").text((d) -> d.city)
svg = d3.select(this).selectAll("svg").data(newData)
gEnter = svg.enter().append("svg").attr("id", (d) -> d.city).append("g")
svg.attr("width", width + margin.left + margin.right )
svg.attr("height", height + margin.top + margin.bottom )
# svg.append("text")
# .attr("x", width + margin.left)
# .attr("y", margin.top)
# .attr("class", "title")
# .attr("text-anchor", "end")
# .text((d) -> d.city)
g = svg.select("g")
.attr("transform", "translate(#{margin.left},#{margin.top})")
points = g.append("g").attr("class", "vis_points")
g.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (height) + ")")
.call(xAxis)
seasonG = g.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + height + ")")
seasonG.selectAll(".season_rect")
.data(seasons).enter()
.append("rect")
.attr("x", (d) -> seasonScale(d.name))
.attr("y", 0)
.attr("width", seasonScale.rangeBand())
.attr("height", 40)
.attr("fill", (d) -> d3.hsl(d.color).brighter())
.attr("stroke", "white")
seasonG.selectAll(".season")
.data(seasons).enter()
.append("text")
.attr("class", "season")
.attr("x", (d) -> xScale(d.date) - xScale(startDate))
.attr("x", (d) -> seasonScale(d.name) + (seasonScale.rangeBand() / 2))
.attr("y", 0)
.attr("dy", 28)
.attr("text-anchor", 'middle')
.attr("fill", "white")
.text((d) -> d.name)
update = () ->
applyFilter()
calculatePercentage()
svg = d3.selectAll("svg").data(filteredData)
g = points.selectAll(".request")
.data(((d) -> d.colors), ((d) -> d.color_id))
g.exit().remove()
requests = g.enter().append("g")
.attr("class", "request")
requests.append("path")
.attr("class", "area")
.style("fill", (d) -> d.color)
.attr("d", (d) -> area(d.data))
.on("click", (d) -> console.log(d))
requests.append("path")
.attr("class", "line")
.style("stroke-opacity", 1e-6)
if layout == "stream"
svg.each((d) -> streamgraph(d.city, d.colors))
if layout == "stack"
svg.each((d) -> stackedAreas(d.city, d.colors))
if layout == "area"
svg.each((d) -> areas(d.city, d.colors))
streamgraph = (city, data) ->
# 'wiggle' is the offset to use
# for streamgraphs.
stack.offset("wiggle")
# the stack layout will set the count0 attribute
# of our data
stack(data)
# reset our y domain and range so that it
# accommodates the highest value + offset
yScale.domain([0, d3.max(data[0].data.map((d) -> d.count0 + d.percent))])
.range([height, 0])
# the line will be placed along the
# baseline of the streams, but will
# be faded away by the transition below.
# this positioning is just for smooth transitioning
# from the area chart
line.y((d) -> yScale(d.count0))
# setup the area generator to utilize
# the count0 values created from the stack
# layout
area.y0((d) -> yScale(d.count0))
.y1((d) -> yScale(d.count0 + d.percent))
# here we create the transition
# and modify the area and line for
# each request group through postselection
t = d3.select("##{city}").selectAll(".request")
.transition()
.duration(duration)
# D3 will take care of the details of transitioning
# between the current state of the elements and
# this new line path and opacity.
t.select("path.area")
.style("fill-opacity", 1.0)
.attr("d", (d) -> area(d.data))
# 1e-6 is the smallest number in JS that
# won't get converted to scientific notation.
# as scientific notation is not supported by CSS,
# we need to use this as the low value so that the
# line doesn't reappear due to an invalid number.
t.select("path.line")
.style("stroke-opacity", 1e-6)
.attr("d", (d) -> line(d.data))
# ---
# Code to transition to Stacked Area chart.
#
# Again, like in the streamgraph function,
# we use the stack layout to manage
# the layout details.
# ---
stackedAreas = (city, data) ->
# the offset is the only thing we need to
# change on our stack layout to have a completely
# different type of chart!
stack.offset("zero")
# re-run the layout on the data to modify the count0
# values
stack(data)
# the rest of this is the same as the streamgraph - but
# because the count0 values are now set for stacking,
# we will get a Stacked Area chart.
yScale.domain([0, d3.max(data[0].data.map((d) -> d.count0 + d.percent))])
.range([height, 0])
line.y((d) -> yScale(d.count0))
area.y0((d) -> yScale(d.count0))
.y1((d) -> yScale(d.count0 + d.percent))
t = d3.select("##{city}").selectAll(".request")
.transition()
.duration(duration)
t.select("path.area")
.style("fill-opacity", 1.0)
.attr("d", (d) -> area(d.data))
t.select("path.line")
.style("stroke-opacity", 1e-6)
.attr("d", (d) -> line(d.data))
# ---
# Code to transition to Area chart.
# ---
areas = (city, data) ->
g = points.selectAll(".request")
# set the starting position of the border
# line to be on the top part of the areas.
# then it is immediately hidden so that it
# can fade in during the transition below
line.y((d) -> yScale(d.count0 + d.percent))
d3.select("##{city}").select("path.line")
.attr("d", (d) -> line(d.data))
.style("stroke-opacity", 1e-6)
# as there is no stacking in this chart, the maximum
# value of the input domain is simply the maximum count value,
# which we precomputed in the display function
yScale.domain([0, d3.max(data.map((d) -> d.maxCount))])
.range([height, 0])
# the baseline of this chart will always
# be at the bottom of the display, so we
# can set y0 to a constant.
area.y0(height)
.y1((d) -> yScale(d.percent))
line.y((d) -> yScale(d.percent))
t = g.transition()
.duration(duration)
# transition the areas to be
# partially transparent so that the
# overlap is better understood.
t.select("path.area")
.style("fill-opacity", 0.5)
.attr("d", (d) -> area(d.data))
# here we finally show the line
# that serves as a nice border at the
# top of our areas
t.select("path.line")
.style("stroke-opacity", 1)
.attr("d", (d) -> line(d.data))
chart.start = () ->
update()
chart.toggle = (name) ->
layout = name
update()
chart.height = (_) ->
if !arguments.length
return height
height = _
chart
chart.width = (_) ->
if !arguments.length
return width
width = _
chart
chart.margin = (_) ->
if !arguments.length
return margin
margin = _
chart
chart.x = (_) ->
if !arguments.length
return xValue
xValue = _
chart
chart.y = (_) ->
if !arguments.length
return yValue
yValue = _
chart
return chart
root.Plot = Plot
root.plotData = (selector, data, plot) ->
d3.select(selector)
.datum(data)
.call(plot)
$ ->
plot = Plot()
# diffplot.color("Red")
display = (error, data) ->
plotData("#vis", data, plot)
# plotData("#detail", data, diffplot)
d3.selectAll(".switch").on "click", (d) ->
d3.event.preventDefault()
id = d3.select(this).attr("id")
plot.toggle(id)
queue()
.defer(d3.json, "data/city_color_disp_data.json")
.await(display)
startPlot = (e) ->
console.log('start')
action = e.data
if action == 'start'
plot.start()
window.addEventListener('message', startPlot, false)
|
[
{
"context": "ear <= 0\n\t\t\t\t\t\ttoCentury += 1\n\t\t\t\t\t\tgrammarKey = \"CENTURY_RANGE_BC\"\n\t\t\t\t\telse\n\t\t\t\t\t\tgrammarKey = \"CENTURY_R",
"end": 16803,
"score": 0.7383214831352234,
"start": 16796,
"tag": "KEY",
"value": "CENTURY"
},
{
"context": "\ttoCentury += 1\n\t\... | src/elements/DateTime/DateTimeRangeGrammar.coffee | programmfabrik/coffeescript-ui | 10 | class CUI.DateTimeRangeGrammar
@REGEXP_DATE = /^[0-9]+[-/.][0-9]+[-/.][0-9]+$/ # Exact date
@REGEXP_MONTH = /^[0-9]+[-/.][0-9]+$/ # Matches if the date has Year and month (no day)
@REGEXP_YEAR = /^\-?[0-9]+$/ # Matches if the date has Year. (no day, no month)
@REGEXP_YEAR_DOT = /^[0-9]+.$/ # Matches Year ending with dot.
@REGEXP_CENTURY = /^[0-9]+th$/ # Matches Year ending with th.
@REGEXP_SPACE = /\s+/
@REGEXP_DASH = /[\–\—]/g # Matches 'EN' and 'EM' dashes.
@TYPE_DATE = "DATE"
@TYPE_YEAR = "YEAR"
@TYPE_YEAR_DOT = "YEAR_DOT"
@TYPE_CENTURY = "CENTURY"
@TYPE_CENTURY_RANGE = "CENTURY_RANGE"
@TYPE_MONTH = "MONTH"
@DASH = "-"
@STORE_FORMAT = "store"
@OUTPUT_YEAR = "year"
@OUTPUT_DATE = "date"
@DISPLAY_ATTRIBUTE_YEAR_MONTH = "year-month"
@EN_DASH = "–"
@MONTHS = {}
@MONTHS["de-DE"] = [
"Januar"
"Februar"
"März"
"April"
"Mai"
"Juni"
"Juli"
"August"
"September"
"Oktober"
"November"
"Dezember"
]
@MONTHS["en-US"] = [
"January"
"February"
"March"
"April"
"May"
"June"
"July"
"August"
"September"
"October"
"November"
"December"
]
### How to add new grammars:
# [<GRAMMAR>, <FUNCTION>, <ARRAY_TOKEN_POSITION>, <ARRAY_FUNCTION_ARGUMENTS>, <KEY>]
#
# GRAMMAR: Plain text with tokens to identify dates.
# - Tokens available: DATE (full date), YEAR (only year), YEAR_DOT (year with dot), CENTURY (year with th)
#
# FUNCTION: Function which is going to be used to parse, in string.
# - Functions available: millennium, century, earlyCentury, lateCentury, range, yearRange, getFromTo
#
# ARRAY_TOKEN_POSITION: Array of integers with the position of the date tokens.
# ARRAY_FUNCTION_ARGUMENTS: (optional) Array with arguments that will be given to the function.
# - Dates are given as arguments automatically.
#
# KEY: (optional) Identifier that is used in the format method.
###
@PARSE_GRAMMARS = {} # TODO: Add ES & IT.
@PARSE_GRAMMARS["de-DE"] = [
["DATE bis DATE", "range", [0, 2], null, "RANGE"]
["YEAR bis YEAR", "range", [0, 2], null, "RANGE_YEAR"]
["YEAR - YEAR n. Chr.", "range", [0, 2]]
["YEAR bis YEAR n. Chr.", "range", [0, 2]]
["zwischen YEAR bis YEAR", "range", [1, 3]]
["zwischen YEAR und YEAR", "range", [1, 3]]
["zwischen DATE bis DATE", "range", [1, 3]]
["zwischen DATE und DATE", "range", [1, 3]]
["von YEAR bis YEAR", "range", [1, 3]]
["YEAR v. Chr. - YEAR n. Chr.", "range", [0, 4], [true]]
["YEAR - YEAR v. Chr.", "range", [0, 2], [true, true]]
["YEAR BC - YEAR n. Chr.", "range", [0, 3], [true]]
["YEAR BC - YEAR nach Chr.", "range", [0, 3], [true]]
["YEAR B.C. - YEAR n. Chr.", "range", [0, 3], [true]]
["YEAR B.C. - YEAR nach Chr.", "range", [0, 3], [true]]
["YEAR bc - YEAR n. Chr.", "range", [0, 3], [true]]
["YEAR bc - YEAR nach Chr.", "range", [0, 3], [true]]
["YEAR ac - YEAR n. Chr.", "range", [0, 3], [true]]
["YEAR ac - YEAR nach Chr.", "range", [0, 3], [true]]
["bis YEAR", "yearRange", [1], [false, true]]
["um YEAR", "yearRange", [1], [false, true, true], "AROUND"]
["ca. YEAR", "yearRange", [1], [false, true, true]]
["um YEAR bc", "yearRange", [1], [true, true, true]]
["um YEAR v. Chr.", "yearRange", [1], [true, true, true], "AROUND_BC"]
["ca. YEAR bc", "yearRange", [1], [true, true, true]]
["ca. YEAR v. Chr.", "yearRange", [1], [true, true, true]]
["vor YEAR", "yearRange", [1], [false, true], "BEFORE"]
["vor YEAR bc", "yearRange", [1], [true, true]]
["vor YEAR v. Chr.", "yearRange", [1], [true, true], "BEFORE_BC"]
["nach YEAR", "yearRange", [1], [false, false, true], "AFTER"]
["nach YEAR ad", "yearRange", [1], [false, false, true]]
["nach YEAR A.D.", "yearRange", [1], [false, false, true]]
["ab YEAR", "yearRange", [1], [false, false, true]]
["ab YEAR ad", "yearRange", [1], [false, false, true]]
["ab YEAR A.D.", "yearRange", [1], [false, false, true]]
["nach YEAR bc", "yearRange", [1], [true, false, true]]
["nach YEAR v. Chr.", "yearRange", [1], [true, false, true], "AFTER_BC"]
["YEAR v. Chr.", "getFromTo", [0], [true]]
["YEAR n. Chr.", "getFromTo", [0]]
["YEAR_DOT Jhd. vor Chr", "century", [0], [true]]
["YEAR_DOT Jhd. vor Chr.", "century", [0], [true]]
["YEAR_DOT Jhd. v. Chr", "century", [0], [true]]
["YEAR_DOT Jhd. v. Chr.", "century", [0], [true], "CENTURY_BC"]
["YEAR_DOT Jhd vor Chr", "century", [0], [true]]
["YEAR_DOT Jhd vor Chr.", "century", [0], [true]]
["YEAR_DOT Jhd v. Chr", "century", [0], [true]]
["YEAR_DOT Jhd v. Chr.", "century", [0], [true]]
["YEAR_DOT Jh vor Chr", "century", [0], [true]]
["YEAR_DOT Jh vor Chr.", "century", [0], [true]]
["YEAR_DOT Jh v. Chr", "century", [0], [true]]
["YEAR_DOT Jh v. Chr.", "century", [0], [true]]
["YEAR_DOT Jh. vor Chr", "century", [0], [true]]
["YEAR_DOT Jh. vor Chr.", "century", [0], [true]]
["YEAR_DOT Jh. v. Chr", "century", [0], [true]]
["YEAR_DOT Jh. v. Chr.", "century", [0], [true]]
["YEAR Jhd. vor Chr", "century", [0], [true]]
["YEAR Jhd. vor Chr.", "century", [0], [true]]
["YEAR Jhd. v. Chr", "century", [0], [true]]
["YEAR Jhd. v. Chr.", "century", [0], [true]]
["YEAR Jhd vor Chr", "century", [0], [true]]
["YEAR Jhd vor Chr.", "century", [0], [true]]
["YEAR Jhd v. Chr", "century", [0], [true]]
["YEAR Jhd v. Chr.", "century", [0], [true]]
["YEAR Jhd ac", "century", [0], [true]]
["YEAR Jh ac", "century", [0], [true]]
["YEAR Jh. ac", "century", [0], [true]]
["YEAR Jhd.", "century", [0]]
["YEAR Jhd", "century", [0]]
["YEAR Jh", "century", [0]]
["YEAR Jh.", "century", [0]]
["YEAR_DOT Jhd.", "century", [0], null, "CENTURY"]
["YEAR_DOT Jhd", "century", [0]]
["YEAR_DOT Jhd nach Chr.", "century", [0]]
["YEAR_DOT Jhd. nach Chr.", "century", [0]]
["YEAR_DOT Jhd. nach Chr", "century", [0]]
["YEAR_DOT Jhd nach Chr", "century", [0]]
["YEAR_DOT Jhd. n. Chr.", "century", [0]]
["YEAR_DOT Jhd. n. Chr", "century", [0]]
["YEAR_DOT Jhd n. Chr.", "century", [0]]
["YEAR_DOT Jhd n. Chr", "century", [0]]
["YEAR_DOT Jt. v. Chr.", "millennium", [0], [true], "MILLENNIUM_BC"]
["YEAR_DOT Jt v. Chr.", "millennium", [0], [true]]
["YEAR_DOT Jt bc", "millennium", [0], [true]]
["YEAR_DOT Jt. bc", "millennium", [0], [true]]
["YEAR_DOT Jt BC", "millennium", [0], [true]]
["YEAR_DOT Jt. BC", "millennium", [0], [true]]
["YEAR_DOT Jt.", "millennium", [0], null, "MILLENNIUM"]
["YEAR_DOT Jt.", "millennium", [0]]
["YEAR_DOT Jt", "millennium", [0]]
["YEAR Jt. v. Chr.", "millennium", [0], [true]]
["YEAR Jt v. Chr.", "millennium", [0], [true]]
["YEAR Jt bc", "millennium", [0], [true]]
["YEAR Jt. bc", "millennium", [0], [true]]
["YEAR Jt BC", "millennium", [0], [true]]
["YEAR Jt. BC", "millennium", [0], [true]]
["YEAR Jt.", "millennium", [0]]
["YEAR Jt.", "millennium", [0]]
["YEAR Jt", "millennium", [0]]
["Anfang YEAR_DOT Jhd", "earlyCentury", [1]]
["Anfang YEAR_DOT Jh", "earlyCentury", [1]]
["Anfang YEAR_DOT Jh.", "earlyCentury", [1], null, "EARLY_CENTURY"]
["Anfang YEAR_DOT Jhd v. Chr.", "earlyCentury", [1], [true]]
["Anfang YEAR_DOT Jh v. Chr.", "earlyCentury", [1], [true]]
["Anfang YEAR_DOT Jh. v. Chr.", "earlyCentury", [1], [true], "EARLY_CENTURY_BC"]
["Ende YEAR_DOT Jhd", "lateCentury", [1]]
["Ende YEAR_DOT Jh", "lateCentury", [1]]
["Ende YEAR_DOT Jh.", "lateCentury", [1], null, "LATE_CENTURY"]
["Ende YEAR_DOT Jhd v. Chr.", "lateCentury", [1], [true]]
["Ende YEAR_DOT Jh v. Chr.", "lateCentury", [1], [true]]
["Ende YEAR_DOT Jh. v. Chr.", "lateCentury", [1], [true], "LATE_CENTURY_BC"]
["YEAR_DOT Jhd. - YEAR_DOT Jhd.", "centuryRange", [0, 3], null, "CENTURY_RANGE"]
["YEAR_DOT Jhd - YEAR_DOT Jhd", "centuryRange", [0, 3]]
["YEAR Jhd. - YEAR Jhd.", "centuryRange", [0, 3]]
["YEAR Jhd - YEAR Jhd", "centuryRange", [0, 3]]
["YEAR Jh. - YEAR Jh.", "centuryRange", [0, 3]]
["YEAR Jh - YEAR Jh", "centuryRange", [0, 3]]
["YEAR_DOT Jh. - YEAR_DOT Jh.", "centuryRange", [0, 3]]
["YEAR_DOT Jh - YEAR_DOT Jh", "centuryRange", [0, 3]]
["YEAR_DOT Jhd. v. Chr. - YEAR_DOT Jhd.", "centuryRange", [0, 5], [true], "CENTURY_RANGE_FROM_BC"]
["YEAR_DOT Jhd v. Chr. - YEAR_DOT Jhd", "centuryRange", [0, 5], [true]]
["YEAR Jhd. v. Chr. - YEAR Jhd.", "centuryRange", [0, 5], [true]]
["YEAR Jhd v. Chr. - YEAR Jhd", "centuryRange", [0, 5], [true]]
["YEAR Jh. v. Chr. - YEAR Jh.", "centuryRange", [0, 5], [true]]
["YEAR Jh v. Chr. - YEAR Jh", "centuryRange", [0, 5], [true]]
["YEAR_DOT Jh. v. Chr. - YEAR_DOT Jh.", "centuryRange", [0, 5], [true]]
["YEAR_DOT Jh v. Chr. - YEAR_DOT Jh", "centuryRange", [0, 5], [true]]
["YEAR_DOT Jhd. v. Chr. - YEAR_DOT Jhd. v. Chr.", "centuryRange", [0, 5], [true, true], "CENTURY_RANGE_BC"]
["YEAR_DOT Jhd v. Chr. - YEAR_DOT Jhd v. Chr.", "centuryRange", [0, 5], [true, true]]
["YEAR Jhd. v. Chr. - YEAR Jhd. v. Chr.", "centuryRange", [0, 5], [true, true]]
["YEAR Jhd v. Chr. - YEAR Jhd v. Chr.", "centuryRange", [0, 5], [true, true]]
["YEAR Jh. v. Chr. - YEAR Jh. v. Chr.", "centuryRange", [0, 5], [true, true]]
["YEAR Jh v. Chr. - YEAR Jh v. Chr.", "centuryRange", [0, 5], [true, true]]
["YEAR_DOT Jh. v. Chr. - YEAR_DOT Jh. v. Chr.", "centuryRange", [0, 5], [true, true]]
["YEAR_DOT Jh v. Chr. - YEAR_DOT Jh v. Chr.", "centuryRange", [0, 5], [true, true]]
]
@PARSE_GRAMMARS["en-US"] = [
["DATE to DATE", "range", [0, 2], null, "RANGE"]
["YEAR to YEAR", "range", [0, 2], null, "RANGE_YEAR"]
["YEAR - YEAR A.D.", "range", [0, 2]]
["YEAR - YEAR AD", "range", [0, 2]]
["YEAR to YEAR A.D.", "range", [0, 2]]
["YEAR to YEAR AD", "range", [0, 2]]
["from YEAR to YEAR", "range", [1, 3]]
["YEAR BC - YEAR A.D.", "range", [0, 3], [true]]
["YEAR BC - YEAR AD", "range", [0, 3], [true]]
["YEAR BC - YEAR CE", "range", [0, 3], [true]]
["YEAR BC - YEAR ad", "range", [0, 3], [true]]
["YEAR B.C. - YEAR A.D.", "range", [0, 3], [true]]
["YEAR B.C. - YEAR AD", "range", [0, 3], [true]]
["YEAR B.C. - YEAR CE", "range", [0, 3], [true]]
["YEAR B.C. - YEAR ad", "range", [0, 3], [true]]
["YEAR B.C. to YEAR", "range", [0, 3], [true]]
["YEAR bc - YEAR A.D.", "range", [0, 3], [true]]
["YEAR bc - YEAR AD", "range", [0, 3], [true]]
["YEAR bc - YEAR CE", "range", [0, 3], [true]]
["YEAR bc - YEAR ad", "range", [0, 3], [true]]
["YEAR ac - YEAR A.D.", "range", [0, 3], [true]]
["YEAR ac - YEAR AD", "range", [0, 3], [true]]
["YEAR ac - YEAR CE", "range", [0, 3], [true]]
["YEAR ac - YEAR ad", "range", [0, 3], [true]]
["YEAR - YEAR BC", "range", [0, 2], [true, true]]
["YEAR - YEAR B.C.", "range", [0, 2], [true, true]]
["MONTH YEAR", "monthRange", [0, 1]]
["after YEAR", "yearRange", [1], [false, false, true], "AFTER"]
["after YEAR BC", "yearRange", [1], [true, false, true], "AFTER_BC"]
["before YEAR", "yearRange", [1], [false, true], "BEFORE"]
["before YEAR BC", "yearRange", [1], [true, true], "BEFORE_BC"]
["around YEAR", "yearRange", [1], [false, true, true], "AROUND"]
["around YEAR BC", "yearRange", [1], [true, true, true], "AROUND_BC"]
["YEAR_DOT millennium", "millennium", [0], null, "MILLENNIUM"]
["YEAR_DOT millennium BC", "millennium", [0], [true], "MILLENNIUM_BC"]
["YEAR millennium", "millennium", [0]]
["YEAR millennium BC", "millennium", [0], [true]]
["YEAR BCE", "getFromTo", [0], [true]]
["YEAR bc", "getFromTo", [0], [true]]
["YEAR BC", "getFromTo", [0], [true]]
["YEAR B.C.", "getFromTo", [0], [true]]
["YEAR AD", "getFromTo", [0]]
["YEAR A.D.", "getFromTo", [0]]
["CENTURY century", "century", [0], null, "CENTURY"]
["CENTURY century BC", "century", [0], [true], "CENTURY_BC"]
["Early CENTURY century", "earlyCentury", [1], null, "EARLY_CENTURY"]
["Early CENTURY century BC", "earlyCentury", [1], [true], "EARLY_CENTURY_BC"]
["Late CENTURY century", "lateCentury", [1], null, "LATE_CENTURY"]
["Late CENTURY century BC", "lateCentury", [1], [true], "LATE_CENTURY_BC"]
["CENTURY century - CENTURY century", "centuryRange", [0, 3], null, "CENTURY_RANGE"]
["CENTURY century BC - CENTURY century", "centuryRange", [0, 4], [true], "CENTURY_RANGE_FROM_BC"]
["CENTURY century B.C. - CENTURY century", "centuryRange", [0, 4], [true]]
["CENTURY century BC - CENTURY century BC", "centuryRange", [0, 4], [true, true], "CENTURY_RANGE_BC"]
["CENTURY century B.C. - CENTURY century B.C.", "centuryRange", [0, 4], [true, true]]
]
@dateRangeToString: (from, to) ->
if not CUI.util.isString(from) or not CUI.util.isString(to)
return
locale = CUI.DateTime.getLocale()
fromMoment = CUI.DateTimeRangeGrammar.getMoment(from)
toMoment = CUI.DateTimeRangeGrammar.getMoment(to)
if not fromMoment?.isValid() or not toMoment?.isValid()
return CUI.DateTimeFormats[locale].formats[0].invalid
if CUI.DateTimeRangeGrammar.REGEXP_YEAR.test(from)
fromIsYear = true
fromYear = parseInt(from)
else if fromMoment.isValid() and fromMoment.date() == 1 and fromMoment.month() == 0 # First day of year.
fromMoment.add(1, "day") # This is a workaround to avoid having the wrong year after parsing the timezone.
fromMoment.parseZone()
fromYear = fromMoment.year()
if from == to
return CUI.DateTime.format(from, "display_short")
if CUI.DateTimeRangeGrammar.REGEXP_YEAR.test(to)
toIsYear = true
toYear = parseInt(to)
else if toMoment.isValid() and toMoment.date() == 31 and toMoment.month() == 11 # Last day of year
toMoment.add(1, "day")
toMoment.parseZone()
toYear = toMoment.year()
grammars = CUI.DateTimeRangeGrammar.PARSE_GRAMMARS[locale]
if not grammars
return
getPossibleString = (key, parameters) ->
for _grammar in grammars
if _grammar[4] == key
grammar = _grammar
break
if not grammar
return
possibleStringArray = grammar[0].split(CUI.DateTimeRangeGrammar.REGEXP_SPACE)
tokenPositions = grammar[2]
for value, index in tokenPositions
if parameters[index]
if possibleStringArray[value] == "YEAR_DOT"
parameters[index] += "."
else if possibleStringArray[value] == "CENTURY"
parameters[index] += "th"
else if CUI.util.isString(parameters[index])
parameters[index] = CUI.DateTime.format(parameters[index], "display_short")
possibleStringArray[value] = parameters[index]
possibleString = possibleStringArray.join(" ")
output = CUI.DateTimeRangeGrammar.stringToDateRange(possibleString)
if not output or output.to != to or output.from != from
return
return possibleString.replace(" #{DateTimeRangeGrammar.DASH} ", " #{DateTimeRangeGrammar.EN_DASH} ")
if not CUI.util.isUndef(fromYear) and not CUI.util.isUndef(toYear)
if fromYear == toYear
return "#{fromYear}"
isBC = fromYear < 0
if isBC
possibleString = getPossibleString("AFTER_BC", [Math.abs(fromYear)])
else
possibleString = getPossibleString("AFTER", [Math.abs(fromYear)])
if possibleString
return possibleString
isBC = toYear < 0
if isBC
possibleString = getPossibleString("BEFORE_BC", [Math.abs(toYear)])
else
possibleString = getPossibleString("BEFORE", [Math.abs(toYear)])
if possibleString
return possibleString
centerYear = (toYear + fromYear) / 2
isBC = centerYear <= 0
if isBC
possibleString = getPossibleString("AROUND_BC", [Math.abs(centerYear)])
else
possibleString = getPossibleString("AROUND", [Math.abs(centerYear)])
if possibleString
return possibleString
yearsDifference = toYear - fromYear
if yearsDifference == 999 # Millennium
isBC = toYear <= 0
if isBC
millennium = (-from + 1) / 1000
possibleString = getPossibleString("MILLENNIUM_BC", [millennium])
else
millennium = to / 1000
possibleString = getPossibleString("MILLENNIUM", [millennium])
if possibleString
return possibleString
else if yearsDifference == 99 # Century
isBC = toYear <= 0
if isBC
century = -(fromYear - 1) / 100
possibleString = getPossibleString("CENTURY_BC", [century])
else
century = toYear / 100
possibleString = getPossibleString("CENTURY", [century])
if possibleString
return possibleString
else if yearsDifference == 15 # Early/Late
isBC = fromYear <= 0
century = Math.ceil(Math.abs(fromYear) / 100)
if isBC
for key in ["EARLY_CENTURY_BC", "LATE_CENTURY_BC"]
possibleString = getPossibleString(key, [century])
if possibleString
return possibleString
else
for key in ["EARLY_CENTURY", "LATE_CENTURY"]
possibleString = getPossibleString(key, [century])
if possibleString
return possibleString
else if (yearsDifference + 1) % 100 == 0 and (fromYear - 1) % 100 == 0 and toYear % 100 == 0
toCentury = (toYear / 100)
if fromYear < 0
fromCentury = -(fromYear - 1) / 100
if toYear <= 0
toCentury += 1
grammarKey = "CENTURY_RANGE_BC"
else
grammarKey = "CENTURY_RANGE_FROM_BC"
else
grammarKey = "CENTURY_RANGE"
fromCentury = (fromYear + 99) / 100
toCentury = toYear / 100
possibleString = getPossibleString(grammarKey, [fromCentury, toCentury])
if possibleString
return possibleString
# Month range XXXX-XX-01 - XXXX-XX-31
if fromMoment.year() == toMoment.year() and
fromMoment.month() == toMoment.month() and
fromMoment.date() == 1 and toMoment.date() == toMoment.endOf("month").date()
for format in CUI.DateTimeFormats[locale].formats
if format.display_attribute == CUI.DateTimeRangeGrammar.DISPLAY_ATTRIBUTE_YEAR_MONTH
month = CUI.DateTimeRangeGrammar.MONTHS[locale][toMoment.month()]
return "#{month} #{toMoment.year()}"
if fromIsYear and toIsYear
possibleString = getPossibleString("RANGE_YEAR", [from, to])
if possibleString
return possibleString
if fromIsYear or toIsYear
if fromIsYear
from = CUI.DateTime.format(from, "display_short")
if toIsYear
to = CUI.DateTime.format(to, "display_short")
# Removes the 'BC' / v. Chr. from 'from' to only show it in the end. For example: 15 - 10 v. Chr.
fromSplit = from.split(CUI.DateTimeRangeGrammar.REGEXP_SPACE)
toSplit = to.split(CUI.DateTimeRangeGrammar.REGEXP_SPACE)
if fromSplit[1] == toSplit[1]
from = fromSplit[0]
return "#{from} - #{to}"
possibleString = getPossibleString("RANGE", [from, to])
if possibleString
return possibleString
return "#{from} #{DateTimeRangeGrammar.EN_DASH} #{to}"
# Main method to check against every grammar.
@stringToDateRange: (input) ->
if CUI.util.isEmpty(input) or not CUI.util.isString(input)
return error: "Input needs to be a non empty string: #{input}"
locale = CUI.DateTime.getLocale()
input = input.trim()
input = input.replace(DateTimeRangeGrammar.REGEXP_DASH, DateTimeRangeGrammar.DASH)
tokens = []
for s in input.split(CUI.DateTimeRangeGrammar.REGEXP_SPACE)
value = s
if CUI.DateTimeRangeGrammar.REGEXP_DATE.test(s) or CUI.DateTimeRangeGrammar.REGEXP_MONTH.test(s)
type = CUI.DateTimeRangeGrammar.TYPE_DATE
else if CUI.DateTimeRangeGrammar.REGEXP_YEAR.test(s)
type = CUI.DateTimeRangeGrammar.TYPE_YEAR
else if CUI.DateTimeRangeGrammar.REGEXP_YEAR_DOT.test(s)
type = CUI.DateTimeRangeGrammar.TYPE_YEAR_DOT
value = s.split(".")[0]
else if CUI.DateTimeRangeGrammar.REGEXP_CENTURY.test(s)
type = CUI.DateTimeRangeGrammar.TYPE_CENTURY
value = s.split("th")[0]
else if value in CUI.DateTimeRangeGrammar.MONTHS[locale]
type = CUI.DateTimeRangeGrammar.TYPE_MONTH
value = CUI.DateTimeRangeGrammar.MONTHS[locale].indexOf(value)
else
type = s # The type for everything else is the value.
tokens.push
type: type
value: value
stringToParse = tokens.map((token) -> token.type).join(" ").toUpperCase()
# Check if there is a grammar that applies to the input.
for _, grammars of CUI.DateTimeRangeGrammar.PARSE_GRAMMARS
for grammar in grammars
if grammar[0].toUpperCase() == stringToParse
method = CUI.DateTimeRangeGrammar[grammar[1]]
if not CUI.util.isFunction(method) or not grammar[2]
continue
tokenPositions = grammar[2]
if CUI.util.isArray(tokenPositions)
if tokenPositions.length == 0
continue
methodArguments = tokenPositions.map((index) -> tokens[index].value)
else
methodArguments = [tokenPositions]
if extraArguments = grammar[3]
if CUI.util.isArray(extraArguments)
methodArguments = methodArguments.concat(extraArguments)
else
methodArguments.push(extraArguments)
value = method.apply(@, methodArguments)
if value
return value
# If there is no grammar available, we try to parse the date.
[from, to] = input.split(/\s+\-\s+/)
if from and to
output = CUI.DateTimeRangeGrammar.range(from, to)
if output
return output
output = CUI.DateTimeRangeGrammar.getFromTo(from)
if output
return output
return error: "NoDateRangeFound #{input}"
@millennium: (millennium, isBC) ->
if isBC
from = -(millennium * 1000 - 1)
to = -((millennium - 1) * 1000)
else
to = millennium * 1000
from = to - 999
return CUI.DateTimeRangeGrammar.getFromToWithRange("#{from}", "#{to}")
@century: (century, isBC) ->
century = century * 100
if isBC
to = -(century - 100)
from = -century + 1
else
to = century
from = century - 99
return CUI.DateTimeRangeGrammar.getFromToWithRange("#{from}", "#{to}")
@centuryRange: (centuryFrom, centuryTo, fromIsBC, toIsBC) ->
from = @century(centuryFrom, fromIsBC)
to = @century(centuryTo, toIsBC)
return from: from?.from, to: to?.to
# 15 -> 1401 - 1416
# 15 -> 1499 1484
@earlyCentury: (century, isBC) ->
century = century * 100
if isBC
from = -century + 1
to = from + 15
else
from = century - 99
to = from + 15
return CUI.DateTimeRangeGrammar.getFromToWithRange("#{from}", "#{to}")
# 15 - -1416 -1401
# 15 - 1484 - 1499
@lateCentury: (century, isBC) ->
century = century * 100
if isBC
to = -(century - 101)
from = to - 15
else
to = century
from = to - 15
return CUI.DateTimeRangeGrammar.getFromToWithRange("#{from}", "#{to}")
@range: (from, to, fromBC = false, toBC = false) ->
if toBC and not to.startsWith(CUI.DateTimeRangeGrammar.DASH)
to = @__toBC(to)
if (fromBC or toBC) and not from.startsWith(CUI.DateTimeRangeGrammar.DASH)
from = @__toBC(from)
return CUI.DateTimeRangeGrammar.getFromToWithRange(from, to)
@monthRange: (month, year) ->
momentDate = CUI.DateTimeRangeGrammar.getMoment(year)
momentDate.month(month)
momentDate.startOf("month")
from = CUI.DateTimeRangeGrammar.format(momentDate, false)
momentDate.endOf("month")
to= CUI.DateTimeRangeGrammar.format(momentDate, false)
return from: from, to: to
@yearRange: (year, isBC = false, fromAddYears = false, toAddYears = false) ->
if isBC and not year.startsWith(CUI.DateTimeRangeGrammar.DASH)
year = "-#{year}"
momentInputFrom = CUI.DateTimeRangeGrammar.getMoment(year)
if not momentInputFrom?.isValid()
return
if not year.startsWith(CUI.DateTimeRangeGrammar.DASH)
momentInputFrom.add(1, "day") # This is a workaround to avoid having the wrong year after parsing the timezone.
momentInputFrom.parseZone()
if fromAddYears or toAddYears
_year = momentInputFrom.year()
if _year % 1000 == 0
yearsToAdd = 500
else if _year % 100 == 0
yearsToAdd = 50
else if _year % 50 == 0
yearsToAdd = 15
else if _year % 10 == 0
yearsToAdd = 5
else
yearsToAdd = 2
momentInputTo = momentInputFrom.clone()
if fromAddYears
momentInputFrom.add(-yearsToAdd, "year")
if toAddYears
momentInputTo.add(yearsToAdd, "year")
if not year.startsWith(CUI.DateTimeRangeGrammar.DASH)
momentInputTo.add(1, "day")
momentInputTo.parseZone()
momentInputFrom.startOf("year")
momentInputTo.endOf("year")
from = CUI.DateTimeRangeGrammar.format(momentInputFrom)
to = CUI.DateTimeRangeGrammar.format(momentInputTo)
return from: from, to: to
@getFromTo: (inputString, isBC = false) ->
if isBC and not inputString.startsWith(CUI.DateTimeRangeGrammar.DASH)
inputString = @__toBC(inputString)
momentInput = CUI.DateTimeRangeGrammar.getMoment(inputString)
if not momentInput?.isValid()
return
if inputString.match(CUI.DateTimeRangeGrammar.REGEXP_YEAR)
if not inputString.startsWith(CUI.DateTimeRangeGrammar.DASH)
momentInput.add(1, "day")
momentInput.parseZone()
from = to = CUI.DateTimeRangeGrammar.format(momentInput)
else if inputString.match(CUI.DateTimeRangeGrammar.REGEXP_MONTH)
from = CUI.DateTimeRangeGrammar.format(momentInput, false)
momentInput.endOf('month');
to = CUI.DateTimeRangeGrammar.format(momentInput, false)
else
from = to = CUI.DateTimeRangeGrammar.format(momentInput, false)
return from: from, to: to
@getFromToWithRange: (fromDate, toDate) ->
from = CUI.DateTimeRangeGrammar.getFromTo(fromDate)
to = CUI.DateTimeRangeGrammar.getFromTo(toDate)
if not from or not to
return
return from: from.from, to: to.to
@format: (dateMoment, yearFormat = true) ->
if yearFormat
outputType = CUI.DateTimeRangeGrammar.OUTPUT_YEAR
else
outputType = CUI.DateTimeRangeGrammar.OUTPUT_DATE
return CUI.DateTime.format(dateMoment, CUI.DateTimeRangeGrammar.STORE_FORMAT, outputType)
@getMoment: (inputString) ->
if not CUI.util.isString(inputString)
return
dateTime = new CUI.DateTime()
momentInput = dateTime.parseValue(inputString);
if !momentInput.isValid() and inputString.startsWith(DateTimeRangeGrammar.DASH)
# This is a workaround for moment.js when strings are like: "-2020-11-05T10:00:00+00:00" or "-0100-01-01"
# Moment js does not support negative full dates, therefore we create a moment without the negative character
# and then we make the year negative.
inputString = inputString.substring(1)
momentInput = dateTime.parseValue(inputString);
momentInput.year(-momentInput.year())
dateTime.destroy()
return momentInput
@__toBC: (inputString) ->
if inputString.match(CUI.DateTimeRangeGrammar.REGEXP_YEAR)
inputString = parseInt(inputString) - 1
return "-#{inputString}" | 192531 | class CUI.DateTimeRangeGrammar
@REGEXP_DATE = /^[0-9]+[-/.][0-9]+[-/.][0-9]+$/ # Exact date
@REGEXP_MONTH = /^[0-9]+[-/.][0-9]+$/ # Matches if the date has Year and month (no day)
@REGEXP_YEAR = /^\-?[0-9]+$/ # Matches if the date has Year. (no day, no month)
@REGEXP_YEAR_DOT = /^[0-9]+.$/ # Matches Year ending with dot.
@REGEXP_CENTURY = /^[0-9]+th$/ # Matches Year ending with th.
@REGEXP_SPACE = /\s+/
@REGEXP_DASH = /[\–\—]/g # Matches 'EN' and 'EM' dashes.
@TYPE_DATE = "DATE"
@TYPE_YEAR = "YEAR"
@TYPE_YEAR_DOT = "YEAR_DOT"
@TYPE_CENTURY = "CENTURY"
@TYPE_CENTURY_RANGE = "CENTURY_RANGE"
@TYPE_MONTH = "MONTH"
@DASH = "-"
@STORE_FORMAT = "store"
@OUTPUT_YEAR = "year"
@OUTPUT_DATE = "date"
@DISPLAY_ATTRIBUTE_YEAR_MONTH = "year-month"
@EN_DASH = "–"
@MONTHS = {}
@MONTHS["de-DE"] = [
"Januar"
"Februar"
"März"
"April"
"Mai"
"Juni"
"Juli"
"August"
"September"
"Oktober"
"November"
"Dezember"
]
@MONTHS["en-US"] = [
"January"
"February"
"March"
"April"
"May"
"June"
"July"
"August"
"September"
"October"
"November"
"December"
]
### How to add new grammars:
# [<GRAMMAR>, <FUNCTION>, <ARRAY_TOKEN_POSITION>, <ARRAY_FUNCTION_ARGUMENTS>, <KEY>]
#
# GRAMMAR: Plain text with tokens to identify dates.
# - Tokens available: DATE (full date), YEAR (only year), YEAR_DOT (year with dot), CENTURY (year with th)
#
# FUNCTION: Function which is going to be used to parse, in string.
# - Functions available: millennium, century, earlyCentury, lateCentury, range, yearRange, getFromTo
#
# ARRAY_TOKEN_POSITION: Array of integers with the position of the date tokens.
# ARRAY_FUNCTION_ARGUMENTS: (optional) Array with arguments that will be given to the function.
# - Dates are given as arguments automatically.
#
# KEY: (optional) Identifier that is used in the format method.
###
@PARSE_GRAMMARS = {} # TODO: Add ES & IT.
@PARSE_GRAMMARS["de-DE"] = [
["DATE bis DATE", "range", [0, 2], null, "RANGE"]
["YEAR bis YEAR", "range", [0, 2], null, "RANGE_YEAR"]
["YEAR - YEAR n. Chr.", "range", [0, 2]]
["YEAR bis YEAR n. Chr.", "range", [0, 2]]
["zwischen YEAR bis YEAR", "range", [1, 3]]
["zwischen YEAR und YEAR", "range", [1, 3]]
["zwischen DATE bis DATE", "range", [1, 3]]
["zwischen DATE und DATE", "range", [1, 3]]
["von YEAR bis YEAR", "range", [1, 3]]
["YEAR v. Chr. - YEAR n. Chr.", "range", [0, 4], [true]]
["YEAR - YEAR v. Chr.", "range", [0, 2], [true, true]]
["YEAR BC - YEAR n. Chr.", "range", [0, 3], [true]]
["YEAR BC - YEAR nach Chr.", "range", [0, 3], [true]]
["YEAR B.C. - YEAR n. Chr.", "range", [0, 3], [true]]
["YEAR B.C. - YEAR nach Chr.", "range", [0, 3], [true]]
["YEAR bc - YEAR n. Chr.", "range", [0, 3], [true]]
["YEAR bc - YEAR nach Chr.", "range", [0, 3], [true]]
["YEAR ac - YEAR n. Chr.", "range", [0, 3], [true]]
["YEAR ac - YEAR nach Chr.", "range", [0, 3], [true]]
["bis YEAR", "yearRange", [1], [false, true]]
["um YEAR", "yearRange", [1], [false, true, true], "AROUND"]
["ca. YEAR", "yearRange", [1], [false, true, true]]
["um YEAR bc", "yearRange", [1], [true, true, true]]
["um YEAR v. Chr.", "yearRange", [1], [true, true, true], "AROUND_BC"]
["ca. YEAR bc", "yearRange", [1], [true, true, true]]
["ca. YEAR v. Chr.", "yearRange", [1], [true, true, true]]
["vor YEAR", "yearRange", [1], [false, true], "BEFORE"]
["vor YEAR bc", "yearRange", [1], [true, true]]
["vor YEAR v. Chr.", "yearRange", [1], [true, true], "BEFORE_BC"]
["nach YEAR", "yearRange", [1], [false, false, true], "AFTER"]
["nach YEAR ad", "yearRange", [1], [false, false, true]]
["nach YEAR A.D.", "yearRange", [1], [false, false, true]]
["ab YEAR", "yearRange", [1], [false, false, true]]
["ab YEAR ad", "yearRange", [1], [false, false, true]]
["ab YEAR A.D.", "yearRange", [1], [false, false, true]]
["nach YEAR bc", "yearRange", [1], [true, false, true]]
["nach YEAR v. Chr.", "yearRange", [1], [true, false, true], "AFTER_BC"]
["YEAR v. Chr.", "getFromTo", [0], [true]]
["YEAR n. Chr.", "getFromTo", [0]]
["YEAR_DOT Jhd. vor Chr", "century", [0], [true]]
["YEAR_DOT Jhd. vor Chr.", "century", [0], [true]]
["YEAR_DOT Jhd. v. Chr", "century", [0], [true]]
["YEAR_DOT Jhd. v. Chr.", "century", [0], [true], "CENTURY_BC"]
["YEAR_DOT Jhd vor Chr", "century", [0], [true]]
["YEAR_DOT Jhd vor Chr.", "century", [0], [true]]
["YEAR_DOT Jhd v. Chr", "century", [0], [true]]
["YEAR_DOT Jhd v. Chr.", "century", [0], [true]]
["YEAR_DOT Jh vor Chr", "century", [0], [true]]
["YEAR_DOT Jh vor Chr.", "century", [0], [true]]
["YEAR_DOT Jh v. Chr", "century", [0], [true]]
["YEAR_DOT Jh v. Chr.", "century", [0], [true]]
["YEAR_DOT Jh. vor Chr", "century", [0], [true]]
["YEAR_DOT Jh. vor Chr.", "century", [0], [true]]
["YEAR_DOT Jh. v. Chr", "century", [0], [true]]
["YEAR_DOT Jh. v. Chr.", "century", [0], [true]]
["YEAR Jhd. vor Chr", "century", [0], [true]]
["YEAR Jhd. vor Chr.", "century", [0], [true]]
["YEAR Jhd. v. Chr", "century", [0], [true]]
["YEAR Jhd. v. Chr.", "century", [0], [true]]
["YEAR Jhd vor Chr", "century", [0], [true]]
["YEAR Jhd vor Chr.", "century", [0], [true]]
["YEAR Jhd v. Chr", "century", [0], [true]]
["YEAR Jhd v. Chr.", "century", [0], [true]]
["YEAR Jhd ac", "century", [0], [true]]
["YEAR Jh ac", "century", [0], [true]]
["YEAR Jh. ac", "century", [0], [true]]
["YEAR Jhd.", "century", [0]]
["YEAR Jhd", "century", [0]]
["YEAR Jh", "century", [0]]
["YEAR Jh.", "century", [0]]
["YEAR_DOT Jhd.", "century", [0], null, "CENTURY"]
["YEAR_DOT Jhd", "century", [0]]
["YEAR_DOT Jhd nach Chr.", "century", [0]]
["YEAR_DOT Jhd. nach Chr.", "century", [0]]
["YEAR_DOT Jhd. nach Chr", "century", [0]]
["YEAR_DOT Jhd nach Chr", "century", [0]]
["YEAR_DOT Jhd. n. Chr.", "century", [0]]
["YEAR_DOT Jhd. n. Chr", "century", [0]]
["YEAR_DOT Jhd n. Chr.", "century", [0]]
["YEAR_DOT Jhd n. Chr", "century", [0]]
["YEAR_DOT Jt. v. Chr.", "millennium", [0], [true], "MILLENNIUM_BC"]
["YEAR_DOT Jt v. Chr.", "millennium", [0], [true]]
["YEAR_DOT Jt bc", "millennium", [0], [true]]
["YEAR_DOT Jt. bc", "millennium", [0], [true]]
["YEAR_DOT Jt BC", "millennium", [0], [true]]
["YEAR_DOT Jt. BC", "millennium", [0], [true]]
["YEAR_DOT Jt.", "millennium", [0], null, "MILLENNIUM"]
["YEAR_DOT Jt.", "millennium", [0]]
["YEAR_DOT Jt", "millennium", [0]]
["YEAR Jt. v. Chr.", "millennium", [0], [true]]
["YEAR Jt v. Chr.", "millennium", [0], [true]]
["YEAR Jt bc", "millennium", [0], [true]]
["YEAR Jt. bc", "millennium", [0], [true]]
["YEAR Jt BC", "millennium", [0], [true]]
["YEAR Jt. BC", "millennium", [0], [true]]
["YEAR Jt.", "millennium", [0]]
["YEAR Jt.", "millennium", [0]]
["YEAR Jt", "millennium", [0]]
["Anfang YEAR_DOT Jhd", "earlyCentury", [1]]
["Anfang YEAR_DOT Jh", "earlyCentury", [1]]
["Anfang YEAR_DOT Jh.", "earlyCentury", [1], null, "EARLY_CENTURY"]
["Anfang YEAR_DOT Jhd v. Chr.", "earlyCentury", [1], [true]]
["Anfang YEAR_DOT Jh v. Chr.", "earlyCentury", [1], [true]]
["Anfang YEAR_DOT Jh. v. Chr.", "earlyCentury", [1], [true], "EARLY_CENTURY_BC"]
["Ende YEAR_DOT Jhd", "lateCentury", [1]]
["Ende YEAR_DOT Jh", "lateCentury", [1]]
["Ende YEAR_DOT Jh.", "lateCentury", [1], null, "LATE_CENTURY"]
["Ende YEAR_DOT Jhd v. Chr.", "lateCentury", [1], [true]]
["Ende YEAR_DOT Jh v. Chr.", "lateCentury", [1], [true]]
["Ende YEAR_DOT Jh. v. Chr.", "lateCentury", [1], [true], "LATE_CENTURY_BC"]
["YEAR_DOT Jhd. - YEAR_DOT Jhd.", "centuryRange", [0, 3], null, "CENTURY_RANGE"]
["YEAR_DOT Jhd - YEAR_DOT Jhd", "centuryRange", [0, 3]]
["YEAR Jhd. - YEAR Jhd.", "centuryRange", [0, 3]]
["YEAR Jhd - YEAR Jhd", "centuryRange", [0, 3]]
["YEAR Jh. - YEAR Jh.", "centuryRange", [0, 3]]
["YEAR Jh - YEAR Jh", "centuryRange", [0, 3]]
["YEAR_DOT Jh. - YEAR_DOT Jh.", "centuryRange", [0, 3]]
["YEAR_DOT Jh - YEAR_DOT Jh", "centuryRange", [0, 3]]
["YEAR_DOT Jhd. v. Chr. - YEAR_DOT Jhd.", "centuryRange", [0, 5], [true], "CENTURY_RANGE_FROM_BC"]
["YEAR_DOT Jhd v. Chr. - YEAR_DOT Jhd", "centuryRange", [0, 5], [true]]
["YEAR Jhd. v. Chr. - YEAR Jhd.", "centuryRange", [0, 5], [true]]
["YEAR Jhd v. Chr. - YEAR Jhd", "centuryRange", [0, 5], [true]]
["YEAR Jh. v. Chr. - YEAR Jh.", "centuryRange", [0, 5], [true]]
["YEAR Jh v. Chr. - YEAR Jh", "centuryRange", [0, 5], [true]]
["YEAR_DOT Jh. v. Chr. - YEAR_DOT Jh.", "centuryRange", [0, 5], [true]]
["YEAR_DOT Jh v. Chr. - YEAR_DOT Jh", "centuryRange", [0, 5], [true]]
["YEAR_DOT Jhd. v. Chr. - YEAR_DOT Jhd. v. Chr.", "centuryRange", [0, 5], [true, true], "CENTURY_RANGE_BC"]
["YEAR_DOT Jhd v. Chr. - YEAR_DOT Jhd v. Chr.", "centuryRange", [0, 5], [true, true]]
["YEAR Jhd. v. Chr. - YEAR Jhd. v. Chr.", "centuryRange", [0, 5], [true, true]]
["YEAR Jhd v. Chr. - YEAR Jhd v. Chr.", "centuryRange", [0, 5], [true, true]]
["YEAR Jh. v. Chr. - YEAR Jh. v. Chr.", "centuryRange", [0, 5], [true, true]]
["YEAR Jh v. Chr. - YEAR Jh v. Chr.", "centuryRange", [0, 5], [true, true]]
["YEAR_DOT Jh. v. Chr. - YEAR_DOT Jh. v. Chr.", "centuryRange", [0, 5], [true, true]]
["YEAR_DOT Jh v. Chr. - YEAR_DOT Jh v. Chr.", "centuryRange", [0, 5], [true, true]]
]
@PARSE_GRAMMARS["en-US"] = [
["DATE to DATE", "range", [0, 2], null, "RANGE"]
["YEAR to YEAR", "range", [0, 2], null, "RANGE_YEAR"]
["YEAR - YEAR A.D.", "range", [0, 2]]
["YEAR - YEAR AD", "range", [0, 2]]
["YEAR to YEAR A.D.", "range", [0, 2]]
["YEAR to YEAR AD", "range", [0, 2]]
["from YEAR to YEAR", "range", [1, 3]]
["YEAR BC - YEAR A.D.", "range", [0, 3], [true]]
["YEAR BC - YEAR AD", "range", [0, 3], [true]]
["YEAR BC - YEAR CE", "range", [0, 3], [true]]
["YEAR BC - YEAR ad", "range", [0, 3], [true]]
["YEAR B.C. - YEAR A.D.", "range", [0, 3], [true]]
["YEAR B.C. - YEAR AD", "range", [0, 3], [true]]
["YEAR B.C. - YEAR CE", "range", [0, 3], [true]]
["YEAR B.C. - YEAR ad", "range", [0, 3], [true]]
["YEAR B.C. to YEAR", "range", [0, 3], [true]]
["YEAR bc - YEAR A.D.", "range", [0, 3], [true]]
["YEAR bc - YEAR AD", "range", [0, 3], [true]]
["YEAR bc - YEAR CE", "range", [0, 3], [true]]
["YEAR bc - YEAR ad", "range", [0, 3], [true]]
["YEAR ac - YEAR A.D.", "range", [0, 3], [true]]
["YEAR ac - YEAR AD", "range", [0, 3], [true]]
["YEAR ac - YEAR CE", "range", [0, 3], [true]]
["YEAR ac - YEAR ad", "range", [0, 3], [true]]
["YEAR - YEAR BC", "range", [0, 2], [true, true]]
["YEAR - YEAR B.C.", "range", [0, 2], [true, true]]
["MONTH YEAR", "monthRange", [0, 1]]
["after YEAR", "yearRange", [1], [false, false, true], "AFTER"]
["after YEAR BC", "yearRange", [1], [true, false, true], "AFTER_BC"]
["before YEAR", "yearRange", [1], [false, true], "BEFORE"]
["before YEAR BC", "yearRange", [1], [true, true], "BEFORE_BC"]
["around YEAR", "yearRange", [1], [false, true, true], "AROUND"]
["around YEAR BC", "yearRange", [1], [true, true, true], "AROUND_BC"]
["YEAR_DOT millennium", "millennium", [0], null, "MILLENNIUM"]
["YEAR_DOT millennium BC", "millennium", [0], [true], "MILLENNIUM_BC"]
["YEAR millennium", "millennium", [0]]
["YEAR millennium BC", "millennium", [0], [true]]
["YEAR BCE", "getFromTo", [0], [true]]
["YEAR bc", "getFromTo", [0], [true]]
["YEAR BC", "getFromTo", [0], [true]]
["YEAR B.C.", "getFromTo", [0], [true]]
["YEAR AD", "getFromTo", [0]]
["YEAR A.D.", "getFromTo", [0]]
["CENTURY century", "century", [0], null, "CENTURY"]
["CENTURY century BC", "century", [0], [true], "CENTURY_BC"]
["Early CENTURY century", "earlyCentury", [1], null, "EARLY_CENTURY"]
["Early CENTURY century BC", "earlyCentury", [1], [true], "EARLY_CENTURY_BC"]
["Late CENTURY century", "lateCentury", [1], null, "LATE_CENTURY"]
["Late CENTURY century BC", "lateCentury", [1], [true], "LATE_CENTURY_BC"]
["CENTURY century - CENTURY century", "centuryRange", [0, 3], null, "CENTURY_RANGE"]
["CENTURY century BC - CENTURY century", "centuryRange", [0, 4], [true], "CENTURY_RANGE_FROM_BC"]
["CENTURY century B.C. - CENTURY century", "centuryRange", [0, 4], [true]]
["CENTURY century BC - CENTURY century BC", "centuryRange", [0, 4], [true, true], "CENTURY_RANGE_BC"]
["CENTURY century B.C. - CENTURY century B.C.", "centuryRange", [0, 4], [true, true]]
]
@dateRangeToString: (from, to) ->
if not CUI.util.isString(from) or not CUI.util.isString(to)
return
locale = CUI.DateTime.getLocale()
fromMoment = CUI.DateTimeRangeGrammar.getMoment(from)
toMoment = CUI.DateTimeRangeGrammar.getMoment(to)
if not fromMoment?.isValid() or not toMoment?.isValid()
return CUI.DateTimeFormats[locale].formats[0].invalid
if CUI.DateTimeRangeGrammar.REGEXP_YEAR.test(from)
fromIsYear = true
fromYear = parseInt(from)
else if fromMoment.isValid() and fromMoment.date() == 1 and fromMoment.month() == 0 # First day of year.
fromMoment.add(1, "day") # This is a workaround to avoid having the wrong year after parsing the timezone.
fromMoment.parseZone()
fromYear = fromMoment.year()
if from == to
return CUI.DateTime.format(from, "display_short")
if CUI.DateTimeRangeGrammar.REGEXP_YEAR.test(to)
toIsYear = true
toYear = parseInt(to)
else if toMoment.isValid() and toMoment.date() == 31 and toMoment.month() == 11 # Last day of year
toMoment.add(1, "day")
toMoment.parseZone()
toYear = toMoment.year()
grammars = CUI.DateTimeRangeGrammar.PARSE_GRAMMARS[locale]
if not grammars
return
getPossibleString = (key, parameters) ->
for _grammar in grammars
if _grammar[4] == key
grammar = _grammar
break
if not grammar
return
possibleStringArray = grammar[0].split(CUI.DateTimeRangeGrammar.REGEXP_SPACE)
tokenPositions = grammar[2]
for value, index in tokenPositions
if parameters[index]
if possibleStringArray[value] == "YEAR_DOT"
parameters[index] += "."
else if possibleStringArray[value] == "CENTURY"
parameters[index] += "th"
else if CUI.util.isString(parameters[index])
parameters[index] = CUI.DateTime.format(parameters[index], "display_short")
possibleStringArray[value] = parameters[index]
possibleString = possibleStringArray.join(" ")
output = CUI.DateTimeRangeGrammar.stringToDateRange(possibleString)
if not output or output.to != to or output.from != from
return
return possibleString.replace(" #{DateTimeRangeGrammar.DASH} ", " #{DateTimeRangeGrammar.EN_DASH} ")
if not CUI.util.isUndef(fromYear) and not CUI.util.isUndef(toYear)
if fromYear == toYear
return "#{fromYear}"
isBC = fromYear < 0
if isBC
possibleString = getPossibleString("AFTER_BC", [Math.abs(fromYear)])
else
possibleString = getPossibleString("AFTER", [Math.abs(fromYear)])
if possibleString
return possibleString
isBC = toYear < 0
if isBC
possibleString = getPossibleString("BEFORE_BC", [Math.abs(toYear)])
else
possibleString = getPossibleString("BEFORE", [Math.abs(toYear)])
if possibleString
return possibleString
centerYear = (toYear + fromYear) / 2
isBC = centerYear <= 0
if isBC
possibleString = getPossibleString("AROUND_BC", [Math.abs(centerYear)])
else
possibleString = getPossibleString("AROUND", [Math.abs(centerYear)])
if possibleString
return possibleString
yearsDifference = toYear - fromYear
if yearsDifference == 999 # Millennium
isBC = toYear <= 0
if isBC
millennium = (-from + 1) / 1000
possibleString = getPossibleString("MILLENNIUM_BC", [millennium])
else
millennium = to / 1000
possibleString = getPossibleString("MILLENNIUM", [millennium])
if possibleString
return possibleString
else if yearsDifference == 99 # Century
isBC = toYear <= 0
if isBC
century = -(fromYear - 1) / 100
possibleString = getPossibleString("CENTURY_BC", [century])
else
century = toYear / 100
possibleString = getPossibleString("CENTURY", [century])
if possibleString
return possibleString
else if yearsDifference == 15 # Early/Late
isBC = fromYear <= 0
century = Math.ceil(Math.abs(fromYear) / 100)
if isBC
for key in ["EARLY_CENTURY_BC", "LATE_CENTURY_BC"]
possibleString = getPossibleString(key, [century])
if possibleString
return possibleString
else
for key in ["EARLY_CENTURY", "LATE_CENTURY"]
possibleString = getPossibleString(key, [century])
if possibleString
return possibleString
else if (yearsDifference + 1) % 100 == 0 and (fromYear - 1) % 100 == 0 and toYear % 100 == 0
toCentury = (toYear / 100)
if fromYear < 0
fromCentury = -(fromYear - 1) / 100
if toYear <= 0
toCentury += 1
grammarKey = "<KEY>_RANGE_<KEY>"
else
grammarKey = "<KEY>_RANGE_FROM_BC"
else
grammarKey = "<KEY>"
fromCentury = (fromYear + 99) / 100
toCentury = toYear / 100
possibleString = getPossibleString(grammarKey, [fromCentury, toCentury])
if possibleString
return possibleString
# Month range XXXX-XX-01 - XXXX-XX-31
if fromMoment.year() == toMoment.year() and
fromMoment.month() == toMoment.month() and
fromMoment.date() == 1 and toMoment.date() == toMoment.endOf("month").date()
for format in CUI.DateTimeFormats[locale].formats
if format.display_attribute == CUI.DateTimeRangeGrammar.DISPLAY_ATTRIBUTE_YEAR_MONTH
month = CUI.DateTimeRangeGrammar.MONTHS[locale][toMoment.month()]
return "#{month} #{toMoment.year()}"
if fromIsYear and toIsYear
possibleString = getPossibleString("RANGE_YEAR", [from, to])
if possibleString
return possibleString
if fromIsYear or toIsYear
if fromIsYear
from = CUI.DateTime.format(from, "display_short")
if toIsYear
to = CUI.DateTime.format(to, "display_short")
# Removes the 'BC' / v. Chr. from 'from' to only show it in the end. For example: 15 - 10 v. Chr.
fromSplit = from.split(CUI.DateTimeRangeGrammar.REGEXP_SPACE)
toSplit = to.split(CUI.DateTimeRangeGrammar.REGEXP_SPACE)
if fromSplit[1] == toSplit[1]
from = fromSplit[0]
return "#{from} - #{to}"
possibleString = getPossibleString("RANGE", [from, to])
if possibleString
return possibleString
return "#{from} #{DateTimeRangeGrammar.EN_DASH} #{to}"
# Main method to check against every grammar.
@stringToDateRange: (input) ->
if CUI.util.isEmpty(input) or not CUI.util.isString(input)
return error: "Input needs to be a non empty string: #{input}"
locale = CUI.DateTime.getLocale()
input = input.trim()
input = input.replace(DateTimeRangeGrammar.REGEXP_DASH, DateTimeRangeGrammar.DASH)
tokens = []
for s in input.split(CUI.DateTimeRangeGrammar.REGEXP_SPACE)
value = s
if CUI.DateTimeRangeGrammar.REGEXP_DATE.test(s) or CUI.DateTimeRangeGrammar.REGEXP_MONTH.test(s)
type = CUI.DateTimeRangeGrammar.TYPE_DATE
else if CUI.DateTimeRangeGrammar.REGEXP_YEAR.test(s)
type = CUI.DateTimeRangeGrammar.TYPE_YEAR
else if CUI.DateTimeRangeGrammar.REGEXP_YEAR_DOT.test(s)
type = CUI.DateTimeRangeGrammar.TYPE_YEAR_DOT
value = s.split(".")[0]
else if CUI.DateTimeRangeGrammar.REGEXP_CENTURY.test(s)
type = CUI.DateTimeRangeGrammar.TYPE_CENTURY
value = s.split("th")[0]
else if value in CUI.DateTimeRangeGrammar.MONTHS[locale]
type = CUI.DateTimeRangeGrammar.TYPE_MONTH
value = CUI.DateTimeRangeGrammar.MONTHS[locale].indexOf(value)
else
type = s # The type for everything else is the value.
tokens.push
type: type
value: value
stringToParse = tokens.map((token) -> token.type).join(" ").toUpperCase()
# Check if there is a grammar that applies to the input.
for _, grammars of CUI.DateTimeRangeGrammar.PARSE_GRAMMARS
for grammar in grammars
if grammar[0].toUpperCase() == stringToParse
method = CUI.DateTimeRangeGrammar[grammar[1]]
if not CUI.util.isFunction(method) or not grammar[2]
continue
tokenPositions = grammar[2]
if CUI.util.isArray(tokenPositions)
if tokenPositions.length == 0
continue
methodArguments = tokenPositions.map((index) -> tokens[index].value)
else
methodArguments = [tokenPositions]
if extraArguments = grammar[3]
if CUI.util.isArray(extraArguments)
methodArguments = methodArguments.concat(extraArguments)
else
methodArguments.push(extraArguments)
value = method.apply(@, methodArguments)
if value
return value
# If there is no grammar available, we try to parse the date.
[from, to] = input.split(/\s+\-\s+/)
if from and to
output = CUI.DateTimeRangeGrammar.range(from, to)
if output
return output
output = CUI.DateTimeRangeGrammar.getFromTo(from)
if output
return output
return error: "NoDateRangeFound #{input}"
@millennium: (millennium, isBC) ->
if isBC
from = -(millennium * 1000 - 1)
to = -((millennium - 1) * 1000)
else
to = millennium * 1000
from = to - 999
return CUI.DateTimeRangeGrammar.getFromToWithRange("#{from}", "#{to}")
@century: (century, isBC) ->
century = century * 100
if isBC
to = -(century - 100)
from = -century + 1
else
to = century
from = century - 99
return CUI.DateTimeRangeGrammar.getFromToWithRange("#{from}", "#{to}")
@centuryRange: (centuryFrom, centuryTo, fromIsBC, toIsBC) ->
from = @century(centuryFrom, fromIsBC)
to = @century(centuryTo, toIsBC)
return from: from?.from, to: to?.to
# 15 -> 1401 - 1416
# 15 -> 1499 1484
@earlyCentury: (century, isBC) ->
century = century * 100
if isBC
from = -century + 1
to = from + 15
else
from = century - 99
to = from + 15
return CUI.DateTimeRangeGrammar.getFromToWithRange("#{from}", "#{to}")
# 15 - -1416 -1401
# 15 - 1484 - 1499
@lateCentury: (century, isBC) ->
century = century * 100
if isBC
to = -(century - 101)
from = to - 15
else
to = century
from = to - 15
return CUI.DateTimeRangeGrammar.getFromToWithRange("#{from}", "#{to}")
@range: (from, to, fromBC = false, toBC = false) ->
if toBC and not to.startsWith(CUI.DateTimeRangeGrammar.DASH)
to = @__toBC(to)
if (fromBC or toBC) and not from.startsWith(CUI.DateTimeRangeGrammar.DASH)
from = @__toBC(from)
return CUI.DateTimeRangeGrammar.getFromToWithRange(from, to)
@monthRange: (month, year) ->
momentDate = CUI.DateTimeRangeGrammar.getMoment(year)
momentDate.month(month)
momentDate.startOf("month")
from = CUI.DateTimeRangeGrammar.format(momentDate, false)
momentDate.endOf("month")
to= CUI.DateTimeRangeGrammar.format(momentDate, false)
return from: from, to: to
@yearRange: (year, isBC = false, fromAddYears = false, toAddYears = false) ->
if isBC and not year.startsWith(CUI.DateTimeRangeGrammar.DASH)
year = "-#{year}"
momentInputFrom = CUI.DateTimeRangeGrammar.getMoment(year)
if not momentInputFrom?.isValid()
return
if not year.startsWith(CUI.DateTimeRangeGrammar.DASH)
momentInputFrom.add(1, "day") # This is a workaround to avoid having the wrong year after parsing the timezone.
momentInputFrom.parseZone()
if fromAddYears or toAddYears
_year = momentInputFrom.year()
if _year % 1000 == 0
yearsToAdd = 500
else if _year % 100 == 0
yearsToAdd = 50
else if _year % 50 == 0
yearsToAdd = 15
else if _year % 10 == 0
yearsToAdd = 5
else
yearsToAdd = 2
momentInputTo = momentInputFrom.clone()
if fromAddYears
momentInputFrom.add(-yearsToAdd, "year")
if toAddYears
momentInputTo.add(yearsToAdd, "year")
if not year.startsWith(CUI.DateTimeRangeGrammar.DASH)
momentInputTo.add(1, "day")
momentInputTo.parseZone()
momentInputFrom.startOf("year")
momentInputTo.endOf("year")
from = CUI.DateTimeRangeGrammar.format(momentInputFrom)
to = CUI.DateTimeRangeGrammar.format(momentInputTo)
return from: from, to: to
@getFromTo: (inputString, isBC = false) ->
if isBC and not inputString.startsWith(CUI.DateTimeRangeGrammar.DASH)
inputString = @__toBC(inputString)
momentInput = CUI.DateTimeRangeGrammar.getMoment(inputString)
if not momentInput?.isValid()
return
if inputString.match(CUI.DateTimeRangeGrammar.REGEXP_YEAR)
if not inputString.startsWith(CUI.DateTimeRangeGrammar.DASH)
momentInput.add(1, "day")
momentInput.parseZone()
from = to = CUI.DateTimeRangeGrammar.format(momentInput)
else if inputString.match(CUI.DateTimeRangeGrammar.REGEXP_MONTH)
from = CUI.DateTimeRangeGrammar.format(momentInput, false)
momentInput.endOf('month');
to = CUI.DateTimeRangeGrammar.format(momentInput, false)
else
from = to = CUI.DateTimeRangeGrammar.format(momentInput, false)
return from: from, to: to
@getFromToWithRange: (fromDate, toDate) ->
from = CUI.DateTimeRangeGrammar.getFromTo(fromDate)
to = CUI.DateTimeRangeGrammar.getFromTo(toDate)
if not from or not to
return
return from: from.from, to: to.to
@format: (dateMoment, yearFormat = true) ->
if yearFormat
outputType = CUI.DateTimeRangeGrammar.OUTPUT_YEAR
else
outputType = CUI.DateTimeRangeGrammar.OUTPUT_DATE
return CUI.DateTime.format(dateMoment, CUI.DateTimeRangeGrammar.STORE_FORMAT, outputType)
@getMoment: (inputString) ->
if not CUI.util.isString(inputString)
return
dateTime = new CUI.DateTime()
momentInput = dateTime.parseValue(inputString);
if !momentInput.isValid() and inputString.startsWith(DateTimeRangeGrammar.DASH)
# This is a workaround for moment.js when strings are like: "-2020-11-05T10:00:00+00:00" or "-0100-01-01"
# Moment js does not support negative full dates, therefore we create a moment without the negative character
# and then we make the year negative.
inputString = inputString.substring(1)
momentInput = dateTime.parseValue(inputString);
momentInput.year(-momentInput.year())
dateTime.destroy()
return momentInput
@__toBC: (inputString) ->
if inputString.match(CUI.DateTimeRangeGrammar.REGEXP_YEAR)
inputString = parseInt(inputString) - 1
return "-#{inputString}" | true | class CUI.DateTimeRangeGrammar
@REGEXP_DATE = /^[0-9]+[-/.][0-9]+[-/.][0-9]+$/ # Exact date
@REGEXP_MONTH = /^[0-9]+[-/.][0-9]+$/ # Matches if the date has Year and month (no day)
@REGEXP_YEAR = /^\-?[0-9]+$/ # Matches if the date has Year. (no day, no month)
@REGEXP_YEAR_DOT = /^[0-9]+.$/ # Matches Year ending with dot.
@REGEXP_CENTURY = /^[0-9]+th$/ # Matches Year ending with th.
@REGEXP_SPACE = /\s+/
@REGEXP_DASH = /[\–\—]/g # Matches 'EN' and 'EM' dashes.
@TYPE_DATE = "DATE"
@TYPE_YEAR = "YEAR"
@TYPE_YEAR_DOT = "YEAR_DOT"
@TYPE_CENTURY = "CENTURY"
@TYPE_CENTURY_RANGE = "CENTURY_RANGE"
@TYPE_MONTH = "MONTH"
@DASH = "-"
@STORE_FORMAT = "store"
@OUTPUT_YEAR = "year"
@OUTPUT_DATE = "date"
@DISPLAY_ATTRIBUTE_YEAR_MONTH = "year-month"
@EN_DASH = "–"
@MONTHS = {}
@MONTHS["de-DE"] = [
"Januar"
"Februar"
"März"
"April"
"Mai"
"Juni"
"Juli"
"August"
"September"
"Oktober"
"November"
"Dezember"
]
@MONTHS["en-US"] = [
"January"
"February"
"March"
"April"
"May"
"June"
"July"
"August"
"September"
"October"
"November"
"December"
]
### How to add new grammars:
# [<GRAMMAR>, <FUNCTION>, <ARRAY_TOKEN_POSITION>, <ARRAY_FUNCTION_ARGUMENTS>, <KEY>]
#
# GRAMMAR: Plain text with tokens to identify dates.
# - Tokens available: DATE (full date), YEAR (only year), YEAR_DOT (year with dot), CENTURY (year with th)
#
# FUNCTION: Function which is going to be used to parse, in string.
# - Functions available: millennium, century, earlyCentury, lateCentury, range, yearRange, getFromTo
#
# ARRAY_TOKEN_POSITION: Array of integers with the position of the date tokens.
# ARRAY_FUNCTION_ARGUMENTS: (optional) Array with arguments that will be given to the function.
# - Dates are given as arguments automatically.
#
# KEY: (optional) Identifier that is used in the format method.
###
@PARSE_GRAMMARS = {} # TODO: Add ES & IT.
@PARSE_GRAMMARS["de-DE"] = [
["DATE bis DATE", "range", [0, 2], null, "RANGE"]
["YEAR bis YEAR", "range", [0, 2], null, "RANGE_YEAR"]
["YEAR - YEAR n. Chr.", "range", [0, 2]]
["YEAR bis YEAR n. Chr.", "range", [0, 2]]
["zwischen YEAR bis YEAR", "range", [1, 3]]
["zwischen YEAR und YEAR", "range", [1, 3]]
["zwischen DATE bis DATE", "range", [1, 3]]
["zwischen DATE und DATE", "range", [1, 3]]
["von YEAR bis YEAR", "range", [1, 3]]
["YEAR v. Chr. - YEAR n. Chr.", "range", [0, 4], [true]]
["YEAR - YEAR v. Chr.", "range", [0, 2], [true, true]]
["YEAR BC - YEAR n. Chr.", "range", [0, 3], [true]]
["YEAR BC - YEAR nach Chr.", "range", [0, 3], [true]]
["YEAR B.C. - YEAR n. Chr.", "range", [0, 3], [true]]
["YEAR B.C. - YEAR nach Chr.", "range", [0, 3], [true]]
["YEAR bc - YEAR n. Chr.", "range", [0, 3], [true]]
["YEAR bc - YEAR nach Chr.", "range", [0, 3], [true]]
["YEAR ac - YEAR n. Chr.", "range", [0, 3], [true]]
["YEAR ac - YEAR nach Chr.", "range", [0, 3], [true]]
["bis YEAR", "yearRange", [1], [false, true]]
["um YEAR", "yearRange", [1], [false, true, true], "AROUND"]
["ca. YEAR", "yearRange", [1], [false, true, true]]
["um YEAR bc", "yearRange", [1], [true, true, true]]
["um YEAR v. Chr.", "yearRange", [1], [true, true, true], "AROUND_BC"]
["ca. YEAR bc", "yearRange", [1], [true, true, true]]
["ca. YEAR v. Chr.", "yearRange", [1], [true, true, true]]
["vor YEAR", "yearRange", [1], [false, true], "BEFORE"]
["vor YEAR bc", "yearRange", [1], [true, true]]
["vor YEAR v. Chr.", "yearRange", [1], [true, true], "BEFORE_BC"]
["nach YEAR", "yearRange", [1], [false, false, true], "AFTER"]
["nach YEAR ad", "yearRange", [1], [false, false, true]]
["nach YEAR A.D.", "yearRange", [1], [false, false, true]]
["ab YEAR", "yearRange", [1], [false, false, true]]
["ab YEAR ad", "yearRange", [1], [false, false, true]]
["ab YEAR A.D.", "yearRange", [1], [false, false, true]]
["nach YEAR bc", "yearRange", [1], [true, false, true]]
["nach YEAR v. Chr.", "yearRange", [1], [true, false, true], "AFTER_BC"]
["YEAR v. Chr.", "getFromTo", [0], [true]]
["YEAR n. Chr.", "getFromTo", [0]]
["YEAR_DOT Jhd. vor Chr", "century", [0], [true]]
["YEAR_DOT Jhd. vor Chr.", "century", [0], [true]]
["YEAR_DOT Jhd. v. Chr", "century", [0], [true]]
["YEAR_DOT Jhd. v. Chr.", "century", [0], [true], "CENTURY_BC"]
["YEAR_DOT Jhd vor Chr", "century", [0], [true]]
["YEAR_DOT Jhd vor Chr.", "century", [0], [true]]
["YEAR_DOT Jhd v. Chr", "century", [0], [true]]
["YEAR_DOT Jhd v. Chr.", "century", [0], [true]]
["YEAR_DOT Jh vor Chr", "century", [0], [true]]
["YEAR_DOT Jh vor Chr.", "century", [0], [true]]
["YEAR_DOT Jh v. Chr", "century", [0], [true]]
["YEAR_DOT Jh v. Chr.", "century", [0], [true]]
["YEAR_DOT Jh. vor Chr", "century", [0], [true]]
["YEAR_DOT Jh. vor Chr.", "century", [0], [true]]
["YEAR_DOT Jh. v. Chr", "century", [0], [true]]
["YEAR_DOT Jh. v. Chr.", "century", [0], [true]]
["YEAR Jhd. vor Chr", "century", [0], [true]]
["YEAR Jhd. vor Chr.", "century", [0], [true]]
["YEAR Jhd. v. Chr", "century", [0], [true]]
["YEAR Jhd. v. Chr.", "century", [0], [true]]
["YEAR Jhd vor Chr", "century", [0], [true]]
["YEAR Jhd vor Chr.", "century", [0], [true]]
["YEAR Jhd v. Chr", "century", [0], [true]]
["YEAR Jhd v. Chr.", "century", [0], [true]]
["YEAR Jhd ac", "century", [0], [true]]
["YEAR Jh ac", "century", [0], [true]]
["YEAR Jh. ac", "century", [0], [true]]
["YEAR Jhd.", "century", [0]]
["YEAR Jhd", "century", [0]]
["YEAR Jh", "century", [0]]
["YEAR Jh.", "century", [0]]
["YEAR_DOT Jhd.", "century", [0], null, "CENTURY"]
["YEAR_DOT Jhd", "century", [0]]
["YEAR_DOT Jhd nach Chr.", "century", [0]]
["YEAR_DOT Jhd. nach Chr.", "century", [0]]
["YEAR_DOT Jhd. nach Chr", "century", [0]]
["YEAR_DOT Jhd nach Chr", "century", [0]]
["YEAR_DOT Jhd. n. Chr.", "century", [0]]
["YEAR_DOT Jhd. n. Chr", "century", [0]]
["YEAR_DOT Jhd n. Chr.", "century", [0]]
["YEAR_DOT Jhd n. Chr", "century", [0]]
["YEAR_DOT Jt. v. Chr.", "millennium", [0], [true], "MILLENNIUM_BC"]
["YEAR_DOT Jt v. Chr.", "millennium", [0], [true]]
["YEAR_DOT Jt bc", "millennium", [0], [true]]
["YEAR_DOT Jt. bc", "millennium", [0], [true]]
["YEAR_DOT Jt BC", "millennium", [0], [true]]
["YEAR_DOT Jt. BC", "millennium", [0], [true]]
["YEAR_DOT Jt.", "millennium", [0], null, "MILLENNIUM"]
["YEAR_DOT Jt.", "millennium", [0]]
["YEAR_DOT Jt", "millennium", [0]]
["YEAR Jt. v. Chr.", "millennium", [0], [true]]
["YEAR Jt v. Chr.", "millennium", [0], [true]]
["YEAR Jt bc", "millennium", [0], [true]]
["YEAR Jt. bc", "millennium", [0], [true]]
["YEAR Jt BC", "millennium", [0], [true]]
["YEAR Jt. BC", "millennium", [0], [true]]
["YEAR Jt.", "millennium", [0]]
["YEAR Jt.", "millennium", [0]]
["YEAR Jt", "millennium", [0]]
["Anfang YEAR_DOT Jhd", "earlyCentury", [1]]
["Anfang YEAR_DOT Jh", "earlyCentury", [1]]
["Anfang YEAR_DOT Jh.", "earlyCentury", [1], null, "EARLY_CENTURY"]
["Anfang YEAR_DOT Jhd v. Chr.", "earlyCentury", [1], [true]]
["Anfang YEAR_DOT Jh v. Chr.", "earlyCentury", [1], [true]]
["Anfang YEAR_DOT Jh. v. Chr.", "earlyCentury", [1], [true], "EARLY_CENTURY_BC"]
["Ende YEAR_DOT Jhd", "lateCentury", [1]]
["Ende YEAR_DOT Jh", "lateCentury", [1]]
["Ende YEAR_DOT Jh.", "lateCentury", [1], null, "LATE_CENTURY"]
["Ende YEAR_DOT Jhd v. Chr.", "lateCentury", [1], [true]]
["Ende YEAR_DOT Jh v. Chr.", "lateCentury", [1], [true]]
["Ende YEAR_DOT Jh. v. Chr.", "lateCentury", [1], [true], "LATE_CENTURY_BC"]
["YEAR_DOT Jhd. - YEAR_DOT Jhd.", "centuryRange", [0, 3], null, "CENTURY_RANGE"]
["YEAR_DOT Jhd - YEAR_DOT Jhd", "centuryRange", [0, 3]]
["YEAR Jhd. - YEAR Jhd.", "centuryRange", [0, 3]]
["YEAR Jhd - YEAR Jhd", "centuryRange", [0, 3]]
["YEAR Jh. - YEAR Jh.", "centuryRange", [0, 3]]
["YEAR Jh - YEAR Jh", "centuryRange", [0, 3]]
["YEAR_DOT Jh. - YEAR_DOT Jh.", "centuryRange", [0, 3]]
["YEAR_DOT Jh - YEAR_DOT Jh", "centuryRange", [0, 3]]
["YEAR_DOT Jhd. v. Chr. - YEAR_DOT Jhd.", "centuryRange", [0, 5], [true], "CENTURY_RANGE_FROM_BC"]
["YEAR_DOT Jhd v. Chr. - YEAR_DOT Jhd", "centuryRange", [0, 5], [true]]
["YEAR Jhd. v. Chr. - YEAR Jhd.", "centuryRange", [0, 5], [true]]
["YEAR Jhd v. Chr. - YEAR Jhd", "centuryRange", [0, 5], [true]]
["YEAR Jh. v. Chr. - YEAR Jh.", "centuryRange", [0, 5], [true]]
["YEAR Jh v. Chr. - YEAR Jh", "centuryRange", [0, 5], [true]]
["YEAR_DOT Jh. v. Chr. - YEAR_DOT Jh.", "centuryRange", [0, 5], [true]]
["YEAR_DOT Jh v. Chr. - YEAR_DOT Jh", "centuryRange", [0, 5], [true]]
["YEAR_DOT Jhd. v. Chr. - YEAR_DOT Jhd. v. Chr.", "centuryRange", [0, 5], [true, true], "CENTURY_RANGE_BC"]
["YEAR_DOT Jhd v. Chr. - YEAR_DOT Jhd v. Chr.", "centuryRange", [0, 5], [true, true]]
["YEAR Jhd. v. Chr. - YEAR Jhd. v. Chr.", "centuryRange", [0, 5], [true, true]]
["YEAR Jhd v. Chr. - YEAR Jhd v. Chr.", "centuryRange", [0, 5], [true, true]]
["YEAR Jh. v. Chr. - YEAR Jh. v. Chr.", "centuryRange", [0, 5], [true, true]]
["YEAR Jh v. Chr. - YEAR Jh v. Chr.", "centuryRange", [0, 5], [true, true]]
["YEAR_DOT Jh. v. Chr. - YEAR_DOT Jh. v. Chr.", "centuryRange", [0, 5], [true, true]]
["YEAR_DOT Jh v. Chr. - YEAR_DOT Jh v. Chr.", "centuryRange", [0, 5], [true, true]]
]
@PARSE_GRAMMARS["en-US"] = [
["DATE to DATE", "range", [0, 2], null, "RANGE"]
["YEAR to YEAR", "range", [0, 2], null, "RANGE_YEAR"]
["YEAR - YEAR A.D.", "range", [0, 2]]
["YEAR - YEAR AD", "range", [0, 2]]
["YEAR to YEAR A.D.", "range", [0, 2]]
["YEAR to YEAR AD", "range", [0, 2]]
["from YEAR to YEAR", "range", [1, 3]]
["YEAR BC - YEAR A.D.", "range", [0, 3], [true]]
["YEAR BC - YEAR AD", "range", [0, 3], [true]]
["YEAR BC - YEAR CE", "range", [0, 3], [true]]
["YEAR BC - YEAR ad", "range", [0, 3], [true]]
["YEAR B.C. - YEAR A.D.", "range", [0, 3], [true]]
["YEAR B.C. - YEAR AD", "range", [0, 3], [true]]
["YEAR B.C. - YEAR CE", "range", [0, 3], [true]]
["YEAR B.C. - YEAR ad", "range", [0, 3], [true]]
["YEAR B.C. to YEAR", "range", [0, 3], [true]]
["YEAR bc - YEAR A.D.", "range", [0, 3], [true]]
["YEAR bc - YEAR AD", "range", [0, 3], [true]]
["YEAR bc - YEAR CE", "range", [0, 3], [true]]
["YEAR bc - YEAR ad", "range", [0, 3], [true]]
["YEAR ac - YEAR A.D.", "range", [0, 3], [true]]
["YEAR ac - YEAR AD", "range", [0, 3], [true]]
["YEAR ac - YEAR CE", "range", [0, 3], [true]]
["YEAR ac - YEAR ad", "range", [0, 3], [true]]
["YEAR - YEAR BC", "range", [0, 2], [true, true]]
["YEAR - YEAR B.C.", "range", [0, 2], [true, true]]
["MONTH YEAR", "monthRange", [0, 1]]
["after YEAR", "yearRange", [1], [false, false, true], "AFTER"]
["after YEAR BC", "yearRange", [1], [true, false, true], "AFTER_BC"]
["before YEAR", "yearRange", [1], [false, true], "BEFORE"]
["before YEAR BC", "yearRange", [1], [true, true], "BEFORE_BC"]
["around YEAR", "yearRange", [1], [false, true, true], "AROUND"]
["around YEAR BC", "yearRange", [1], [true, true, true], "AROUND_BC"]
["YEAR_DOT millennium", "millennium", [0], null, "MILLENNIUM"]
["YEAR_DOT millennium BC", "millennium", [0], [true], "MILLENNIUM_BC"]
["YEAR millennium", "millennium", [0]]
["YEAR millennium BC", "millennium", [0], [true]]
["YEAR BCE", "getFromTo", [0], [true]]
["YEAR bc", "getFromTo", [0], [true]]
["YEAR BC", "getFromTo", [0], [true]]
["YEAR B.C.", "getFromTo", [0], [true]]
["YEAR AD", "getFromTo", [0]]
["YEAR A.D.", "getFromTo", [0]]
["CENTURY century", "century", [0], null, "CENTURY"]
["CENTURY century BC", "century", [0], [true], "CENTURY_BC"]
["Early CENTURY century", "earlyCentury", [1], null, "EARLY_CENTURY"]
["Early CENTURY century BC", "earlyCentury", [1], [true], "EARLY_CENTURY_BC"]
["Late CENTURY century", "lateCentury", [1], null, "LATE_CENTURY"]
["Late CENTURY century BC", "lateCentury", [1], [true], "LATE_CENTURY_BC"]
["CENTURY century - CENTURY century", "centuryRange", [0, 3], null, "CENTURY_RANGE"]
["CENTURY century BC - CENTURY century", "centuryRange", [0, 4], [true], "CENTURY_RANGE_FROM_BC"]
["CENTURY century B.C. - CENTURY century", "centuryRange", [0, 4], [true]]
["CENTURY century BC - CENTURY century BC", "centuryRange", [0, 4], [true, true], "CENTURY_RANGE_BC"]
["CENTURY century B.C. - CENTURY century B.C.", "centuryRange", [0, 4], [true, true]]
]
@dateRangeToString: (from, to) ->
if not CUI.util.isString(from) or not CUI.util.isString(to)
return
locale = CUI.DateTime.getLocale()
fromMoment = CUI.DateTimeRangeGrammar.getMoment(from)
toMoment = CUI.DateTimeRangeGrammar.getMoment(to)
if not fromMoment?.isValid() or not toMoment?.isValid()
return CUI.DateTimeFormats[locale].formats[0].invalid
if CUI.DateTimeRangeGrammar.REGEXP_YEAR.test(from)
fromIsYear = true
fromYear = parseInt(from)
else if fromMoment.isValid() and fromMoment.date() == 1 and fromMoment.month() == 0 # First day of year.
fromMoment.add(1, "day") # This is a workaround to avoid having the wrong year after parsing the timezone.
fromMoment.parseZone()
fromYear = fromMoment.year()
if from == to
return CUI.DateTime.format(from, "display_short")
if CUI.DateTimeRangeGrammar.REGEXP_YEAR.test(to)
toIsYear = true
toYear = parseInt(to)
else if toMoment.isValid() and toMoment.date() == 31 and toMoment.month() == 11 # Last day of year
toMoment.add(1, "day")
toMoment.parseZone()
toYear = toMoment.year()
grammars = CUI.DateTimeRangeGrammar.PARSE_GRAMMARS[locale]
if not grammars
return
getPossibleString = (key, parameters) ->
for _grammar in grammars
if _grammar[4] == key
grammar = _grammar
break
if not grammar
return
possibleStringArray = grammar[0].split(CUI.DateTimeRangeGrammar.REGEXP_SPACE)
tokenPositions = grammar[2]
for value, index in tokenPositions
if parameters[index]
if possibleStringArray[value] == "YEAR_DOT"
parameters[index] += "."
else if possibleStringArray[value] == "CENTURY"
parameters[index] += "th"
else if CUI.util.isString(parameters[index])
parameters[index] = CUI.DateTime.format(parameters[index], "display_short")
possibleStringArray[value] = parameters[index]
possibleString = possibleStringArray.join(" ")
output = CUI.DateTimeRangeGrammar.stringToDateRange(possibleString)
if not output or output.to != to or output.from != from
return
return possibleString.replace(" #{DateTimeRangeGrammar.DASH} ", " #{DateTimeRangeGrammar.EN_DASH} ")
if not CUI.util.isUndef(fromYear) and not CUI.util.isUndef(toYear)
if fromYear == toYear
return "#{fromYear}"
isBC = fromYear < 0
if isBC
possibleString = getPossibleString("AFTER_BC", [Math.abs(fromYear)])
else
possibleString = getPossibleString("AFTER", [Math.abs(fromYear)])
if possibleString
return possibleString
isBC = toYear < 0
if isBC
possibleString = getPossibleString("BEFORE_BC", [Math.abs(toYear)])
else
possibleString = getPossibleString("BEFORE", [Math.abs(toYear)])
if possibleString
return possibleString
centerYear = (toYear + fromYear) / 2
isBC = centerYear <= 0
if isBC
possibleString = getPossibleString("AROUND_BC", [Math.abs(centerYear)])
else
possibleString = getPossibleString("AROUND", [Math.abs(centerYear)])
if possibleString
return possibleString
yearsDifference = toYear - fromYear
if yearsDifference == 999 # Millennium
isBC = toYear <= 0
if isBC
millennium = (-from + 1) / 1000
possibleString = getPossibleString("MILLENNIUM_BC", [millennium])
else
millennium = to / 1000
possibleString = getPossibleString("MILLENNIUM", [millennium])
if possibleString
return possibleString
else if yearsDifference == 99 # Century
isBC = toYear <= 0
if isBC
century = -(fromYear - 1) / 100
possibleString = getPossibleString("CENTURY_BC", [century])
else
century = toYear / 100
possibleString = getPossibleString("CENTURY", [century])
if possibleString
return possibleString
else if yearsDifference == 15 # Early/Late
isBC = fromYear <= 0
century = Math.ceil(Math.abs(fromYear) / 100)
if isBC
for key in ["EARLY_CENTURY_BC", "LATE_CENTURY_BC"]
possibleString = getPossibleString(key, [century])
if possibleString
return possibleString
else
for key in ["EARLY_CENTURY", "LATE_CENTURY"]
possibleString = getPossibleString(key, [century])
if possibleString
return possibleString
else if (yearsDifference + 1) % 100 == 0 and (fromYear - 1) % 100 == 0 and toYear % 100 == 0
toCentury = (toYear / 100)
if fromYear < 0
fromCentury = -(fromYear - 1) / 100
if toYear <= 0
toCentury += 1
grammarKey = "PI:KEY:<KEY>END_PI_RANGE_PI:KEY:<KEY>END_PI"
else
grammarKey = "PI:KEY:<KEY>END_PI_RANGE_FROM_BC"
else
grammarKey = "PI:KEY:<KEY>END_PI"
fromCentury = (fromYear + 99) / 100
toCentury = toYear / 100
possibleString = getPossibleString(grammarKey, [fromCentury, toCentury])
if possibleString
return possibleString
# Month range XXXX-XX-01 - XXXX-XX-31
if fromMoment.year() == toMoment.year() and
fromMoment.month() == toMoment.month() and
fromMoment.date() == 1 and toMoment.date() == toMoment.endOf("month").date()
for format in CUI.DateTimeFormats[locale].formats
if format.display_attribute == CUI.DateTimeRangeGrammar.DISPLAY_ATTRIBUTE_YEAR_MONTH
month = CUI.DateTimeRangeGrammar.MONTHS[locale][toMoment.month()]
return "#{month} #{toMoment.year()}"
if fromIsYear and toIsYear
possibleString = getPossibleString("RANGE_YEAR", [from, to])
if possibleString
return possibleString
if fromIsYear or toIsYear
if fromIsYear
from = CUI.DateTime.format(from, "display_short")
if toIsYear
to = CUI.DateTime.format(to, "display_short")
# Removes the 'BC' / v. Chr. from 'from' to only show it in the end. For example: 15 - 10 v. Chr.
fromSplit = from.split(CUI.DateTimeRangeGrammar.REGEXP_SPACE)
toSplit = to.split(CUI.DateTimeRangeGrammar.REGEXP_SPACE)
if fromSplit[1] == toSplit[1]
from = fromSplit[0]
return "#{from} - #{to}"
possibleString = getPossibleString("RANGE", [from, to])
if possibleString
return possibleString
return "#{from} #{DateTimeRangeGrammar.EN_DASH} #{to}"
# Main method to check against every grammar.
@stringToDateRange: (input) ->
if CUI.util.isEmpty(input) or not CUI.util.isString(input)
return error: "Input needs to be a non empty string: #{input}"
locale = CUI.DateTime.getLocale()
input = input.trim()
input = input.replace(DateTimeRangeGrammar.REGEXP_DASH, DateTimeRangeGrammar.DASH)
tokens = []
for s in input.split(CUI.DateTimeRangeGrammar.REGEXP_SPACE)
value = s
if CUI.DateTimeRangeGrammar.REGEXP_DATE.test(s) or CUI.DateTimeRangeGrammar.REGEXP_MONTH.test(s)
type = CUI.DateTimeRangeGrammar.TYPE_DATE
else if CUI.DateTimeRangeGrammar.REGEXP_YEAR.test(s)
type = CUI.DateTimeRangeGrammar.TYPE_YEAR
else if CUI.DateTimeRangeGrammar.REGEXP_YEAR_DOT.test(s)
type = CUI.DateTimeRangeGrammar.TYPE_YEAR_DOT
value = s.split(".")[0]
else if CUI.DateTimeRangeGrammar.REGEXP_CENTURY.test(s)
type = CUI.DateTimeRangeGrammar.TYPE_CENTURY
value = s.split("th")[0]
else if value in CUI.DateTimeRangeGrammar.MONTHS[locale]
type = CUI.DateTimeRangeGrammar.TYPE_MONTH
value = CUI.DateTimeRangeGrammar.MONTHS[locale].indexOf(value)
else
type = s # The type for everything else is the value.
tokens.push
type: type
value: value
stringToParse = tokens.map((token) -> token.type).join(" ").toUpperCase()
# Check if there is a grammar that applies to the input.
for _, grammars of CUI.DateTimeRangeGrammar.PARSE_GRAMMARS
for grammar in grammars
if grammar[0].toUpperCase() == stringToParse
method = CUI.DateTimeRangeGrammar[grammar[1]]
if not CUI.util.isFunction(method) or not grammar[2]
continue
tokenPositions = grammar[2]
if CUI.util.isArray(tokenPositions)
if tokenPositions.length == 0
continue
methodArguments = tokenPositions.map((index) -> tokens[index].value)
else
methodArguments = [tokenPositions]
if extraArguments = grammar[3]
if CUI.util.isArray(extraArguments)
methodArguments = methodArguments.concat(extraArguments)
else
methodArguments.push(extraArguments)
value = method.apply(@, methodArguments)
if value
return value
# If there is no grammar available, we try to parse the date.
[from, to] = input.split(/\s+\-\s+/)
if from and to
output = CUI.DateTimeRangeGrammar.range(from, to)
if output
return output
output = CUI.DateTimeRangeGrammar.getFromTo(from)
if output
return output
return error: "NoDateRangeFound #{input}"
@millennium: (millennium, isBC) ->
if isBC
from = -(millennium * 1000 - 1)
to = -((millennium - 1) * 1000)
else
to = millennium * 1000
from = to - 999
return CUI.DateTimeRangeGrammar.getFromToWithRange("#{from}", "#{to}")
@century: (century, isBC) ->
century = century * 100
if isBC
to = -(century - 100)
from = -century + 1
else
to = century
from = century - 99
return CUI.DateTimeRangeGrammar.getFromToWithRange("#{from}", "#{to}")
@centuryRange: (centuryFrom, centuryTo, fromIsBC, toIsBC) ->
from = @century(centuryFrom, fromIsBC)
to = @century(centuryTo, toIsBC)
return from: from?.from, to: to?.to
# 15 -> 1401 - 1416
# 15 -> 1499 1484
@earlyCentury: (century, isBC) ->
century = century * 100
if isBC
from = -century + 1
to = from + 15
else
from = century - 99
to = from + 15
return CUI.DateTimeRangeGrammar.getFromToWithRange("#{from}", "#{to}")
# 15 - -1416 -1401
# 15 - 1484 - 1499
@lateCentury: (century, isBC) ->
century = century * 100
if isBC
to = -(century - 101)
from = to - 15
else
to = century
from = to - 15
return CUI.DateTimeRangeGrammar.getFromToWithRange("#{from}", "#{to}")
@range: (from, to, fromBC = false, toBC = false) ->
if toBC and not to.startsWith(CUI.DateTimeRangeGrammar.DASH)
to = @__toBC(to)
if (fromBC or toBC) and not from.startsWith(CUI.DateTimeRangeGrammar.DASH)
from = @__toBC(from)
return CUI.DateTimeRangeGrammar.getFromToWithRange(from, to)
@monthRange: (month, year) ->
momentDate = CUI.DateTimeRangeGrammar.getMoment(year)
momentDate.month(month)
momentDate.startOf("month")
from = CUI.DateTimeRangeGrammar.format(momentDate, false)
momentDate.endOf("month")
to= CUI.DateTimeRangeGrammar.format(momentDate, false)
return from: from, to: to
@yearRange: (year, isBC = false, fromAddYears = false, toAddYears = false) ->
if isBC and not year.startsWith(CUI.DateTimeRangeGrammar.DASH)
year = "-#{year}"
momentInputFrom = CUI.DateTimeRangeGrammar.getMoment(year)
if not momentInputFrom?.isValid()
return
if not year.startsWith(CUI.DateTimeRangeGrammar.DASH)
momentInputFrom.add(1, "day") # This is a workaround to avoid having the wrong year after parsing the timezone.
momentInputFrom.parseZone()
if fromAddYears or toAddYears
_year = momentInputFrom.year()
if _year % 1000 == 0
yearsToAdd = 500
else if _year % 100 == 0
yearsToAdd = 50
else if _year % 50 == 0
yearsToAdd = 15
else if _year % 10 == 0
yearsToAdd = 5
else
yearsToAdd = 2
momentInputTo = momentInputFrom.clone()
if fromAddYears
momentInputFrom.add(-yearsToAdd, "year")
if toAddYears
momentInputTo.add(yearsToAdd, "year")
if not year.startsWith(CUI.DateTimeRangeGrammar.DASH)
momentInputTo.add(1, "day")
momentInputTo.parseZone()
momentInputFrom.startOf("year")
momentInputTo.endOf("year")
from = CUI.DateTimeRangeGrammar.format(momentInputFrom)
to = CUI.DateTimeRangeGrammar.format(momentInputTo)
return from: from, to: to
@getFromTo: (inputString, isBC = false) ->
if isBC and not inputString.startsWith(CUI.DateTimeRangeGrammar.DASH)
inputString = @__toBC(inputString)
momentInput = CUI.DateTimeRangeGrammar.getMoment(inputString)
if not momentInput?.isValid()
return
if inputString.match(CUI.DateTimeRangeGrammar.REGEXP_YEAR)
if not inputString.startsWith(CUI.DateTimeRangeGrammar.DASH)
momentInput.add(1, "day")
momentInput.parseZone()
from = to = CUI.DateTimeRangeGrammar.format(momentInput)
else if inputString.match(CUI.DateTimeRangeGrammar.REGEXP_MONTH)
from = CUI.DateTimeRangeGrammar.format(momentInput, false)
momentInput.endOf('month');
to = CUI.DateTimeRangeGrammar.format(momentInput, false)
else
from = to = CUI.DateTimeRangeGrammar.format(momentInput, false)
return from: from, to: to
@getFromToWithRange: (fromDate, toDate) ->
from = CUI.DateTimeRangeGrammar.getFromTo(fromDate)
to = CUI.DateTimeRangeGrammar.getFromTo(toDate)
if not from or not to
return
return from: from.from, to: to.to
@format: (dateMoment, yearFormat = true) ->
if yearFormat
outputType = CUI.DateTimeRangeGrammar.OUTPUT_YEAR
else
outputType = CUI.DateTimeRangeGrammar.OUTPUT_DATE
return CUI.DateTime.format(dateMoment, CUI.DateTimeRangeGrammar.STORE_FORMAT, outputType)
@getMoment: (inputString) ->
if not CUI.util.isString(inputString)
return
dateTime = new CUI.DateTime()
momentInput = dateTime.parseValue(inputString);
if !momentInput.isValid() and inputString.startsWith(DateTimeRangeGrammar.DASH)
# This is a workaround for moment.js when strings are like: "-2020-11-05T10:00:00+00:00" or "-0100-01-01"
# Moment js does not support negative full dates, therefore we create a moment without the negative character
# and then we make the year negative.
inputString = inputString.substring(1)
momentInput = dateTime.parseValue(inputString);
momentInput.year(-momentInput.year())
dateTime.destroy()
return momentInput
@__toBC: (inputString) ->
if inputString.match(CUI.DateTimeRangeGrammar.REGEXP_YEAR)
inputString = parseInt(inputString) - 1
return "-#{inputString}" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.